请帮我用Java写一个将密码加密和解密的算法,密码最多16位,加密后的字符串最多64位
时间: 2024-04-01 09:32:05 浏览: 16
好的,我可以为你提供一个基于AES对称加密算法的Java实现,可以将密码加密和解密。以下是示例代码:
```
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class PasswordEncryptorDecryptor {
private static final String ALGORITHM = "AES";
private static final String KEY = "mysecretpassword"; // 密钥,必须是16个字符
public static String encrypt(String password) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encryptedBytes = cipher.doFinal(password.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedPassword) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedPassword);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
}
public static void main(String[] args) throws Exception {
String password = "mypassword";
String encryptedPassword = encrypt(password);
System.out.println("Encrypted password: " + encryptedPassword);
String decryptedPassword = decrypt(encryptedPassword);
System.out.println("Decrypted password: " + decryptedPassword);
}
}
```
该代码使用AES算法和Base64编码实现密码加密和解密。加密后的字符串最多64位,因为Base64编码会将原始字节序列转换为64个不同的字符。请注意,密钥必须是16个字符,因为AES算法使用128位的密钥。在实际应用中,请务必使用更安全的密钥和算法。