自己测试写的一个DES加密类,分析一下,也为了自己以后使用方便。
getEncryptionStr方法获得加密的密文,getDesString方法获得密文解密的明文,两个方法都要传入秘钥,当然秘钥是双方都知道的,加密的意义在于在数据传输过程中,保护数据安全,一定程度上防止数据被截获分析。
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class DES_encryption {
private static Key getKey(String strKey) {
Key key=null;
try {
KeyGenerator
_generator = KeyGenerator.getInstance("DES");
_generator.init(new
SecureRandom(strKey.getBytes()));
key =
_generator.generateKey();
_generator =
null;
return
key;
} catch (Exception e) {
e.printStackTrace();
}
return key;
}
public static String getEncryptionStr(String
strMing,String strKey) {
BASE64Encoder base64en = new
BASE64Encoder();
try {
byte[]
byteMing = strMing.getBytes("UTF8");
Key
key=getKey(strKey);
Cipher
cipher;
cipher =
Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE,
key);
String
strMiresult = base64en.encode(cipher.doFinal(byteMing));
return
strMiresult;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String
getDesString(String strMi,String strKey) {
BASE64Decoder base64De = new
BASE64Decoder();
try {
Key
key=getKey(strKey);
byte[] byteMi
= base64De.decodeBuffer(strMi);
Cipher
cipher;
cipher =
Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE,
key);
String
strDesResult = new String(cipher.doFinal(byteMi), "UTF8");
return
strDesResult;
} catch (Exception e) {
System.out.println("秘钥密文不匹配,解密失败!");
}
return null;
}
}
本文介绍了一个简单的DES加密类实现,包括加密和解密的方法。通过使用Java的Security和Crypto包,实现了基于字符串密钥的DES加密和解密过程。文章提供了完整的源代码示例。
5194

被折叠的 条评论
为什么被折叠?



