Java DES 对称加密
程序员文章站
2022-03-12 23:03:37
...
package com.inspur.uc.util;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import com.inspur.uc.util.mail.Base64;
/**
* DES 对称加密算法
*/
public class DESUtil {
/**
* 生成**
* @param key
* @return SecretKey
*/
public static SecretKey createKey(String key) {
// 需要判断pass长度,并需要长度大于8
if (key == null || key.length() < 8) {
key += "abcdefgh";
}
SecretKey sk = null;
try {
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("ISO-8859-1"));
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
sk = skf.generateSecret(desKeySpec);
} catch (Exception e) {
e.printStackTrace();
}
return sk;
}
/**
* DES加密
* @param content
* @param key
* @return String
*/
public static String encode(String content, SecretKey key){
try {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE,key );
byte[] b = cipher.doFinal(content.getBytes());
return Base64.encodeBytes(b);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* DES解密
* @param miwen
* @param key
* @return String
* @throws Exception
*/
public static String decode(String miwen, SecretKey key){
String str = null;
try {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
str = new String(cipher.doFinal(Base64.decode(miwen)));
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args)throws Exception {
String yuanwen = "123test测试@qq.11.com";
System.out.println("原文:"+yuanwen);
SecretKey key = createKey("123456");
String bs = encode(yuanwen,key);
System.out.println("加密后:"+bs);
String bsde = decode(bs,key);
System.out.println("解密后:"+bsde);
}
}
输出结果:
原文:123test测试@qq.11.com
加密后:szzkguMZPDa5LleJgENwzb92f6urkT9R
解密后:123test测试@qq.11.com
上一篇: 十五条 JavaScript 编程技巧
下一篇: php怎么删除所有文件夹
推荐阅读
-
加密解密 - 用php实现java中的aes加密
-
php提供的对称加密算法
-
PHP des加密输入如何才能和JAVA的des输出一至呢
-
PHP使用DES进行加密与解密的方法详解_php技巧
-
php对称加密算法的例子_PHP教程
-
PHP加密3DES报错 Call to undefined function: mcrypt_module_open() 的解决方法,mcryptmoduleopen_PHP教程
-
纯php实现DES以及TripleDES加密算法
-
请问个有关问题,关于3DES加密,知道明文和密文,能推出密钥吗
-
PHP加密3DES报错 Call to undefined function: mcrypt_module_open() 如何解决,mcryptmoduleopen
-
PHP加密3DES报错 Call to undefined function: mcrypt_module_open() 如何解决,mcryptmoduleopen