Last active
May 6, 2019 15:35
-
-
Save cleopatra27/c71411df99988d0b314f4697f4ae34a5 to your computer and use it in GitHub Desktop.
Sample java 3DES class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TDES { | |
public static void main(String[] args) throws Exception { | |
String text = "cleopatra douglas"; | |
byte[] codedtext = new TripleDESTest().encrypt(text); | |
String decodedtext = new TripleDESTest().decrypt(codedtext); | |
System.out.println(codedtext); // a reference to an array | |
System.out.println(decodedtext); // This correctly shows "cleopatra douglas" | |
} | |
public byte[] encrypt(String message) throws Exception { | |
final MessageDigest md = MessageDigest.getInstance("md5"); | |
final byte[] digestOfPassword = md.digest("HG58YZ3CR9" | |
.getBytes("utf-8")); | |
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); | |
for (int j = 0, k = 16; j < 8;) { | |
keyBytes[k++] = keyBytes[j++]; | |
} | |
final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); | |
final IvParameterSpec iv = new IvParameterSpec(new byte[8]); | |
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); | |
cipher.init(Cipher.ENCRYPT_MODE, key, iv); | |
final byte[] plainTextBytes = message.getBytes("utf-8"); | |
final byte[] cipherText = cipher.doFinal(plainTextBytes); | |
return cipherText; | |
} | |
public String decrypt(byte[] message) throws Exception { | |
final MessageDigest md = MessageDigest.getInstance("md5"); | |
final byte[] digestOfPassword = md.digest("HG58YZ3CR9" | |
.getBytes("utf-8")); | |
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); | |
for (int j = 0, k = 16; j < 8;) { | |
keyBytes[k++] = keyBytes[j++]; | |
} | |
final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); | |
final IvParameterSpec iv = new IvParameterSpec(new byte[8]); | |
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); | |
decipher.init(Cipher.DECRYPT_MODE, key, iv); | |
final byte[] plainText = decipher.doFinal(message); | |
return new String(plainText, "UTF-8"); | |
} | |
//https://stackoverflow.com/questions/20227/how-do-i-use-3des-encryption-decryption-in-java |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment