700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Java简单实现DES加密解密算法

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

时间:2018-10-21 22:05:10

相关推荐

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

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

文章目录

Java简单实现DES加密解密算法DES算法介绍实现相关java类代码实现

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;//设置密钥keyprivate 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 exceptionthrow new RuntimeException(e);}}//解密函数public static String getDecryptString(String str) {//接受byte[]并转换成StringBASE64Decoder base64decoder = new BASE64Decoder();try {//将String变成bytebyte[] 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 exceptionthrow new RuntimeException(e);}}//测试public static void main(String[] args) {System.out.println(getEncryptString("root"));//System.out.println(getDecryptString("WnplV/ietfQ="));}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。