package odera.projects.appointmentssoftware.services; import java.nio.charset.StandardCharsets; import java.security.spec.KeySpec; import java.util.Base64; import javax.crypto.*; import javax.crypto.spec.DESedeKeySpec; public class EncryptionDecryptionDES { private static final String DESEDE_ENCRYPTION_SCHEME = "DESede"; private final Cipher cipher; private final SecretKey key; public EncryptionDecryptionDES(String password) throws Exception { //key has to be at least 24 bytes long if(password.length() < 24) { StringBuilder passwordBuilder = new StringBuilder(password); while (passwordBuilder.length() < 24) { passwordBuilder.append(" "); } password = passwordBuilder.toString(); } byte[] arrayBytes = password.getBytes(StandardCharsets.UTF_8); KeySpec keySpec = new DESedeKeySpec(arrayBytes); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(DESEDE_ENCRYPTION_SCHEME); cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME); key = secretKeyFactory.generateSecret(keySpec); } public String encrypt(String plainText) throws Exception { byte[] plainTextByte = plainText.getBytes(); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptedByte = cipher.doFinal(plainTextByte); Base64.Encoder encoder = Base64.getEncoder(); return encoder.encodeToString(encryptedByte); } // public String decrypt(String encryptedText) // throws Exception { // Base64.Decoder decoder = Base64.getDecoder(); // byte[] encryptedTextByte = decoder.decode(encryptedText); // cipher.init(Cipher.DECRYPT_MODE, key); // byte[] decryptedByte = cipher.doFinal(encryptedTextByte); // return new String(decryptedByte); // } }