Security & Cryptography
Compute Cryptographic Hashes
To compute the hashes of relatively small blocks of data using different algorithms:
final MessageDigest md5 = MessageDigest.getInstance("MD5");
final MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
final MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
final byte[] data = "FOO BAR".getBytes();
System.out.println("MD5 hash: " + DatatypeConverter.printHexBinary(md5.digest(data)));
System.out.println("SHA1 hash: " + DatatypeConverter.printHexBinary(sha1.digest(data)));
System.out.println("SHA256 hash: " + DatatypeConverter.printHexBinary(sha256.digest(data)));
Produces this output:
MD5 hash: E99E768582F6DD5A3BA2D9C849DF736E
SHA1 hash: 0135FAA6323685BA8A8FF8D3F955F0C36949D8FB
SHA256 hash: 8D35C97BCD902B96D1B551741BBE8A7F50BB5A690B4D0225482EAA63DBFB9DED
Additional algorithms may be available depending on your implementation of the Java platform.
Generate Cryptographically Random Data
To generate samples of cryptographically random data:
final byte[] sample = new byte[16];
new SecureRandom().nextBytes(sample);
System.out.println("Sample: " + DatatypeConverter.printHexBinary(sample));
Produces output similar to:
Sample: E4F14CEA2384F70B706B53A6DF8C5EFE
Note that the call to nextBytes()
may block while entropy is gathered depending on the algorithm being used.
To specify the algorithm and provider:
final byte[] sample = new byte[16];
final SecureRandom randomness = SecureRandom.getInstance("SHA1PRNG", "SUN");
randomness.nextBytes(sample);
System.out.println("Provider: " + randomness.getProvider());
System.out.println("Algorithm: " + randomness.getAlgorithm());
System.out.println("Sample: " + DatatypeConverter.printHexBinary(sample));
Produces output similar to:
Provider: SUN version 1.8
Algorithm: SHA1PRNG
Sample: C80C44BAEB352FD29FBBE20489E4C0B9
Generate Public / Private Key Pairs
To generate key pairs using different algorithms and key sizes:
final KeyPairGenerator dhGenerator = KeyPairGenerator.getInstance("DiffieHellman");
final KeyPairGenerator dsaGenerator = KeyPairGenerator.getInstance("DSA");
final KeyPairGenerator rsaGenerator = KeyPairGenerator.getInstance("RSA");
dhGenerator.initialize(1024);
dsaGenerator.initialize(1024);
rsaGenerator.initialize(2048);
final KeyPair dhPair = dhGenerator.generateKeyPair();
final KeyPair dsaPair = dsaGenerator.generateKeyPair();
final KeyPair rsaPair = rsaGenerator.generateKeyPair();
Additional algorithms and key sizes may be available on your implementation of the Java platform.
To specify a source of randomness to use when generating the keys:
final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048, SecureRandom.getInstance("SHA1PRNG", "SUN"));
final KeyPair pair = generator.generateKeyPair();
Compute and Verify Digital Signatures
To compute a signature:
final PrivateKey privateKey = keyPair.getPrivate();
final byte[] data = "FOO BAR".getBytes();
final Signature signer = Signature.getInstance("SHA1withRSA");
signer.initSign(privateKey);
signer.update(data);
final byte[] signature = signer.sign();
Note that the signature algorithm must be compatible with the algorithm used to generate the key pair.
To verify a signature:
final PublicKey publicKey = keyPair.getPublic();
final Signature verifier = Signature.getInstance("SHA1withRSA");
verifier.initVerify(publicKey);
verifier.update(data);
System.out.println("Signature: " + verifier.verify(signature));
Produces this output:
Signature: true
Encrypt and Decrypt Data with Public / Private Keys
To encrypt data with a public key:
final Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
rsa.update(message.getBytes());
final byte[] result = rsa.doFinal();
System.out.println("Message: " + message);
System.out.println("Encrypted: " + DatatypeConverter.printHexBinary(result));
Produces output similar to:
Message: Hello
Encrypted: 5641FBB9558ECFA9ED...
Note that when creating the Cipher
object, you have to specify a transformation that is compatible with the type of key being used. (See JCA Standard Algorithm Names for a list of supported transformations.). For RSA encryption data message.getBytes()
length must be smaller than the key size. See this SO Answer for detail.
To decrypt the data:
final Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
rsa.update(cipherText);
final String result = new String(rsa.doFinal());
System.out.println("Decrypted: " + result);
Produces the following output:
Decrypted: Hello