Java 对称加密算法 AES,DES,3DES,RC4介绍及示例

在Java中,对称加密算法是一类常用的加密技术,它们使用相同的密钥进行加密和解密操作。以下是AES、DES、3DES和RC4四种对称加密算法的介绍及Java示例。

1. AES(Advanced Encryption Standard)

简介
AES,全称为高级加密标准,是美国联邦政府采用的一种区块加密标准。它采用分组加密的方式,每个数据块进行独立加密。AES提供了三种密钥长度:128位、192位和256位,密钥长度越高,安全性越强。AES算法被广泛应用于保护电子数据的机密性,如金融交易、网络通信等。

Java示例

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 String encrypt(String plainText, String key) throws Exception {  
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");  
        Cipher cipher = Cipher.getInstance("AES");  
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);  
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());  
        return Base64.getEncoder().encodeToString(encryptedBytes);  
    }  
  
    public static String decrypt(String encryptedText, String key) throws Exception {  
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");  
        Cipher cipher = Cipher.getInstance("AES");  
        cipher.init(Cipher.DECRYPT_MODE, secretKey);  
        byte[] originalBytes = Base64.getDecoder().decode(encryptedText);  
        byte[] decryptedBytes = cipher.doFinal(originalBytes);  
        return new String(decryptedBytes);  
    }  
  
    // 示例用法  
    public static void main(String[] args) throws Exception {  
        String key = "1234567890123456"; // AES密钥长度应为16(128位)、24(192位)或32(256位)字节  
        String plainText = "Hello, World!";  
        String encryptedText = encrypt(plainText, key);  
        String decryptedText = decrypt(encryptedText, key);  
        System.out.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值