您的位置:首页 > 运维架构 > Apache

java利用Apache commons codec进行MD5加密,BASE64加密解密,执行系统命令

2017-12-01 17:38 1111 查看

编写代码之前先来介绍一下我们要用到的两个包;

commons-codec-1.10.jar
Commons项目中用来处理常用的编码方法的工具类包,例如DES、SHA1、MD5、Base64,URL,Soundx等等。

commons-exec-1.3.jar
Apache Commons Exec 是 Apache 上的一个 Java 项目,提供一些常用的方法用来执行外部进程

你可以到本站直接下载 Apache Commons 官方包

下面看一下代码结构:

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
/**
* @author Delver_Si
*
*/
public class EncodeAndDecode {
/**
* Md5加密
* @param str
* @return
*/
public static String Md5encode(String str) {
return DigestUtils.md5Hex(str);
}
/**
* Base64加密
* @param str
* @return
*/
public static String Base64encode(String str) {
byte[] b = Base64.encodeBase64(str.getBytes(), true);
return new String(b);
}
/**
* Base64解密
* @param str
* @return
*/
public static String Base64decode(String str) {
byte[] b = Base64.decodeBase64(str.getBytes());
return new String(b);
}
/**
* 生成SHA1
*/
public static String SHA1encode(String str) {
return DigestUtils.sha1Hex(str);
}
}

把主要功能都放在一个类文件中

新建Test类引用上个文件

import security.EncodeAndDecode;
import security.Exec;
public class Test {
public static void main(String[] args) {
System.out.println(EncodeAndDecode.Md5encode("jb51.net"));//MD5加密
System.out.println(EncodeAndDecode.Base64encode("jb51.net"));//Base64加密
System.out.println(EncodeAndDecode.Base64decode("amI1MS5uZXQ="));//Base64解密
String str = Exec.exec("ping jb51.net");//执行系统的Ping命令
System.out.println(str);
}
}

好了 ,运行一下看看最终结果

这些只是Apache commons 包的基本功能,其它功能大家可以到这里下载 apache commons 使用说明 中文WORD版 详细研究

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息