1.Hex编码将二进制数据按16进制转换为字符串,1字节=2个字符,编码后体积为2倍。
2.Base64由MIME规范定义的编码算法,其将3个字节(24位)编码为4个字符。字符集包括64个,可表示6二进制位的数据,因此一个字符对应一组6bit的数据。编码后体积约为4/3倍,针对不足位数用=补齐。
通常也称散列算法,是一种将任意长度的消息变成固定长度的消息摘要算法,不可逆;
1MD5MessageDigestAlgorithm5,流行度极高,但目前被发现存在碰撞冲突风险;任意长度输出为128bit=16字节摘要
2SHA1SHA指SecurityHashAlgorithm,由美国国家安全局NSA设计的安全散列算法系列;SHA1输出长度为160bit=20字节摘要
3SHA256继SHA1出现的算法(属于SHA-2类),安全性较SHA1更高;SHA256输出长度为256bit=32字节摘要。
MessageAuthenticationCode,消息认证码算法,基于HASH算法之上,增加了密钥的支持以提高安全性。具体算法包括HmacMD5/HmacSHA1/HmacSHA256等,输入包括数据及密钥,输出长度与HASH算法一致。密钥可以是任意长度的数据。
/***WriteabytearrayashexadecimalString.*/publicstaticStringbyteToHexString(byte[]bytes){returnString.valueOf(Hex.encodeHex(bytes));}/***TransformanhexadecimalStringtoabytearray.*/publicstaticbyte[]hexStringToByte(StringhexString){try{returnHex.decodeHex(hexString.toCharArray());}catch(DecoderExceptione){thrownewRuntimeException(e);}}//Hex来自common-codec扩展包//字节编码片段privatestaticfinalchar[]DIGITS_LOWER={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};/***@paramdata*abyte[]toconverttoHexcharacters*@returnAchar[]containinghexadecimalcharacters*@since1.4*/protectedstaticchar[]encodeHex(finalbyte[]data){finalintl=data.length;finalchar[]out=newchar[l<<1];//twocharactersformthehexvalue.for(inti=0,j=0;i
/***EncodeaStringtobase64**@paramvalue*TheplainString*@returnThebase64encodedString*/publicstaticStringencodeBASE64(Stringvalue){try{returnnewString(Base64.encodeBase64(value.getBytes("utf-8")));}catch(UnsupportedEncodingExceptionex){thrownewRuntimeException(ex);}}/***Decodeabase64value**@paramvalue*Thebase64encodedString*@returndecodedbinarydata*/publicstaticbyte[]decodeBASE64(Stringvalue){try{returnBase64.decodeBase64(value.getBytes("utf-8"));}catch(UnsupportedEncodingExceptionex){thrownewRuntimeException(ex);}}
/***BuildanhexadecimalMD5hashforaString**@paramvalue*TheStringtohash*@returnAnhexadecimalHash*/publicstaticStringhexMD5(Stringvalue){try{MessageDigestmessageDigest=MessageDigest.getInstance("MD5");messageDigest.reset();messageDigest.update(value.getBytes("utf-8"));byte[]digest=messageDigest.digest();returnbyteToHexString(digest);}catch(Exceptionex){thrownewRuntimeException(ex);}}
static{//addbouncycastlesupportformd4etc..Security.addProvider(newBouncyCastleProvider());}/***初始化密钥**@paramtype*@return*/publicstaticStringinitHmacKey(MacTypetype){try{KeyGeneratorgenerator=KeyGenerator.getInstance(type.name());SecretKeysecretKey=generator.generateKey();byte[]key=secretKey.getEncoded();returnCodec.byteToHexString(key);}catch(Exceptione){thrownewRuntimeException(e);}}/***计算HMAC摘要**@paramdata*@paramkey*@paramtype*@return*/publicstaticStringcomputeHmac(byte[]data,Stringkey,MacTypetype){try{byte[]keydata=Codec.hexStringToByte(key);SecretKeysecretKey=newSecretKeySpec(keydata,type.name());Macmac=Mac.getInstance(secretKey.getAlgorithm());mac.init(secretKey);byte[]digest=mac.doFinal(data);returnCodec.byteToHexString(digest);}catch(Exceptione){thrownewRuntimeException(e);}}
maven依赖