ubuntu

Ubuntu Java加密解密如何实现

小樊
41
2025-03-08 08:55:43
栏目: 编程语言

在Ubuntu上使用Java进行加密和解密,你可以使用Java Cryptography Extension (JCE)框架。以下是一个简单的示例,展示了如何使用Java的Cipher类进行AES加密和解密。

首先,确保你已经安装了Java开发工具包(JDK)。如果没有,请访问Oracle官网下载并安装。

  1. 创建一个名为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);
    }
}
  1. 打开终端,导航到包含EncryptionDemo.java文件的目录。

  2. 编译Java文件:

javac EncryptionDemo.java
  1. 运行编译后的类:
java EncryptionDemo

你应该会看到原始文本、加密后的文本和解密后的文本的输出。

注意:这个示例使用了AES算法和128位密钥长度。你可以根据需要更改算法和密钥长度。同时,这个示例使用了Base64编码来显示加密后的文本,以便于阅读和传输。在实际应用中,你可能需要使用更安全的编码方式。

0
看了该问题的人还看了