文章16 | 阅读 6999 | 点赞0
commons-codec
是Apache开源组织提供的用于摘要运算、编码的包。在该包中主要分为四类加密:BinaryEncoders、DigestEncoders、LanguageEncoders、NetworkEncoders。
今天就为大家介绍一下如何用commons-codec
包完成常见的编码、摘要运算。
示例代码:
@Test
public void testBase64()
{
System.out.println("==============Base64================");
byte[] data = "jianggujin".getBytes();
Base64 base64 = new Base64();
String encode = base64.encodeAsString(data);
System.out.println(encode);
System.out.println(new String(base64.decode(encode)));
}
运行结果:
==============Base64================ amlhbmdndWppbg==
jianggujin
示例代码:
@Test
public void testMD5()
{
System.out.println("==============MD5================");
String result = DigestUtils.md5Hex("jianggujin");
System.out.println(result);
}
运行结果:
acab4efdfd3b8efcdec37fe160d7be0e
SHA等摘要运算和MD5类似。
示例代码:
@Test
public void testURLCodec() throws Exception
{
System.out.println("==============URLCodec================");
URLCodec codec = new URLCodec();
String data = "蒋固金";
String encode = codec.encode(data, "UTF-8");
System.out.println(encode);
System.out.println(codec.decode(encode, "UTF-8"));
}
运行结果:
==============URLCodec================
%E8%92%8B%E5%9B%BA%E9%87%91
蒋固金
完整示例代码:
package com.gujin.codec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.net.URLCodec;
import org.junit.Test;
public class CodecTest {
@Test
public void testBase64()
{
System.out.println("==============Base64================");
byte[] data = "jianggujin".getBytes();
Base64 base64 = new Base64();
String encode = base64.encodeAsString(data);
System.out.println(encode);
System.out.println(new String(base64.decode(encode)));
}
@Test
public void testMD5()
{
System.out.println("==============MD5================");
String result = DigestUtils.md5Hex("jianggujin");
System.out.println(result);
}
@Test
public void testURLCodec() throws Exception
{
System.out.println("==============URLCodec================");
URLCodec codec = new URLCodec();
String data = "蒋固金";
String encode = codec.encode(data, "UTF-8");
System.out.println(encode);
System.out.println(codec.decode(encode, "UTF-8"));
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/jianggujin/article/details/51149133
内容来源于网络,如有侵权,请联系作者删除!