Created
July 7, 2014 02:29
-
-
Save yinheli/fb7420d07db2e235da31 to your computer and use it in GitHub Desktop.
AES/ECB/PKCS5Padding
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
import sun.misc.BASE64Decoder; | |
import sun.misc.BASE64Encoder; | |
import javax.crypto.Cipher; | |
import javax.crypto.spec.SecretKeySpec; | |
/** | |
* @author yinheli | |
*/ | |
public class AESUtil { | |
private static final String ALGORITHM = "AES"; | |
private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding"; | |
private SecretKeySpec key; | |
public AESUtil(String hexKey) { | |
key = new SecretKeySpec(hex2byte(hexKey), ALGORITHM); | |
} | |
public String encryptData(String data) throws Exception { | |
Cipher cipher = Cipher.getInstance(ALGORITHM_STR); | |
cipher.init(Cipher.ENCRYPT_MODE, key); | |
return new BASE64Encoder().encode(cipher.doFinal(data.getBytes())); | |
} | |
public String decryptData(String base64Data) throws Exception{ | |
Cipher cipher = Cipher.getInstance(ALGORITHM_STR); | |
cipher.init(Cipher.DECRYPT_MODE, key); | |
return new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(base64Data))); | |
} | |
private static byte[] hex2byte(String s) { | |
if (s.length() % 2 == 0) { | |
return hex2byte (s.getBytes(), 0, s.length() >> 1); | |
} else { | |
return hex2byte("0"+s); | |
} | |
} | |
private static byte[] hex2byte (byte[] b, int offset, int len) { | |
byte[] d = new byte[len]; | |
for (int i=0; i<len*2; i++) { | |
int shift = i%2 == 1 ? 0 : 4; | |
d[i>>1] |= Character.digit((char) b[offset+i], 16) << shift; | |
} | |
return d; | |
} | |
public static void main(String[] args) throws Exception { | |
AESUtil util = new AESUtil("31323334353637383930313233343539"); | |
System.out.println("cardNo:"+util.encryptData("4205190000000001")); | |
System.out.println("exp:"+util.encryptData("201501")); | |
System.out.println("csc:"+util.encryptData("123")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment