用Java写一个加密和解密的代码
时间: 2023-05-23 15:00:37 浏览: 111
Java加密&解密代码
好的,我可以帮您编写一个Java的加密和解密代码。加密与解密可以用对称加密方式实现,比如AES加密算法。您需要输入要加密的明文消息和密钥,然后程序会输出加密后的密文。同样,您也可以输入密文和密钥来解密消息。以下是简单的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class Encryption {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
public static String encrypt(String plainText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(cipherText);
}
public static String decrypt(String cipherText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(plainText);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
String key = "my-secure-key";
String encryptedText = encrypt(plainText, key);
System.out.println("Encrypted text: " + encryptedText);
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted text: " + decryptedText);
}
}
```
需要注意的是,暴力破解加密密文是一种不道德而且可能不合法的行为,请谨慎使用加密技术,以保护您和他人的隐私。
阅读全文