Java

cipher类java与对称加密算法

小樊
82
2024-09-09 10:34:40
栏目: 编程语言

Cipher 类是 Java 加密扩展(Java Cryptography Extension,JCE)中的一个关键组件,它提供了对多种加密算法的访问。对称加密算法是一种使用相同密钥进行加密和解密的加密方式。在 Java 中,你可以使用 Cipher 类来实现对称加密算法,例如 AES、DES 和 3DES 等。

以下是一个使用 Cipher 类和 AES 对称加密算法的示例:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class SymmetricEncryptionExample {
    public static void main(String[] args) throws Exception {
        // 生成 AES 密钥
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();

        // 加密
        Cipher cipherForEncryption = Cipher.getInstance("AES");
        cipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] plainTextBytes = "Hello, World!".getBytes();
        byte[] encryptedBytes = cipherForEncryption.doFinal(plainTextBytes);
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted text: " + encryptedText);

        // 解密
        Cipher cipherForDecryption = Cipher.getInstance("AES");
        cipherForDecryption.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipherForDecryption.doFinal(Base64.getDecoder().decode(encryptedText));
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted text: " + decryptedText);
    }
}

在这个示例中,我们首先生成一个 AES 密钥,然后使用 Cipher 类进行加密和解密操作。注意,为了在不同的会话之间安全地存储和传输密钥,你需要使用密钥交换算法(如 RSA)或其他安全方法。

0
看了该问题的人还看了