Last active
August 29, 2015 14:17
-
-
Save artjomb/fa611c84594af7f4ac31 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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