Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.72 KB | None | 0 0
  1. import javax.crypto.*;
  2. import javax.crypto.spec.GCMParameterSpec;
  3. import java.nio.ByteBuffer;
  4. import java.nio.charset.StandardCharsets;
  5. import java.security.InvalidAlgorithmParameterException;
  6. import java.security.InvalidKeyException;
  7. import java.security.NoSuchAlgorithmException;
  8. import java.util.Base64;
  9.  
  10. public class AES {
  11.  
  12. public String encrypt(String msg, SecretKey key, byte[] iv) {
  13.  
  14. byte[] cipher;
  15.  
  16. try {
  17. Cipher encryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
  18.  
  19. GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv);
  20.  
  21. System.out.format("Key bits: %d\n", key.getEncoded().length * 8);
  22. encryptionCipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
  23.  
  24. byte[] bytes = msg.getBytes();
  25.  
  26. cipher = encryptionCipher.doFinal(bytes);
  27. ByteBuffer byteBuffer = ByteBuffer.allocate(4 + iv.length + cipher.length);
  28. byteBuffer.putInt(iv.length);
  29. byteBuffer.put(iv);
  30. byteBuffer.put(cipher);
  31. cipher = byteBuffer.array();
  32. cipher = Base64.getEncoder().encode(cipher);
  33.  
  34. return new String(cipher, StandardCharsets.UTF_8);
  35. } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
  36.  
  37. System.out.format("Error: %s\n", e.getMessage());
  38. e.printStackTrace();
  39. } catch (InvalidAlgorithmParameterException e) {
  40. e.printStackTrace();
  41. }
  42.  
  43. return null;
  44. }
  45.  
  46. public String decrypt(String cipher, SecretKey key) {
  47. byte[] msg;
  48.  
  49. try {
  50. byte[] bytes = Base64.getDecoder().decode(cipher);
  51. ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
  52. int ivLength = byteBuffer.getInt();
  53. if(ivLength < 12 || ivLength >= 16) { // check input parameter
  54. throw new IllegalArgumentException("invalid iv length");
  55. }
  56. byte[] iv = new byte[ivLength];
  57. byteBuffer.get(iv);
  58. byte[] cipherText = new byte[byteBuffer.remaining()];
  59. byteBuffer.get(cipherText);
  60.  
  61.  
  62. Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
  63. GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv);
  64. decryptionCipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
  65.  
  66. msg = decryptionCipher.doFinal(cipherText);
  67.  
  68. return new String(msg, StandardCharsets.UTF_8);
  69. } catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException e) {
  70. e.printStackTrace();
  71. }
  72.  
  73. return null;
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement