· 6 years ago · Jun 08, 2019, 11:34 AM
1 private static SecretKey generateSessionKey() throws NoSuchAlgorithmException{
2 KeyGenerator generator = KeyGenerator.getInstance("AES");
3 return generator.generateKey();
4 }
5
6 private static byte[] encryptSessionKey(SecretKey sessionKey, Key publicKey) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
7 Cipher cipher = Cipher.getInstance("RSA");
8 cipher.init(Cipher.ENCRYPT_MODE, publicKey);
9 byte[] encodedKey = cipher.doFinal(sessionKey.getEncoded());
10 return Base64.getEncoder().encode(encodedKey);
11 }
12
13 private static SecretKey decryptSessionKey(byte[] base64EncodedKey, Key privateKey) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
14
15 Cipher cipher = Cipher.getInstance("RSA");
16 cipher.init(Cipher.DECRYPT_MODE, privateKey);
17 byte[] decodedKey = cipher.doFinal(Base64.getDecoder().decode(base64EncodedKey));
18 return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
19 }
20 public static