在Ubuntu上使用Java进行数据加密,你可以使用Java Cryptography Extension (JCE)框架。JCE提供了各种加密算法,如AES、DES、RSA等。以下是一个使用AES算法进行数据加密和解密的示例:
首先,确保你已经安装了Java开发工具包(JDK)。如果没有,请访问Oracle官网下载并安装。
创建一个名为EncryptionExample.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 EncryptionExample {
public static void main(String[] args) throws Exception {
String originalData = "Hello, World!";
System.out.println("Original data: " + originalData);
// 加密
String encryptedData = encrypt(originalData, "mySecretKey123");
System.out.println("Encrypted data: " + encryptedData);
// 解密
String decryptedData = decrypt(encryptedData, "mySecretKey123");
System.out.println("Decrypted data: " + decryptedData);
}
public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedData, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
EncryptionExample.java
文件的目录,并运行以下命令编译代码:javac EncryptionExample.java
java EncryptionExample
你将看到原始数据、加密后的数据和解密后的数据。
请注意,这个示例使用了AES算法和ECB模式。在实际应用中,你可能需要根据需求选择不同的加密算法和模式。同时,为了保证数据安全,建议使用更复杂的密钥,并妥善保管。