Xét 1 ví dụ mã hóa dữ liệu như sau:
package com.mycompany;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES {
//chuỗi kí tự cần mã hóa
static String plaintext = "hello world";
//mã tự quy định trong mã hóa
static String encryptionKey = "0123456789abcdef";
public static void main(String[] args) {
try {
System.out.println("==Java==");
System.out.println("plain: " + plaintext);
byte[] cipher = encryptS5(plaintext, encryptionKey);
System.out.print("cipher: " + cipher);
for (int i = 0; i < cipher.length; i++) {
System.out.print(new Integer(cipher[i]) + " ");
}
System.out.println("");
String decrypted = decryptS5(cipher, encryptionKey);
System.out.println("decrypt: " + decrypted);
} catch (Exception e) {
e.printStackTrace();
}
}
// mã hóa với chuỗi mã hóa và key quy định bằng nhau
public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[16]));
return cipher.doFinal(plainText.getBytes("UTF-8"));
}
// giải mã với chuỗi mã hóa và key quy định bằng nhau
public static String decrypt(byte[] cipherText, String encryptionKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[16]));
return new String(cipher.doFinal(cipherText), "UTF-8");
}
// mã hóa với chuỗi mã hóa và key quy định khác nhau
public static byte[] encryptS5(String plainText, String encryptionKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[16]));
return cipher.doFinal(plainText.getBytes("UTF-8"));
}
// giải mã với chuỗi mã hóa và key quy định khác nhau
public static String decryptS5(byte[] cipherText, String encryptionKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[16]));
return new String(cipher.doFinal(cipherText), "UTF-8");
}
}
Output:
==Java==
plain: hello world
cipher: [[email protected] -94 -106 -3 111 -21 24 25 -80 94 7 -76 -70 -77 49 -100 95 -53 73 -39 -5 98 76 -85 14 42 97 24 121 -2 -84 -48
decrypt: hello