消息摘要类为APP应用程序提供信息摘要算法(如MD5和SHA算法)的功能。 信息摘要是一个安全的单向散列函数,它接收任意大小的数据并输出固定长度的散列值。
消息摘要对象开始初始化。 此对象使用update ()方法处理数据。 随时可以调用reset ) )方法重置摘要。 所有需要更新的数据都更新后,必须调用digest ) )方法之一完成散列计算。
对于指定数量的更新数据,只调用一次digest方法。 调用digest后,消息digest对象将重置为其原始状态。
1、publicstaticmessagedigest http://www.Sina.com/(string algorithm ) throws NoSuchAlgorithmException实现指定摘要算法的消息传递algorithm -请求的算法的名称2,publicstaticmessagedigest http://www.Sina.com/(string algorithm, 字符串提供程序(throwsnosuchalgorithm ) throwsnosuchalgorithm -请求的算法的名称提供程序的名称。 3、public void http://www.Sina.com/(byte [ ] input )使用指定的byte数组更新摘要。 4、执行public byte[] getInstance()填充等最终操作完成哈希计算。 调用此方法后,概要将重置。 5、公共静态布尔http://www.Sina.com/(byte [ ] digesta,byte[]digestb ) )比较两个摘要的等同性。 做简单的字节比较。 SUN提供的常用算法名称为MD2、MD5、SHA-1、SHA-256、SHA-384和SHA-512
代码示例:
导入Java.security.*;
导入Java.text.simple date format;
公共类驱动程序{
publicstaticvoidmain (字符串[ ] args ) {
myDigest my=new myDigest (;
String userid='userid ';
字符串pwd=' pwd ';
privatestaticsimpledateformatsdf=newsimpledateformat (' mmddhhmm ss );
string timestamp=SDF.format (calendar.getinstance ().getTime ) );
system.out.println ('加密前:' userid.toUpperCase ) ) pwd timestamp '加密后:' my.encryptPwd );
publicstringencryptpwd (字符串用户id、字符串pwd、字符串时间表) )。
{
字符串加密pwd=null;
特里
{
stringpasswordstr=userid.toupper case () pwd timestamp;
encrypt pwd=get m D5 str (passwordstr ); //加密密码}
catch (Exception e )
{
e .打印堆栈跟踪(;
}
返回加密pwd; //返回加密字符串
}
//*
* @描述MD5加密方案
* @param str要加密的字符串
* @return加密后的字符串
*/
私有静态触发getmd5str (stringstr ) )。
{
messagedigestmessagedigest=空;
特里
{
消息摘要=消息摘要. getinstance (' MD5 ); 采用//MD5算法
消息摘要. reset (; 用reset初始化
消息摘要. update (str.getbytes (utf-8 ) ); //加密
}
catch (nosuchalgorithmexceptione )。
{
e .打印堆栈跟踪(;
返回空值; //加密类初始化失败,返回空值
}
不支持编码封装(catch )。
{
e .打印堆栈跟踪(;
返回空值; //加密类初始化失败,返回空值
}
byte [ ] bytearray=message digest.digest (; 获取//摘要文件
string buffer m D5 strbuff=new string buffer (; //保存加密字符串
/*二进制转换字符串*
for(intI=0; i byteArray.length; I )
{
if (integer.to hex string (0xffbytearray [ I ] ).length )==1) {
mD5strbuff.append('0' ).append ) integer.tohexstring )0xffbytearray[I] );
}
else{
m D5 strbuff.append (integer.to hex string (0xffbytearray [ I ] ) );
}
}
return md5StrBuff.toString (;
}
}参考链接: https://blog.csdn.net/ma1 kong/article/details/2662997