当前位置: 首页 > 图文教程 > 网络编程 > JSP > java易懂易用的MD5加密(可直接运行) (1)

JSP
我认为JSP有问题(下)
JSP显示中文问题的解决方案
JSP技术简介
JSP开发导引
JSP开发入门
JSP多种web应用服务器导致JSP源码泄漏漏洞
JSP实现浏览器关闭cookies情况下的会话管理
tomcat 3.1在RedHat下的安装
初学jsp心得
如何防止IE缓存jsp文件
利用Java实现zip压缩/解压缩
一个用JSP做的日历
无边框窗口代码详解
实例讲解JSP Model2体系结构(上)
实例讲解JSP Model2体系结构(中)
实例讲解JSP Model2体系结构(下)
JSP模板应用指南(下)
JSP简明教程:令人兴奋的脚本编程
JSP简明教程:对比与总结
jsp基础学习资料

JSP 中的 java易懂易用的MD5加密(可直接运行) (1)


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 83 ::
收藏到网摘: n/a

出于安全考虑,网络的传输中经常对传输数据做加密和编码处理,其中涉及以下几种 1、md5加密,该加密算法是单向加密,即加密的数据不能再通过解密还原。相关类包含在java.security.MessageDigest包中。
2、3-DES加密,该加密算法是可逆的,解密方可以通过与加密方约定的密钥匙进行解密。相关类包含在javax.crypto.*包中。
3、base64编码,是用于传输8bit字节代码最常用的编码方式。相关类在sun.misc.BASE64Decoder 和sun.misc.BASE64Encoder 中。
4、URLEncoder编码,是一种字符编码,保证被传送的参数由遵循规范的文本组成。相关类在java.net.URLEncoder包中。
细节:
1、进行MD5加密,得到byte[]
复制代码 代码如下:
5、根据需要可以去掉字符串的换行符号
复制代码 代码如下:

/**
* 去掉字符串的换行符号
* base64编码3-DES的数据时,得到的字符串有换行符号,根据需要可以去掉
*/
private String filter(String str)
{
String output = null;
StringBuffer sb = new StringBuffer();
for(int i = 0; i < str.length(); i++)
{
int asc = str.charAt(i);
if(asc != 10 && asc != 13)
sb.append(str.subSequence(i, i + 1));
}
output = new String(sb);
return output;
}

6、对字符串进行URLDecoder.encode(strEncoding)编码
复制代码 代码如下:

/**
* 对字符串进行URLDecoder.encode(strEncoding)编码
* @param String src 要进行编码的字符串
*
* @return String 进行编码后的字符串
*/
public String getURLEncode(String src)
{
String requestValue="";
try{
requestValue = URLEncoder.encode(src);
}
catch(Exception e){
e.printStackTrace();
}
return requestValue;
}

7、对字符串进行URLDecoder.decode(strEncoding)解码
复制代码 代码如下:

/**
* 对字符串进行URLDecoder.decode(strEncoding)解码
* @param String src 要进行解码的字符串
*
* @return String 进行解码后的字符串
*/
public String getURLDecoderdecode(String src)
{
String requestValue="";
try{
requestValue = URLDecoder.decode(src);
}
catch(Exception e){
e.printStackTrace();
}
return requestValue;
}

8、进行3-DES解密(密钥匙等同于加密的密钥匙)
复制代码 代码如下:

/**
*
*进行3-DES解密(密钥匙等同于加密的密钥匙)。
* @param byte[] src 要进行3-DES解密byte[]
* @param String spkey分配的SPKEY
* @return String 3-DES解密后的String
*/
public String deCrypt(byte[] debase64,String spKey)
{
String strDe = null;
Cipher cipher = null;
try
{
cipher=Cipher.getInstance("DESede");
byte[] key = getEnKey(spKey);
DESedeKeySpec dks = new DESedeKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey sKey = keyFactory.generateSecret(dks);
cipher.init(Cipher.DECRYPT_MODE, sKey);
byte ciphertext[] = cipher.doFinal(debase64);
strDe = new String(ciphertext,"UTF-16LE");
}
catch(Exception ex)
{
strDe = "";
ex.printStackTrace();
}
return strDe;
经过以上步骤就可以完成MD5加密,3-DES加密、base64编码传输、base64解码、3-DES解密得到原文。