admin 管理员组

文章数量: 1086019


2024年3月7日发(作者:mybatis plus github)

AES加密JAVA代码实现

AES(Advanced Encryption Standard)是一种对称加密算法,被广泛应用于网络通信和数据保护领域。下面给出一个基于Java的AES加密代码实现。

```java

import ;

import KeySpec;

import rdCharsets;

import ;

import 64;

public class AESUtil

private static final String AES_ALGORITHM = "AES";

private static final int AES_KEY_SIZE = 128;

private static final String ENCODING = "UTF-8";

//生成AES密钥

public static String generateAESKey( throws Exception

Key aesKey = teAESKey(AES_KEY_SIZE);

byte[] aesKeyBytes = oded(;

return oder(.encodeToString(aesKeyBytes);

}

//AES加密

public static String encrypt(String data, String key) throws

Exception

Cipher cipher = tance(AES_ALGORITHM);

byte[] keyBytes = oder(.decode(key);

Key aesKey = new SecretKeySpec(keyBytes, AES_ALGORITHM);

(T_MODE, aesKey);

byte[] encryptedData =

l(es(ENCODING));

return oder(.encodeToString(encryptedData);

}

//AES解密

public static String decrypt(String encryptedData, String

key) throws Exception

Cipher cipher = tance(AES_ALGORITHM);

byte[] keyBytes = oder(.decode(key);

Key aesKey = new SecretKeySpec(keyBytes, AES_ALGORITHM);

(T_MODE, aesKey);

byte[] decodedData =

oder(.decode(encryptedData);

byte[] decryptedData = l(decodedData);

return new String(decryptedData, _8);

}

//测试

public static void main(String[] args)

try

String originalData = "Hello, AES!";

String key = generateAESKey(;

String encryptedData = encrypt(originalData, key);

String decryptedData = decrypt(encryptedData, key);

n("Original Data: " + originalData);

n("AES Key: " + key);

n("Encrypted Data: " + encryptedData);

n("Decrypted Data: " + decryptedData);

} catch (Exception e)

tackTrace(;

}

}

```

上述代码实现了基本的AES加密和解密功能。关键的几个步骤如下:

1. `generateAESKey`方法用于生成AES密钥,长度为128位。生成的密钥通过Base64编码返回。

2. `encrypt`方法接受明文数据和密钥作为参数,通过AES算法对数据进行加密。首先将密钥解码为字节数组,然后使用`SecretKeySpec`类创建一个`Key`对象,最后使用`Cipher`类初始化并执行加密操作。加密后的数据通过Base64编码返回。

3. `decrypt`方法接受加密数据和密钥作为参数,通过AES算法对数据进行解密。密钥解码和`Key`对象的创建与加密步骤相同,只是在此基础上使用`Cipher`类执行解密操作。解密后的数据转换为字符串并返回。

此外,为了方便测试,`main`方法调用了上述方法进行加密和解密操作,并打印了结果。

需要注意的是,上述代码仅作为示例,实际使用中还需注意异常处理、密钥管理等安全性相关问题。


本文标签: 密钥 加密 数据 方法 作为