com.codacy.scoobydoo.Decryptor Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of scooby-doo-fwk Show documentation
Show all versions of scooby-doo-fwk Show documentation
Automated testing framework
package com.codacy.scoobydoo;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.util.Objects;
public class Decryptor {
private static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
private static final String UNICODE_FORMAT = "UTF8";
private final Cipher cipher;
private final SecretKey key;
public Decryptor(String encryptionKey) {
Objects.requireNonNull(encryptionKey);
if (encryptionKey.length() < 24) {
final String errorMessage = "Encryption key must have at least 24 characters.";
IllegalArgumentException exception = new IllegalArgumentException(errorMessage);
LoggingHelper.error(errorMessage, exception);
throw exception;
}
try {
byte[] arrayBytes = encryptionKey.getBytes(UNICODE_FORMAT);
DESedeKeySpec ks = new DESedeKeySpec(arrayBytes);
SecretKeyFactory skf = SecretKeyFactory.getInstance(DESEDE_ENCRYPTION_SCHEME);
key = skf.generateSecret(ks);
cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME);
} catch (Exception e) {
LoggingHelper.error("Decryptor creation failed.", e);
throw new RuntimeException(e);
}
}
public String encrypt(String unencryptedString) {
Objects.requireNonNull(unencryptedString);
String encryptedString;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
encryptedString = new String(Base64.encodeBase64(encryptedText));
} catch (Exception e) {
LoggingHelper.error("Encryption failed.", e);
throw new RuntimeException(e);
}
return encryptedString;
}
public String decrypt(String encryptedString) {
Objects.requireNonNull(encryptedString);
if(encryptedString.isBlank()) {
final String errorMessage = "Encrypted string cannot be blank.";
IllegalArgumentException exception = new IllegalArgumentException(errorMessage);
LoggingHelper.error(errorMessage, exception);
throw exception;
}
String decryptedString;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText = Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedString = new String(plainText);
} catch (Exception e) {
LoggingHelper.error("Decryption failed.", e);
throw new RuntimeException(e);
}
return decryptedString;
}
}