Java Code Examples for java.security.MessageDigest

The following are top voted examples for showing how to use java.security.MessageDigest. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: WhiteRabbit   File: StringUtilities.java View source code 7 votes vote down vote up
/**
 * Get hex string interpretation of the 16-byte MD5 hash for an input string Author: Kristina
 */
public static String getMD5Digest(String str) {
	try {
		byte[] buffer = str.getBytes();
		byte[] result = null;
		StringBuffer buf = null;
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		// allocate room for the hash
		result = new byte[md5.getDigestLength()];
		// calculate hash
		md5.reset();
		md5.update(buffer);
		
		result = md5.digest();
		// System.out.println(result);
		// create hex string from the 16-byte hash
		buf = new StringBuffer(result.length * 2);
		for (int i = 0; i < result.length; i++) {
			int intVal = result[i] & 0xff;
			if (intVal < 0x10) {
				buf.append("0");
			}
			buf.append(Integer.toHexString(intVal).toUpperCase());
		}
		return buf.toString();
	} catch (NoSuchAlgorithmException e) {
		System.err.println("Exception caught: " + e);
		e.printStackTrace();
		
	}
	return null;
}
 
Example 2
Project: HBase-Research   File: HBaseTestingUtility.java View source code 7 votes vote down vote up
/**
 * Return an md5 digest of the entire contents of a table.
 */
public String checksumRows(final HTable table) throws Exception {
  Scan scan = new Scan();
  ResultScanner results = table.getScanner(scan);
  MessageDigest digest = MessageDigest.getInstance("MD5");
  for (Result res : results) {
    digest.update(res.getRow());
  }
  results.close();
  return digest.toString();
}
 
Example 3
Project: lettuce   File: RedisAsyncConnectionImpl.java View source code 6 votes vote down vote up
@Override
public String digest(V script) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.update(codec.encodeValue(script));
        return new String(Base16.encode(md.digest(), false));
    } catch (NoSuchAlgorithmException e) {
        throw new RedisException("JVM does not support SHA1");
    }
}
 
Example 4
Project: sslcertx   File: App.java View source code 6 votes vote down vote up
public static String getFingerprint(X509Certificate cert)
		throws NoSuchAlgorithmException, CertificateEncodingException {
	MessageDigest md = MessageDigest.getInstance("SHA-1");
	byte[] der = cert.getEncoded();
	md.update(der);
	byte[] digest = md.digest();
	String hex = Hex.encodeHexString(digest).toUpperCase();
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < hex.length(); i++) {
		if (i > 0 && i % 2 == 0) {
			sb.append(":");
		}
		sb.append(hex.charAt(i));
	}
	return sb.toString();
}
 
Example 5
Project: netlib   File: Encryption.java View source code 6 votes vote down vote up
/**
 * returns the digest of the input
 * 
 * @param algorithm    e.g. "SHA-1"
 * @param input
 * @return digest value
 */
public static byte[] getDigest(String algorithm, byte[] input) {
    try {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        md.reset();
        md.update(input, 0, input.length);
        return md.digest();

    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Project: java-csp   File: DOMHMACSignatureMethod.java View source code 6 votes vote down vote up
@Override
boolean verify(Key key, DOMSignedInfo si, byte[] sig,
               XMLValidateContext context)
    throws InvalidKeyException, SignatureException, XMLSignatureException
{
    if (key == null || si == null || sig == null) {
        throw new NullPointerException();
    }
    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("key must be SecretKey");
    }
    if (hmac == null) {
        try {
            hmac = Mac.getInstance(getJCAAlgorithm());
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    if (outputLengthSet && outputLength < getDigestLength()) {
        throw new XMLSignatureException
            ("HMACOutputLength must not be less than " + getDigestLength());
    }
    hmac.init(key);
    si.canonicalize(context, new MacOutputStream(hmac));
    byte[] result = hmac.doFinal();

    return MessageDigest.isEqual(sig, result);
}
 
Example 7
Project: netlib   File: Encryption.java View source code 6 votes vote down vote up
/**
 * Calculate the digest but do not touch md.
 * 
 * @param md
 * @return the digest, calculated with a clone of md
 */
public static byte[] intermediateDigest(MessageDigest md) {
    try {
        // ugly fix around the behavior on digests
        MessageDigest mdClone = (MessageDigest)md.clone();
        return mdClone.digest();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Project: nuCommander   File: CalculateChecksumDialog.java View source code 6 votes vote down vote up
public void actionPerformed(ActionEvent e) {
    // Start by disposing this dialog
    dispose();

    if(e.getSource()==okButton) {
        try {
            MessageDigest digest = getSelectedMessageDigest();
            String algorithm = digest.getAlgorithm();
            AbstractFile checksumFile;

            // Resolve the destination checksum file

            if(specificLocationRadioButton.isSelected()) {
                // User-defined checksum file
                String enteredPath = specificLocationTextField.getText();

                PathUtils.ResolvedDestination resolvedDest = PathUtils.resolveDestination(enteredPath, mainFrame.getActiveTable().getCurrentFolder());
                // The path entered doesn't correspond to any existing folder
                if (resolvedDest==null) {
                    showErrorDialog(Translator.get("invalid_path", enteredPath));
                    return;
                }

                if(resolvedDest.getDestinationType()==PathUtils.ResolvedDestination.EXISTING_FOLDER)
                    checksumFile = resolvedDest.getDestinationFile().getDirectChild(getChecksumFilename(algorithm));
                else
                    checksumFile = resolvedDest.getDestinationFile();
            }
            else {
                // Temporary file
                checksumFile = FileFactory.getTemporaryFile(getChecksumFilename(algorithm), true);
            }

            // Save the algorithm that was used for the next time this dialog is invoked
            lastUsedAlgorithm = algorithm; 

            // Start processing files
            ProgressDialog progressDialog = new ProgressDialog(mainFrame, Translator.get("properties_dialog.calculating"));
            CalculateChecksumJob job = new CalculateChecksumJob(progressDialog, mainFrame, files, checksumFile, digest);
            progressDialog.start(job);
        }
        catch(IOException ex) {
            // Note: FileFactory.getTemporaryFile() should never throw an IOException

            showErrorDialog(Translator.get("invalid_path", specificLocationTextField.getText()));
        }
    }
}