|
@@ -1,9 +1,10 @@
|
|
|
package com.danielbohry.stocks.service;
|
|
package com.danielbohry.stocks.service;
|
|
|
|
|
|
|
|
-import com.danielbohry.stocks.repository.portfolio.PortfolioEntity;
|
|
|
|
|
|
|
+import com.danielbohry.stocks.exception.DecryptionKeyException;
|
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
|
|
|
|
+import javax.crypto.BadPaddingException;
|
|
|
import javax.crypto.Cipher;
|
|
import javax.crypto.Cipher;
|
|
|
import javax.crypto.spec.IvParameterSpec;
|
|
import javax.crypto.spec.IvParameterSpec;
|
|
|
import javax.crypto.spec.SecretKeySpec;
|
|
import javax.crypto.spec.SecretKeySpec;
|
|
@@ -40,27 +41,24 @@ public class EncryptService {
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public String decrypt(String encryptedData) throws Exception {
|
|
public String decrypt(String encryptedData) throws Exception {
|
|
|
- SecretKeySpec key = getSecretKey();
|
|
|
|
|
|
|
+ try {
|
|
|
|
|
+ SecretKeySpec key = getSecretKey();
|
|
|
|
|
|
|
|
- byte[] combined = Base64.getDecoder().decode(encryptedData);
|
|
|
|
|
- byte[] iv = new byte[IV_LENGTH];
|
|
|
|
|
- byte[] encrypted = new byte[combined.length - IV_LENGTH];
|
|
|
|
|
|
|
+ byte[] combined = Base64.getDecoder().decode(encryptedData);
|
|
|
|
|
+ byte[] iv = new byte[IV_LENGTH];
|
|
|
|
|
+ byte[] encrypted = new byte[combined.length - IV_LENGTH];
|
|
|
|
|
|
|
|
- System.arraycopy(combined, 0, iv, 0, IV_LENGTH);
|
|
|
|
|
- System.arraycopy(combined, IV_LENGTH, encrypted, 0, encrypted.length);
|
|
|
|
|
|
|
+ System.arraycopy(combined, 0, iv, 0, IV_LENGTH);
|
|
|
|
|
+ System.arraycopy(combined, IV_LENGTH, encrypted, 0, encrypted.length);
|
|
|
|
|
|
|
|
- Cipher cipher = Cipher.getInstance(ALGORITHM);
|
|
|
|
|
- cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
|
|
|
|
|
-
|
|
|
|
|
- byte[] decrypted = cipher.doFinal(encrypted);
|
|
|
|
|
- return new String(decrypted, StandardCharsets.UTF_8);
|
|
|
|
|
- }
|
|
|
|
|
|
|
+ Cipher cipher = Cipher.getInstance(ALGORITHM);
|
|
|
|
|
+ cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
|
|
|
|
|
|
|
|
- public boolean isEncrypted(PortfolioEntity entity) {
|
|
|
|
|
- return entity != null &&
|
|
|
|
|
- entity.getEncryptedStocks() != null &&
|
|
|
|
|
- !entity.getEncryptedStocks().isEmpty() &&
|
|
|
|
|
- (entity.getStocks() == null || entity.getStocks().isEmpty());
|
|
|
|
|
|
|
+ byte[] decrypted = cipher.doFinal(encrypted);
|
|
|
|
|
+ return new String(decrypted, StandardCharsets.UTF_8);
|
|
|
|
|
+ } catch (BadPaddingException e) {
|
|
|
|
|
+ throw new DecryptionKeyException("Cannot decrypt data", e);
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
private SecretKeySpec getSecretKey() {
|
|
private SecretKeySpec getSecretKey() {
|