Java Aes-CBC加密,用JAVA原生的lib做的加密解密示例,这里需要注意的是,加密的结果需要转换一下格式
// private static String sKey="123456";
private static final byte[] INIT_VECTOR = { 0x31, 0x37, 0x36, 0x35,
0x34, 0x33, 0x32, 0x31,
0x38, 0x27, 0x36, 0x35,
0x33, 0x23, 0x32, 0x33 };
public static String encrypt(String sSrc, String sKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return byteToHexString(encrypted);
}
public static String decrypt(String sSrc, String sKey) throws Exception {
try {
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR);
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = hexToBytes(sSrc);
byte[] original = cipher.doFinal(encrypted1);
return new String(hexToBytes(byteToHexString(original)));
} catch (Exception ex) {
return null;
}
}
public static String byteToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer(bytes.length);
String sTemp;
for (int i = 0; i < bytes.length; i++) {
sTemp = Integer.toHexString(0xFF & bytes[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toLowerCase());
}
return sb.toString();
}
public static byte[] hexToBytes(String s) {
s = s.toUpperCase();
int len = s.length() / 2;
int ii = 0;
byte[] bs = new byte[len];
char c;
int h;
for (int i = 0; i < len; i++) {
c = s.charAt(ii++);
if (c <= '9') {
h = c - '0';
} else {
h = c - 'A' + 10;
}
h <<= 4;
c = s.charAt(ii++);
if (c <= '9') {
h |= c - '0';
} else {
h |= c - 'A' + 10;
}
bs[i] = (byte) h;
}
return bs;
}