Java|Java 实现字符串SHA1加密方法

目录

  • Java 字符串SHA1加密
    • 导入类
    • 定义函数
  • javaSHA1实现加密解密
    • 封装一个方法用于加密
    • 主函数测试
【Java|Java 实现字符串SHA1加密方法】
Java 字符串SHA1加密
导入类
import java.security.MessageDigest;


定义函数
private String toUserPwd(final String password) {try {if (password == null) {return null; }final MessageDigest messageDigest = MessageDigest.getInstance("SHA"); final byte[] digests = messageDigest.digest(password.getBytes()); final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < digests.length; i++) {int halfbyte = (digests[i] >>> 4) & 0x0F; for (int j = 0; j <= 1; j++) {stringBuilder.append(((0 <= halfbyte) && (halfbyte <= 9))? (char) ('0' + halfbyte): (char) ('a' + (halfbyte - 10))); halfbyte = digests[i] & 0x0F; }}return stringBuilder.toString(); } catch (final Throwable throwable) {this.log.error("error converting password", throwable); return null; } }


javaSHA1实现加密解密
封装一个方法用于加密
/*** sha1加密* @param data* @return* @throws NoSuchAlgorithmException */public static String sha1(String data) throws NoSuchAlgorithmException {//加盐更安全一些data += "lyz"; //信息摘要器算法名称MessageDigest md = MessageDigest.getInstance("SHA1"); //把字符串转为字节数组byte[] b = data.getBytes(); //使用指定的字节来更新我们的摘要md.update(b); //获取密文(完成摘要计算)byte[] b2 = md.digest(); //获取计算的长度int len = b2.length; //16进制字符串String str = "0123456789abcdef"; //把字符串转为字符串数组char[] ch = str.toCharArray(); //创建一个40位长度的字节数组char[] chs = new char[len*2]; //循环20次for(int i=0,k=0; i>>:无符号右移// &:按位与//0xf:0-15的数字chs[k++] = ch[b3 >>> 4 & 0xf]; chs[k++] = ch[b3 & 0xf]; }//字符数组转为字符串return new String(chs); }


主函数测试
public static void main(String[] args) throws NoSuchAlgorithmException {String data = "https://www.it610.com/article/跳梁小豆tlxd666"; String result = sha1(data); System.out.println("加密后:"+result); }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读