jingzi123456789的专栏

每天一小步、三天一大步

JAVA安全:3DES

1、安全加密算法

3DES,三重数据加密,且可以逆推的一种算法方案。

2、3DES加密算法的原理介绍

对称加密算法DES、3DES原理和实现方式:https://my.oschina.net/zchuanzhao/blog/525898

3、3DES加密过程

https://baike.baidu.com/item/3DES/6368161?fr=aladdin

4、3DES生成秘钥

这里特别要注意:K1、K2、K3决定了算法的安全性,若三个密钥互不相同,本质上就相当于用一个长为168位的密钥进行加密。
一直以为秘钥长度设置为168或112就是生成的16进制秘钥字符串长度不是48(192位),其实结果就是192bit。
package test.des;

import java.security.NoSuchAlgorithmException;

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

import org.junit.Test;
/**
 * DES是非对称加密,加密和解密使用的密钥\初始化向量都要相同,否则当然解不了密
 *
 */
public class DESUtil {
	private static String default_key = "0462164c0ae6daa12f980e2ca2fb15c12a921eae3c119ee5";
	//算法密钥长度参数:3DES(112或168)
    private static int key_length = 168;
	private static byte[] gen_key = null;
	
	@Test
	public void testDES() {
		String preencryptData = "1234567890";
		try {
			System.out.println("preencryptData:" + preencryptData);
			byte[] encryptData = encrypt(hexStringToBytes(preencryptData), getKey());
			String encryptDataStr = fromByteToHex(encryptData);
			System.out.println("encryptData:" + encryptDataStr);
			byte[] decryptData = decrypt(encryptData, getKey());
			String decryptDataStr = fromByteToHex(decryptData);
			System.out.println("decryptDataStr:" + decryptDataStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 生成秘钥
	 */
	public byte[] getKey() {
		if (null != gen_key && gen_key.length != 0) {
			System.out.println("gen_key:" + fromByteToHex(gen_key));
			return gen_key;
		}
		try {
			gen_key = generateKey();
		} catch (NoSuchAlgorithmException e) {
			gen_key = hexStringToBytes(default_key);
			e.printStackTrace();
		}
		System.out.println("gen_key:" + fromByteToHex(gen_key));
		return gen_key;
	}
	
    /**
     * DES 加密
     */
    public static byte[] encrypt(byte[] data, byte[] key) throws Exception{
        SecretKey secretKey = new SecretKeySpec(key, "DESede");
        Cipher cipher = Cipher.getInstance("DESede");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] resultBytes  = cipher.doFinal(data);
        return resultBytes ;
    }
    
    /**
     * DES 解密
     */
    public static byte[] decrypt(byte[] data, byte[] key) throws Exception{
        SecretKey secretKey = new SecretKeySpec(key, "DESede");
        Cipher cipher = Cipher.getInstance("DESede");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] resultBytes  = cipher.doFinal(data);
        return resultBytes ;
    }
    
    private byte[] generateKey() throws NoSuchAlgorithmException {
    	KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede") ;
    	keyGenerator.init(key_length);
    	SecretKey secretKey = keyGenerator.generateKey();
    	return secretKey.getEncoded();
    }
    
	private byte[] hexStringToBytes(String hexString) {   
	    if (hexString == null || hexString.equals("")) {   
	        return null;   
	    }   
	    hexString = hexString.toUpperCase();   
	    int length = hexString.length() / 2;   
	    char[] hexChars = hexString.toCharArray();   
	    byte[] d = new byte[length];   
	    for (int i = 0; i < length; i++) {   
	        int pos = i * 2;   
	        d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));   
	    }   
	    return d;   
	}   
	
	private byte charToByte(char c) {   
	    return (byte) "0123456789ABCDEF".indexOf(c);   
	}  
	
	private String fromByteToHex(byte[] data){
        StringBuilder builder = new StringBuilder("");
        if(data == null || data.length <= 0){
            return null;
        }
        for(int i = 0; i<data.length;i++){
            int v = data[i] & 0xFF;
            String result = Integer.toHexString(v);
            if(result.length()<2){
                builder.append(0);
            }
            builder.append(result);
        }
        return builder.toString();
    }

}

测试结果:

preencryptData:1234567890
gen_key:0d9da72ada085719fd80670d31d3df9b7ada2c620849e5b5
encryptData:ea836cced09c9fd8
gen_key:0d9da72ada085719fd80670d31d3df9b7ada2c620849e5b5
decryptDataStr:1234567890

5、其他文章

https://www.cnblogs.com/wsss/p/6925090.html
https://blog.csdn.net/hwaphon/article/details/52190653
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jingzi123456789/article/details/79978831
个人分类: 安全
上一篇Spring自动装配Bean
下一篇JAVA三种实现单例模式方法(一):懒汉式实现单例设计模式
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭