3DES加密算法

来源:互联网 发布:数据结构课程设计java 编辑:程序博客网 时间:2024/06/15 21:20

3DES(或称为Triple DES)是三重数据加密算法(TDEA,Triple Data Encryption Algorithm)块密码的通称。它相当于是对每个数据块应用三次DES加密算法。由于计算机运算能力的增强,原版DES密码的密钥长度变得容易被暴力破解;3DES即是设计用来提供一种相对简单的方法,即通过增加DES的密钥长度来避免类似的攻击,而不是设计一种全新的块密码算法。

基于Java的DES算法的使用

     //base64编码     public static String byte2base64(byte[] bytes){     BASE64Encoder base64Encoder = new BASE64Encoder();     return base64Encoder.encode(bytes);     }     //base64解码     public static byte[] base642byte(String base64) throws Exception{     BASE64Decoder base64Decoder = new BASE64Decoder();     return base64Decoder.decodeBuffer(base64);     }          public static String getKeyDes() throws Exception{     //1.通过KeyGenerator获取秘钥生成器     KeyGenerator kg = KeyGenerator.getInstance("DES");     //2.设置DES算法的秘钥为56位     kg.init(56);     //3.生成DES算法的秘钥     SecretKey key = kg.generateKey();     //4.为了方便存储,生成秘钥后进行base64编码     String base64Str = byte2base64(key.getEncoded());     return base64Str;     }     public static SecretKey  SecreKeyDes(String base64Key) throws Exception{     //1.将相应的秘钥字符串转换成SecretKey对象     byte[] bytes = base642byte(base64Key);     //2.需要将秘钥base64解码后,传入对应的算法后实例一个SecretKey即可     SecretKey key = new SecretKeySpec(bytes, "DES");     return key;     }     //加密     public static byte[] encryptDES(byte[] source,SecretKey key)throws Exception{     Cipher cipher = Cipher.getInstance("DES");     cipher.init(Cipher.ENCRYPT_MODE,key);//加密模式     byte[] bytes = cipher.doFinal(source);     return bytes;     }     //解密     public static byte[] decryptDES(byte[] source,SecretKey key)throws Exception{     Cipher cipher = Cipher.getInstance("DES");     cipher.init(Cipher.DECRYPT_MODE,key);//解密模式     byte[] bytes = cipher.doFinal(source);     return bytes;     }     


原创粉丝点击