淘先锋技术网

首页 1 2 3 4 5 6 7

Java是一种广泛使用的编程语言,支持多种加密算法。其中,AES(高级加密标准)是一种高度安全和广泛使用的对称加密算法。在Java中,我们可以使用AES128和AES256对数据进行加密和解密。

要使用AES加密,我们需要导入Java提供的加密库javax.crypto。下面是一个使用AES128进行加密和解密的示例:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
private static final String ALGORITHM = "AES";
public static byte[] encrypt(byte[] key, byte[] data) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] key, byte[] encryptedData) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
return cipher.doFinal(encryptedData);
}
public static byte[] generateKey128() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(128);
SecretKey key = keyGenerator.generateKey();
return key.getEncoded();
}
}

上面的代码中,我们首先定义了一个私有常量ALGORITHM表示加密算法(这里是AES),然后通过encrypt方法和decrypt方法分别对数据进行加密和解密。generateKey128方法用于生成一个128位的随机密钥。

要使用AES256进行加密和解密,我们只需要将KeyGenerator初始化为256即可。下面是一个使用AES256进行加密和解密的示例:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AES256Util {
private static final String ALGORITHM = "AES";
public static byte[] encrypt(byte[] key, byte[] data) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] key, byte[] encryptedData) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
return cipher.doFinal(encryptedData);
}
public static byte[] generateKey256() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(256);
SecretKey key = keyGenerator.generateKey();
return key.getEncoded();
}
}

上面的代码与之前的示例类似,只是将KeyGenerator的初始化改为了256位。这样就可以使用AES256对数据进行加密和解密了。