Skip to content

Instantly share code, notes, and snippets.

@joeolaoye
Created March 10, 2016 10:47
Show Gist options
  • Save joeolaoye/dd6dd66c23a53e3be8cc to your computer and use it in GitHub Desktop.
Save joeolaoye/dd6dd66c23a53e3be8cc to your computer and use it in GitHub Desktop.
TripleDES Encryption Hardner and Softner
public String harden(String unencryptedString) throws NoSuchAlgorithmException, UnsupportedEncodingException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digestOfPassword = md.digest(key.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
SecretKey secretKey = new SecretKeySpec(keyBytes, "DESede");
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] plainTextBytes = unencryptedString.getBytes("utf-8");
byte[] buf = cipher.doFinal(plainTextBytes);
byte[] base64Bytes = Base64.encodeBase64(buf);
String base64EncryptedString = new String(base64Bytes);
return base64EncryptedString;
}
public String soften(String encryptedString) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
if(encryptedString == null)
{
return "";
}
byte[] message = Base64.decodeBase64(encryptedString.getBytes("utf-8"));
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digestOfPassword = md.digest(key.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
SecretKey secretKey = new SecretKeySpec(keyBytes, "DESede");
Cipher decipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment