使用AES-256 Java加密

Ger*_*era 9 java encryption base64 aes

我有这个简单的代码,我在互联网上找到..我正在学习这个加密/解密的东西..这段代码似乎工作正常,但我不明白的东西......为什么在"c.doFinal()之后"(用于使用AES-256加密/解密)这个人使用BASE64编码/解码该加密值?仅使用AES还不够?

`private static final String ALGO = "AES";
 private static final byte[] keyValue = 
 new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };


 public static String encrypt(String Data) throws Exception {
    Key key = generateKey();
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.ENCRYPT_MODE, key);
    byte[] encVal = c.doFinal(Data.getBytes());
    String encryptedValue = new BASE64Encoder().encode(encVal);
    return encryptedValue;
}

public static String decrypt(String encryptedData) throws Exception {
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
    byte[] decValue = c.doFinal(decordedValue);
    String decryptedValue = new String(decValue);
    return decryptedValue;
}
private static Key generateKey() throws Exception {
    Key key = new SecretKeySpec(keyValue, ALGO);
    return key;
}

public static void main(String[] args) throws Exception {

    String data = "SOME TEXT";
    String dataEnc = AES.encrypt(data);
    String dataDec = AES.decrypt(dataEnc);

    System.out.println("Plain Text : " + data);
    System.out.println("Encrypted Text : " + dataEnc);
    System.out.println("Decrypted Text : " + dataDec);
}`
Run Code Online (Sandbox Code Playgroud)

谢谢!!

Syo*_*yon 9

返回的加密数据doFinal是二进制的,因此无法打印(它看起来像是一堆乱码.)Base64编码将二进制文件转换为一组ASCII字符,这使得它易于阅读并且还可以在只能使用明文数据的情况下使用加密数据.

Base64编码不会添加任何额外的加密或安全性,它只会使加密数据在您无法使用二进制文件的情况下可用.