Java简单实现DES加密解密算法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/liu_Yudong/article/details/88966515

Java简单实现DES加密解密算法

DES算法介绍

DEC加密算法属于对称加密,即利用指定的密钥,按照密码的长度截取数据,分成数据块,和密钥进行复杂的移位、算数运算或者数据处理等操作,形成只有特定的密码才能够解开的数据。 加密与解密用的是同一个密钥,即加密密钥等于解密密钥,加密密钥和解密密钥可以相互推倒出来。

实现相关java类

1.Key:Key类是Java加密的所有父类
2.SecureRandom:指定安全策略组
3.KeyGenerator:生成算法对象
4.BASE64Encoder和BASE64Decoder:通过base64位完成byte和String的相互转换
5.Cipher:这是一个重点类
  Java/Android要使用任何加密,都需要使用Cipher这个类
  Cipher cipher = Cipher.getInstance(“算法名称”)
  cipher.init(加密/解密模式,Key秒),Cipher.DECRYPT_MODE 解密;Cipher.ENCRYPT_MODE 加密
  即:加密:cipher.init(Cipher.ENCRYPT_MODE, key);解密:cipher.init(Cipher.DECRYPT_MODE, key);
  调用doFinal()方法完成单步的加密或解密数据;如果是多组数据,需要用到updata();

代码实现

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
//去除警告
@SuppressWarnings("restriction")
public class DESUtil {
	private static Key key;
	//设置密钥key
	private static String KEY_STR = "myKey";
	private static String CHARSETNAME = "UTF-8";
	private static String ALGORITHM = "DES";
	static {
		try {
			//生成DES算法对象
			KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
			//运用SHA1安全策略
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			//设置密钥种子
			secureRandom.setSeed(KEY_STR.getBytes());
			//初始化基于SHA1的算法对象
			generator.init(secureRandom);
			//生成密钥对象
			key = generator.generateKey();
			generator = null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	//加密函数
	public static String getEncryptString(String str) {
		BASE64Encoder base64encoder = new BASE64Encoder();
		try {
			//按utf-8编码
			byte[] bytes = str.getBytes(CHARSETNAME);
			//获取加密对象
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			//初始化加密信息
			cipher.init(Cipher.ENCRYPT_MODE, key);
			//加密
			byte[] doFinal = cipher.doFinal(bytes);
			//byte to encode好的String返回
			return base64encoder.encode(doFinal);
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}
	//解密函数
	public static String getDecryptString(String str) {
		//接受byte[]并转换成String
		BASE64Decoder base64decoder = new BASE64Decoder();
		try {
			//将String变成byte
			byte[] bytes = base64decoder.decodeBuffer(str);
			//获取解密对象
			Cipher cipher = Cipher.getInstance(ALGORITHM);
			//初始化解密信息
			cipher.init(Cipher.DECRYPT_MODE, key);
			//解密
			byte[] doFinal = cipher.doFinal(bytes);
			//返回解密信息
			return new String(doFinal, CHARSETNAME);
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}
	//测试
	public static void main(String[] args) {
		System.out.println(getEncryptString("root"));
//		System.out.println(getDecryptString("WnplV/ietfQ="));
	}
}

猜你喜欢

转载自blog.csdn.net/liu_Yudong/article/details/88966515