Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@artjomb
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artjomb/fa611c84594af7f4ac31 to your computer and use it in GitHub Desktop.
Save artjomb/fa611c84594af7f4ac31 to your computer and use it in GitHub Desktop.
package mytest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import org.apache.commons.codec.binary.Base64;
public class Test19EncDec {
private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
private static final byte[] KEY = "StBet9834#$10BCy".getBytes();
public static void main(String[] args) {
String pt = "5123456789012346";
String ct = encryptCreditCard(pt);
System.out.println("Recovered Plaintext: " + decryptCreditCard(ct));
System.out.println("Expected Plaintext: " + pt);
}
private static String encryptCreditCard(String ccNumber) {
Key key = new SecretKeySpec(KEY, "AES");
try {
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] ccNumberBytes = ccNumber.getBytes();
byte[] encCCNumber = c.doFinal(ccNumberBytes);
return new String(Base64.encodeBase64(encCCNumber));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String decryptCreditCard(String ciphertext) {
Key key = new SecretKeySpec(KEY, "AES");
try {
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
byte[] ccENCBytes = Base64.decodeBase64(ciphertext);
byte[] ccDECBytes = c.doFinal(ccENCBytes);
return new String(ccDECBytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment