加密与解密概述

加密是将明文数据转换为密文数据的过程,而解密是将密文数据还原为明文数据的过程。Java提供了丰富的加密解密API,可以实现对称加密、非对称加密和哈希加密等多种加密方式。


对称加密

对称加密使用相同的密钥进行加密和解密。常见的对称加密算法包括AES、DES等。下面我们以AES算法为例,展示如何在Java中进行对称加密和解密。


package cn.juwatech;

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

public class AESExample {
    public static void main(String[] args) throws Exception {
        // 生成AES密钥
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); // 设置密钥长度为128位
        SecretKey secretKey = keyGen.generateKey();

        // 原始数据
        String originalData = "Hello, this is a secret message!";
        System.out.println("原始数据: " + originalData);

        // 加密数据
        byte[] encryptedData = encrypt(originalData, secretKey);
        String encryptedBase64 = Base64.getEncoder().encodeToString(encryptedData);
        System.out.println("加密数据: " + encryptedBase64);

        // 解密数据
        String decryptedData = decrypt(encryptedData, secretKey);
        System.out.println("解密数据: " + decryptedData);
    }

    // 加密方法
    public static byte[] encrypt(String data, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return cipher.doFinal(data.getBytes());
    }

    // 解密方法
    public static String decrypt(byte[] encryptedData, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedData);
        return new String(decryptedBytes);
    }
}