Skip to content

Instantly share code, notes, and snippets.

@christianroman
Created May 11, 2012 03:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianroman/2657404 to your computer and use it in GitHub Desktop.
Save christianroman/2657404 to your computer and use it in GitHub Desktop.
Generate AES secret key
public static void main(String[] args) {
String plainText = "Very secret data";
AES aesClient = new AES("client");
SecretKey AESKey = aesClient.getEncodedSecret();
RSA rsaClient = new RSA();
byte[] RSAcipher = rsaClient.EncryptSecretKey(AESKey);
String cipherData = aesClient.encryptAndSerialize(plainText);
// Assume that client sends the cipherData and RSAcipher to the server...
RSA serverRSA = new RSA();
SecretKey AESkeyServer = rsaServer.decryptAESKey(RSAcipher);
if (AESKey.equals(AESkeyServer)) System.out.println("equals");
AES aesServer = new AES();
String originalPlainText = aesServer.deserializeAndDecrypt(cipherData, AESkeyServer);
System.out.println(originalPlainText);
//voilaaa!
}
public SecretKey decryptAESKey(byte[] data) {
SecretKey key = null;
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
PBEKeySpec pbeKeySpec = new PBEKeySpec(AES.passPherase);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(AES.algorithm);
key = secretKeyFactory.generateSecret(pbeKeySpec);
} catch (Exception e) {
e.printStackTrace();
}
return key;
}
public byte[] EncryptSecretKey(SecretKey secretKey) {
Cipher cipher = null;
byte[] key = null;
try {
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
key = cipher.doFinal(secretKey.getEncoded());
} catch (Exception e) {
e.printStackTrace();
}
return key;
}
public SecretKey generateSecretKey(String password) {
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
return secretKey;
}
public SecretKey getEncodedSecret() throws Exception {
PBEKeySpec pbeKeySpec = new PBEKeySpec(passPherase);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
return secretKey;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment