JAVA加密算法(3)- 对称加密算法(DES、3DES、AES)

##对称加密算法概念

  • 加密密钥和解密密钥相同,大部分算法加密揭秘过程互逆。
  • 特点:算法公开、(相比非对称加密)计算量小、加密速度快、效率高。
  • 弱点:双方都使用同样的密钥,安全性得不到保证。

##常用对称加密算法

  • DES(Data Encryption Standard)
  • 3DES(DES加强版,使用3次DES计算,Triple DES,DESede)
  • AES(Advanced Encryption Standard,3DES加强版)

##JDK版DES/3DES/AES算法调用模板

1. 生成密钥

//KeyGenerator,密钥生成器
KeyGenerator keyGen = KeyGenerator.getInstance("DES");//算法:DES,DESede,AES

//初始化密钥生成器
keyGen.init(56); //各算法密钥长度不同,参见说明

//生成密钥
SecretKey secretKey = keyGen.generateKey();

//生产字节码数据
byte[] key = secretKey.getEncoded();

说明: 1.通过「KeyGenerator.getInstance("DES")」生成密钥, 2.参数为算法名称:分别对应DES、DESede(即3DES)、AES 3.每种算法密钥长度参数:DES(56),3DES(112,168),AES(192,256)

###2.加/解密

//通过字节码数据key 恢复密钥
SecretKey secretKey = new SecretKeySpec(key, "DES");

//Cipher完成加密/解密工作
Cipher cipher = Cipher.getInstance("DES");

//根据密钥,对Cipher初始化,并选择加密还是解密
cipher.init(Cipher.ENCRYPT_MODE, secretKey);

byte[] result = cipher.doFinal(data);

1.加密或解密都通过cipher.init()设置,参数:ENCRYPT_MODE/DECRYPT_MODE 2.加密或解密都通过cipher.doFinal() 执行,获得byte[]类型结果。

###代码示例

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class DESUtil {
	
	/*
	 * 生成密钥
	 */
	public static byte[] initKey() throws Exception{
		KeyGenerator keyGen = KeyGenerator.getInstance("DES");
		keyGen.init(56);
		SecretKey secretKey = keyGen.generateKey();
		return secretKey.getEncoded();
	}

	
	/*
	 * DES 加密
	 */
	public static byte[] encrypt(byte[] data, byte[] key) throws Exception{
		SecretKey secretKey = new SecretKeySpec(key, "DES");
		
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		byte[] cipherBytes = cipher.doFinal(data);
		return cipherBytes;
	}
	
	
	/*
	 * DES 解密
	 */
	public static byte[] decrypt(byte[] data, byte[] key) throws Exception{
		SecretKey secretKey = new SecretKeySpec(key, "DES");
		
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.DECRYPT_MODE, secretKey);
		byte[] plainBytes = cipher.doFinal(data);
		return plainBytes;
	}

    //Test
    public static void main(String[] args) throws Exception {
    byte[] desKey = DESUtil.initKey();
		System.out.println("DES KEY : " + BytesToHex.fromBytesToHex(desKey));
		byte[] desResult = DESUtil.encrypt(DATA.getBytes(), desKey);
		System.out.println(DATA + ">>>DES 加密结果>>>" + BytesToHex.fromBytesToHex(desResult));
		
		byte[] desPlain = DESUtil.decrypt(desResult, desKey);
		System.out.println(DATA + ">>>DES 解密结果>>>" + new String(desPlain));
    }
}

转载于:https://my.oschina.net/qiegao/blog/786062

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值