在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編碼來顯示加密后的文本,以便于閱讀和傳輸。在實際應用中,你可能需要使用更安全的編碼方式。