阅读量:0
在Ubuntu上使用Java进行加密和解密,你可以使用Java Cryptography Extension (JCE)框架。以下是一个简单的示例,展示了如何使用Java的Cipher类进行AES加密和解密。
首先,确保你已经安装了Java开发工具包(JDK)。如果没有,请访问Oracle官网下载并安装。
- 创建一个名为
EncryptionDemo.java的文件,并添加以下代码:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class EncryptionDemo {
public static void main(String[] args) throws Exception {
String originalText = "Hello, World!";
System.out.println("Original Text: " + originalText);
// 加密
String encryptedText = encrypt(originalText, "AES");
System.out.println("Encrypted Text: " + encryptedText);
// 解密
String decryptedText = decrypt(encryptedText, "AES");
System.out.println("Decrypted Text: " + decryptedText);
}
public static String encrypt(String text, String algorithm) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
keyGenerator.init(128); // 设置密钥长度
SecretKey secretKey = keyGenerator.generateKey();
byte[] encodedKey = secretKey.getEncoded();
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encodedKey, algorithm));
byte[] encryptedBytes = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String algorithm) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
keyGenerator.init(128); // 设置密钥长度
SecretKey secretKey = keyGenerator.generateKey();
byte[] encodedKey = secretKey.getEncoded();
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encodedKey, algorithm));
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
-
打开终端,导航到包含
EncryptionDemo.java文件的目录。 -
编译Java文件:
javac EncryptionDemo.java
- 运行编译后的类:
java EncryptionDemo
你应该会看到原始文本、加密后的文本和解密后的文本的输出。
注意:这个示例使用了AES算法和128位密钥长度。你可以根据需要更改算法和密钥长度。同时,这个示例使用了Base64编码来显示加密后的文本,以便于阅读和传输。在实际应用中,你可能需要使用更安全的编码方式。
以上就是关于“Ubuntu Java加密解密如何实现”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm