Сделал шифрование для некоторой информации, но мне кажется что этот код можно написать намного лучше
Есть вот такой код
package com.cargodelivery.cargodelivery.services.cryptography;
import org.springframework.stereotype.Service;
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
@Service
public class EncryptDataAESImpl implements EncryptDataAES {
private SecretKey secretKey;
private final int T_LEN = 128;
private final int KEY_SIZE = 128;
private Cipher encryptCipher;
@Override
public String encryptDataValue(String value) {
secretKey = init();
return encrypt(value);
}
@Override
public SecretKey init() {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(KEY_SIZE);
return keyGenerator.generateKey();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
@Override
public String encrypt(String value) {
byte[] messageBytes = value.getBytes();
try {
encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptBytes = encryptCipher.doFinal(messageBytes);
return encode(encryptBytes);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
IllegalBlockSizeException | BadPaddingException e) {
throw new RuntimeException("Ошибка во время шифрования!");
}
}
@Override
public String decrypt(String value) {
byte[] messageBytes = decode(value);
try {
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
GCMParameterSpec spec = new GCMParameterSpec(T_LEN, decode(value.substring(0, encryptCipher.getBlockSize())));
decryptCipher.init(Cipher.DECRYPT_MODE, secretKey, spec);
byte[] decryptBytes = decryptCipher.doFinal(messageBytes);
return new String(decryptBytes);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
BadPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException e) {
throw new RuntimeException("Ошибка во время шифрования!");
}
}
@Override
public String encode(byte[] data) {
return Base64.getEncoder().encodeToString(data);
}
@Override
public byte[] decode(String data) {
return Base64.getDecoder().decode(data);
}
}
Как его можно улучшить? В плане читаемости и подобного. Вроде работает, но кажется что можно сделать получше