|
1 | 1 | package io.sentrius.sso.core.security.service; |
2 | 2 |
|
3 | 3 | import javax.crypto.Cipher; |
| 4 | +import javax.crypto.spec.GCMParameterSpec; |
4 | 5 | import javax.crypto.spec.SecretKeySpec; |
5 | 6 | import java.io.IOException; |
6 | 7 | import java.nio.charset.StandardCharsets; |
@@ -30,7 +31,7 @@ public class CryptoService { |
30 | 31 | final ApplicationKeyRepository applicationKeyRepository; |
31 | 32 | private final byte[] key; |
32 | 33 |
|
33 | | - private static final String CIPHER_INSTANCE = "AES/ECB/PKCS5Padding"; |
| 34 | + private static final String CIPHER_INSTANCE = "AES/GCM/NoPadding"; |
34 | 35 | private static final String CRYPT_ALGORITHM = "AES"; |
35 | 36 | private static final String HASH_ALGORITHM = "SHA-256"; |
36 | 37 | private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(); |
@@ -65,16 +66,28 @@ public String hash(String str, String salt) throws NoSuchAlgorithmException { |
65 | 66 |
|
66 | 67 | public String encrypt(String str) throws GeneralSecurityException { |
67 | 68 | Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE); |
68 | | - cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, CRYPT_ALGORITHM)); |
| 69 | + byte[] iv = new byte[12]; |
| 70 | + new SecureRandom().nextBytes(iv); |
| 71 | + GCMParameterSpec gcmSpec = new GCMParameterSpec(128, iv); |
| 72 | + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, CRYPT_ALGORITHM), gcmSpec); |
69 | 73 | byte[] encVal = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)); |
70 | | - return Base64.getEncoder().encodeToString(encVal); |
| 74 | + byte[] encryptedIvAndText = new byte[iv.length + encVal.length]; |
| 75 | + System.arraycopy(iv, 0, encryptedIvAndText, 0, iv.length); |
| 76 | + System.arraycopy(encVal, 0, encryptedIvAndText, iv.length, encVal.length); |
| 77 | + return Base64.getEncoder().encodeToString(encryptedIvAndText); |
71 | 78 | } |
72 | 79 |
|
73 | 80 | public String encrypt(byte [] bytes) throws GeneralSecurityException { |
74 | 81 | Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE); |
75 | | - cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, CRYPT_ALGORITHM)); |
| 82 | + byte[] iv = new byte[12]; |
| 83 | + new SecureRandom().nextBytes(iv); |
| 84 | + GCMParameterSpec gcmSpec = new GCMParameterSpec(128, iv); |
| 85 | + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, CRYPT_ALGORITHM), gcmSpec); |
76 | 86 | byte[] encVal = cipher.doFinal(bytes); |
77 | | - return Base64.getEncoder().encodeToString(encVal); |
| 87 | + byte[] encryptedIvAndText = new byte[iv.length + encVal.length]; |
| 88 | + System.arraycopy(iv, 0, encryptedIvAndText, 0, iv.length); |
| 89 | + System.arraycopy(encVal, 0, encryptedIvAndText, iv.length, encVal.length); |
| 90 | + return Base64.getEncoder().encodeToString(encryptedIvAndText); |
78 | 91 | } |
79 | 92 |
|
80 | 93 | public String decrypt(String encryptedStr) throws GeneralSecurityException { |
|
0 commit comments