pbkdf2加密解密java
时间: 2023-11-20 13:55:01 浏览: 37
PBKDF2是一种密码学中的密钥派生函数,它可以将一个较弱的密码转换为一个强密钥,从而增加密码的安全性。在Java中,可以使用javax.crypto.SecretKeyFactory类来实现PBKDF2算法的加密和解密。
下面是一个简单的Java代码示例,演示如何使用PBKDF2算法进行加密和解密:
```java
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.spec.KeySpec;
import java.util.Arrays;
public class PBKDF2Example {
public static void main(String[] args) throws Exception {
String password = "myPassword123";
byte[] salt = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
int iterations = 10000;
int keyLength = 256;
// 加密
byte[] encrypted = encrypt(password, salt, iterations, keyLength);
System.out.println("Encrypted: " + Arrays.toString(encrypted));
// 解密
boolean isMatch = decrypt(password, salt, iterations, keyLength, encrypted);
System.out.println("Is match: " + isMatch);
}
public static byte[] encrypt(String password, byte[] salt, int iterations, int keyLength) throws Exception {
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, keyLength);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
return factory.generateSecret(spec).getEncoded();
}
public static boolean decrypt(String password, byte[] salt, int iterations, int keyLength, byte[] encrypted) throws Exception {
byte[] decrypted = encrypt(password, salt, iterations, keyLength);
return Arrays.equals(encrypted, decrypted);
}
}
```
在上面的代码中,encrypt()方法使用PBKDF2算法对密码进行加密,decrypt()方法使用相同的算法对密码进行解密,并比较解密后的结果是否与加密前的密码相同。