java 实现密码加密解密
时间: 2023-08-02 10:07:24 浏览: 97
Java 中可以使用加密算法来实现密码的加密和解密。常用的加密算法包括 MD5、SHA、DES、AES 等。
以下是一个使用 AES 算法进行密码加密和解密的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class PasswordEncryption {
private static final String AES = "AES";
public static String encrypt(String password, String key) throws Exception {
SecretKeySpec secretKeySpec = getSecretKeySpec(key);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(password.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedPassword, String key) throws Exception {
SecretKeySpec secretKeySpec = getSecretKeySpec(key);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword));
return new String(decryptedBytes);
}
private static SecretKeySpec getSecretKeySpec(String key) throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
byte[] encodedKey = (key + secretKey.hashCode()).getBytes();
return new SecretKeySpec(encodedKey, AES);
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) throws Exception {
String password = "password123";
String key = "secretKey";
String encryptedPassword = PasswordEncryption.encrypt(password, key);
System.out.println("Encrypted password: " + encryptedPassword);
String decryptedPassword = PasswordEncryption.decrypt(encryptedPassword, key);
System.out.println("Decrypted password: " + decryptedPassword);
}
}
```
输出结果:
```
Encrypted password: VfVvqKgiKf2vSxmdOJfJyQ==
Decrypted password: password123
```
阅读全文