一. 简述

MD5: 全称为message digest algorithm 5(信息摘要算法), 能够进行加密, 可是不能解密, 属于单向加密, 通经常使用于文件校验

Base64: 把随意序列的8为字节描写叙述为一种不易为人识别的形式, 通经常使用于邮件、http加密. 登陆的username和password字段通过它加密, 能够进行加密和解密.

二. 代码

1. MD5:

public class MD5Utils {
/**
* 使用md5的算法进行加密
* @param plainText 加密明文
* @return 加密密文
*/
public static String getDigest(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("error happens", e);
}
return new BigInteger(1, secretBytes).toString(16);
}
}

2. Base64:

public class Base64Util {
/**
* 使用Base64进行编码
* @param encodeContent 须要编码的内容
* @return 编码后的内容
*/
public static String encode(String encodeContent) {
if (encodeContent == null) {
return null;
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(encodeContent.getBytes());
} /**
* 使用Base64进行编码
* @param encodeContent 须要编码的内容
* @return 编码后的内容
*/
public static String encode(byte[] encodeText) {
return encode(new String(encodeText));
} /**
* 使用Base64进行解码
* @param encodeContent 须要解码的内容
* @return 解码后的内容
*/
public static String decode(String decodeContent) {
byte[] bytes = null;
if (decodeContent == null) {
return null;
}
try {
bytes = new BASE64Decoder().decodeBuffer(decodeContent);
} catch (IOException e) {
throw new RuntimeException("error happens", e);
} finally {
}
return new String(bytes);
}
}

3. 測试代码:

public class Test {
/**
* 先使用MD5算法加密, 再使用base64算法进行编码
* @param args
*/
public static void main(String[] args) {
String plainText = "pwd";
String encodedPassword = MD5Utils.getDigest(Base64Util.encode(plainText));
System.out.println(encodedPassword);
}
}

为什么使用MD5加密后还要使用Base64编码呢? 用Base64算法编码后得到的是32位长度的字符串, 这样有利于在数据库中进行存储.

版权声明:本文博主原创文章。博客,未经同意不得转载。

最新文章

  1. zepto源代码解读
  2. BZOJ_2434_[NOI2011]_阿狸的打字机_(AC自动机+dfs序+树状数组)
  3. Java中处理Linux信号量
  4. Java实战之03Spring-02Spring的核心之IoC
  5. jquery 中ajax的参数
  6. 从JDBC到hibernate再到mybatis之路
  7. JavaWeb 乱码问题终极解决方案!
  8. Python基础(reduce,filter,map函数)
  9. 如何开启远程debug调试功能?
  10. [LeetCode] Subdomain Visit Count 子域名访问量统计
  11. java.lang.IllegalAccessError: org.apache.commons.dbcp.DelegatingPreparedStatement.isClosed()Z
  12. blockchain[z]
  13. day43 数据库学习egon的博客 索引
  14. IT系统故障引起的一个事故的思考
  15. Comparable与Comparator区别
  16. TreeMap源代码深入剖析
  17. Java IO流-字节流
  18. 【android】Socket简单用法
  19. solr原理
  20. [USACO]奶牛抗议(DP+树状数组+离散化)

热门文章

  1. SpringMVC @ResponseBody 415错误处理
  2. ipconfig /flushdns 清除系统DNS缓存
  3. POJ 1182 :食物链(并查集)
  4. windows phone (15) UI变换上
  5. Objective-C路成魔【18-复制对象】
  6. HDU 4982 Goffi and Squary Partition(推理)
  7. 轻松管理您的网络password
  8. SQLServer2014新功能
  9. php:修改NetBeans默认字体
  10. hdu1372 dfs搜索之国际象棋的马