AES暗号化と復号化のケース
AES暗号化および復号化ツールクラス:
AESテスト:
実行結果:
暗号化:�q&sUKva�9 N�復号:13.2
/**
* AES 、
*
* @author
*
*/
public class AESUtils {
static String password = "niuba123";
static int keysiz = 128;
static String algorithmStr = "AES";
/**
*
*
* @param content
*
* @return
*/
public static byte[] encryptByAES(String content) {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithmStr);
keyGenerator.init(keysiz, new SecureRandom(password.getBytes()));
SecretKey secretKey = keyGenerator.generateKey();
byte[] encyptFormat = secretKey.getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(encyptFormat,
algorithmStr);
Cipher cipher = Cipher.getInstance(algorithmStr);//
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);//
byte[] result = cipher.doFinal(byteContent);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] decrypt(byte[] content) {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithmStr);
keyGenerator.init(keysiz, new SecureRandom(password.getBytes()));
SecretKey secretKey = keyGenerator.generateKey();
byte[] encryptFormat = secretKey.getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(encryptFormat,
algorithmStr);
Cipher cipher = Cipher.getInstance(algorithmStr);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
AESテスト:
public static void main(String[] args) {
try {
String testStr = "13.2";
byte[] bytes = AESUtils.encryptByAES(testStr);
System.out.println(" :"+new String(bytes, "utf-8"));
byte[] bytes2 = AESUtils.decrypt(bytes);
System.out.println(" :"+new String(bytes2,"utf-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
実行結果:
暗号化:�q&sUKva�9 N�復号:13.2