对于MD5&SHA加密util类感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解Java,并且为您提供关于BASE64、MD5、SHA、HMAC几种加密算法、C#MD5与javaMD5生成的
对于MD5&SHA 加密 util 类感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解Java,并且为您提供关于BASE64、MD5、SHA、HMAC几种加密算法、C# MD5 与 java MD5 生成的字符串不一致问题、C# 计算字符串的哈希值(MD5、SHA)、C#SHA-256与Java SHA-256.结果不同?的宝贵知识。
本文目录一览:- MD5&SHA 加密 util 类(Java)(md5加密java代码)
- BASE64、MD5、SHA、HMAC几种加密算法
- C# MD5 与 java MD5 生成的字符串不一致问题
- C# 计算字符串的哈希值(MD5、SHA)
- C#SHA-256与Java SHA-256.结果不同?
MD5&SHA 加密 util 类(Java)(md5加密java代码)
MD5&SHA 加密 util 类(Java)
- package com.arui.util;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- public class EncryptUtils {
- /**
- * Encrypt string using MD5 algorithm
- */
- public final static String encryptMD5(String source) {
- if (source == null) {
- source = "";
- }
- String result = "";
- try {
- result = encrypt(source, "MD5");
- } catch (NoSuchAlgorithmException ex) {
- // this should never happen
- throw new RuntimeException(ex);
- }
- return result;
- }
- /**
- * Encrypt string using SHA algorithm
- */
- public final static String encryptSHA(String source) {
- if (source == null) {
- source = "";
- }
- String result = "";
- try {
- result = encrypt(source, "SHA");
- } catch (NoSuchAlgorithmException ex) {
- // this should never happen
- throw new RuntimeException(ex);
- }
- return result;
- }
- /**
- * Encrypt string
- */
- private final static String encrypt(String source, String algorithm)
- throws NoSuchAlgorithmException {
- byte[] resByteArray = encrypt(source.getBytes(), algorithm);
- return toHexString(resByteArray);
- }
- /**
- * Encrypt byte array.
- */
- private final static byte[] encrypt(byte[] source, String algorithm)
- throws NoSuchAlgorithmException {
- MessageDigest md = MessageDigest.getInstance(algorithm);
- md.reset();
- md.update(source);
- return md.digest();
- }
- /**
- * Get hex string from byte array
- */
- private final static String toHexString(byte[] res) {
- StringBuffer sb = new StringBuffer(res.length << 1);
- for (int i = 0; i < res.length; i++) {
- String digit = Integer.toHexString(0xFF & res[i]);
- if (digit.length() == 1) {
- digit = ''0'' + digit;
- }
- sb.append(digit);
- }
- return sb.toString().toUpperCase();
- }
- }
原文链接: http://blog.csdn.net/arui319/article/details/5771804
BASE64、MD5、SHA、HMAC几种加密算法
本篇内容简要介绍BASE64、MD5、SHA、HMAC几种加密算法。
BASE64编码算法不算是真正的加密算法。
MD5、SHA、HMAC这三种加密算法,可谓是非可逆加密,就是不可解密的加密方法,我们称之为单向加密算法。我们通常只把他们作为加密的基础。单纯的以上三种的加密并不可靠。
BASE64
按照RFC2045的定义,Base64被定义为:Base64内容传送编码被设计用来把任意序列的8位字节描述为一种不易被人直接识别的形式。(The Base64 Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable.)
常见于邮件、http加密,截取http信息,你就会发现登录操作的用户名、密码字段通过BASE64加密的。
如基本的单向加密算法:
-
BASE64 严格地说,属于编码格式,而非加密算法
-
MD5(Message Digest algorithm 5,信息摘要算法)
-
SHA(Secure Hash Algorithm,安全散列算法)
-
HMAC(Hash Message Authentication Code,散列消息鉴别码)
复杂的对称加密(DES、PBE)、非对称加密算法:
-
DES(Data Encryption Standard,数据加密算法)
-
PBE(Password-based encryption,基于密码验证)
-
RSA(算法的名字以发明者的名字命名:Ron Rivest, AdiShamir 和Leonard Adleman)
-
DH(Diffie-Hellman算法,密钥一致协议)
-
DSA(Digital Signature Algorithm,数字签名)
-
ECC(Elliptic Curves Cryptography,椭圆曲线密码编码学)
本篇内容简要介绍BASE64、MD5、SHA、HMAC、DES、PBE、RSA几种方法。
MD5、SHA、HMAC这三种加密算法,可谓是非可逆加密,就是不可解密的加密方法。我们通常只把他们作为加密的基础。单纯的以上三种的加密并不可靠。
通过java代码实现如下:
- /**
- * BASE64解密
- *
- * @param key
- * @return
- * @throws Exception
- */
- public static byte[] decryptBASE64(String key) throws Exception {
- return (new BASE64Decoder()).decodeBuffer(key);
- }
- /**
- * BASE64加密
- *
- * @param key
- * @return
- * @throws Exception
- */
- public static String encryptBASE64(byte[] key) throws Exception {
- return (new BASE64Encoder()).encodeBuffer(key);
- }
主要就是BASE64Encoder、BASE64Decoder两个类,我们只需要知道使用对应的方法即可。另,BASE加密后产生的字节位数是8的倍数,如果不够位数以=符号填充。
MD5
MD5 -- message-digest algorithm 5 (信息-摘要算法)缩写,广泛用于加密和解密技术,常用于文件校验。校验?不管文件多大,经过MD5后都能生成唯一的MD5值。好比现在的ISO校验,都是MD5校验。怎么用?当然是把ISO经过MD5后产生MD5的值。一般下载linux-ISO的朋友都见过下载链接旁边放着MD5的串。就是用来验证文件是否一致的。
通过java代码实现如下:
- /**
- * MD5加密
- *
- * @param data
- * @return
- * @throws Exception
- */
- public static byte[] encryptMD5(byte[] data) throws Exception {
- MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
- md5.update(data);
- return md5.digest();
- }
通常我们不直接使用上述MD5加密。通常将MD5产生的字节数组交给BASE64再加密一把,得到相应的字符串。
SHA
SHA(Secure Hash Algorithm,安全散列算法),数字签名等密码学应用中重要的工具,被广泛地应用于电子商务等信息安全领域。虽然,SHA与MD5通过碰撞法都被破解了, 但是SHA仍然是公认的安全加密算法,较之MD5更为安全。
通过java代码实现如下:
- /**
- * SHA加密
- *
- * @param data
- * @return
- * @throws Exception
- */
- public static byte[] encryptSHA(byte[] data) throws Exception {
- MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
- sha.update(data);
- return sha.digest();
- }
- }
HMAC
HMAC(Hash Message Authentication Code,散列消息鉴别码,基于密钥的Hash算法的认证协议。消息鉴别码实现鉴别的原理是,用公开函数和密钥产生一个固定长度的值作为认证标识,用这个标识鉴别消息的完整性。使用一个密钥生成一个固定大小的小数据块,即MAC,并将其加入到消息中,然后传输。接收方利用与发送方共享的密钥进行鉴别认证等。
通过java代码实现如下:
- /**
- * 初始化HMAC密钥
- *
- * @return
- * @throws Exception
- */
- public static String initMacKey() throws Exception {
- KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
- SecretKey secretKey = keyGenerator.generateKey();
- return encryptBASE64(secretKey.getEncoded());
- }
- /**
- * HMAC加密
- *
- * @param data
- * @param key
- * @return
- * @throws Exception
- */
- public static byte[] encryptHMAC(byte[] data, String key) throws Exception {
- SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);
- Mac mac = Mac.getInstance(secretKey.getAlgorithm());
- mac.init(secretKey);
- return mac.doFinal(data);
- }
给出一个完整类,如下:
- import java.security.MessageDigest;
- import javax.crypto.KeyGenerator;
- import javax.crypto.Mac;
- import javax.crypto.SecretKey;
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
- /**
- * 基础加密组件
- *
- * @author 梁栋
- * @version 1.0
- * @since 1.0
- */
- public abstract class Coder {
- public static final String KEY_SHA = "SHA";
- public static final String KEY_MD5 = "MD5";
- /**
- * MAC算法可选以下多种算法
- *
- * <pre>
- * HmacMD5
- * HmacSHA1
- * HmacSHA256
- * HmacSHA384
- * HmacSHA512
- * </pre>
- */
- public static final String KEY_MAC = "HmacMD5";
- /**
- * BASE64解密
- *
- * @param key
- * @return
- * @throws Exception
- */
- public static byte[] decryptBASE64(String key) throws Exception {
- return (new BASE64Decoder()).decodeBuffer(key);
- }
- /**
- * BASE64加密
- *
- * @param key
- * @return
- * @throws Exception
- */
- public static String encryptBASE64(byte[] key) throws Exception {
- return (new BASE64Encoder()).encodeBuffer(key);
- }
- /**
- * MD5加密
- *
- * @param data
- * @return
- * @throws Exception
- */
- public static byte[] encryptMD5(byte[] data) throws Exception {
- MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
- md5.update(data);
- return md5.digest();
- }
- /**
- * SHA加密
- *
- * @param data
- * @return
- * @throws Exception
- */
- public static byte[] encryptSHA(byte[] data) throws Exception {
- MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
- sha.update(data);
- return sha.digest();
- }
- /**
- * 初始化HMAC密钥
- *
- * @return
- * @throws Exception
- */
- public static String initMacKey() throws Exception {
- KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
- SecretKey secretKey = keyGenerator.generateKey();
- return encryptBASE64(secretKey.getEncoded());
- }
- /**
- * HMAC加密
- *
- * @param data
- * @param key
- * @return
- * @throws Exception
- */
- public static byte[] encryptHMAC(byte[] data, String key) throws Exception {
- SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);
- Mac mac = Mac.getInstance(secretKey.getAlgorithm());
- mac.init(secretKey);
- return mac.doFinal(data);
- }
- }
再给出一个测试类:
- import static org.junit.Assert.*;
- import org.junit.Test;
- /**
- *
- * @author 梁栋
- * @version 1.0
- * @since 1.0
- */
- public class CoderTest {
- @Test
- public void test() throws Exception {
- String inputStr = "简单加密";
- System.err.println("原文:/n" + inputStr);
- byte[] inputData = inputStr.getBytes();
- String code = Coder.encryptBASE64(inputData);
- System.err.println("BASE64加密后:/n" + code);
- byte[] output = Coder.decryptBASE64(code);
- String outputStr = new String(output);
- System.err.println("BASE64解密后:/n" + outputStr);
- // 验证BASE64加密解密一致性
- assertEquals(inputStr, outputStr);
- // 验证MD5对于同一内容加密是否一致
- assertArrayEquals(Coder.encryptMD5(inputData), Coder
- .encryptMD5(inputData));
- // 验证SHA对于同一内容加密是否一致
- assertArrayEquals(Coder.encryptSHA(inputData), Coder
- .encryptSHA(inputData));
- String key = Coder.initMacKey();
- System.err.println("Mac密钥:/n" + key);
- // 验证HMAC对于同一内容,同一密钥加密是否一致
- assertArrayEquals(Coder.encryptHMAC(inputData, key), Coder.encryptHMAC(
- inputData, key));
- BigInteger md5 = new BigInteger(Coder.encryptMD5(inputData));
- System.err.println("MD5:/n" + md5.toString(16));
- BigInteger sha = new BigInteger(Coder.encryptSHA(inputData));
- System.err.println("SHA:/n" + sha.toString(32));
- BigInteger mac = new BigInteger(Coder.encryptHMAC(inputData, inputStr));
- System.err.println("HMAC:/n" + mac.toString(16));
- }
- }
控制台输出:
- 原文:
- 简单加密
- BASE64加密后:
- 566A5Y2V5Yqg5a+G
- BASE64解密后:
- 简单加密
- Mac密钥:
- uGxdHC+6ylRDaik++leFtGwiMbuYUJ6mqHWyhSgF4trVkVBBSQvY/a22xU8XT1RUemdCWW155Bke
- pBIpkd7QHg==
- MD5:
- -550b4d90349ad4629462113e7934de56
- SHA:
- 91k9vo7p400cjkgfhjh0ia9qthsjagfn
- HMAC:
- 2287d192387e95694bdbba2fa941009a
BASE64的加密解密是双向的,可以求反解。
MD5、SHA以及HMAC是单向加密,任何数据加密后只会产生唯一的一个加密串,通常用来校验数据在传输过程中是否被修改。其中HMAC算法有一个密钥,增强了数据传输过程中的安全性,强化了算法外的不可控因素。
单向加密的用途主要是为了校验数据在传输过程中是否被修改。
C# MD5 与 java MD5 生成的字符串不一致问题
C# 源码
查了下C#的api ,System.Text.UnicodeEncoding.Unicode.GetBytes(s)用的是utf-16 little-endian编码方式。
java 源码
public static String getMD5(String str, String encoding) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes(encoding));
byte[] result = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.length; i++) {
int val = result[i] & 0xff;
sb.append(Integer.toHexString(val));
}
return sb.toString();
}
运行结果
4b98b56b759916acc26268f2792a123
4b98b56b759916acc26268f2792a123
C# 计算字符串的哈希值(MD5、SHA)
一、关于本文
本文中是一个类库,包括下面几个函数:
1)计算32位MD5码(大小写):Hash_MD5_32
2)计算16位MD5码(大小写):Hash_MD5_16
3)计算32位2重MD5码(大小写):Hash_2_MD5_32
4)计算16位2重MD5码(大小写):Hash_2_MD5_16
5)计算SHA-1码(大小写):Hash_SHA_1
6)计算SHA-256码(大小写):Hash_SHA_256
7)计算SHA-384码(大小写):Hash_SHA_384
8)计算SHA-512码(大小写):Hash_SHA_512
编译后被打包成文件HashTools.dll,其他程序可以在添加引用后对这些函数进行调用
二、类库中各函数代码
0)类库结构
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HashTools
{
public class HashHelper
{
//各个函数
}
}
1)计算32位MD5码(大小写):Hash_MD5_32
/// <summary>
/// 计算32位MD5码
/// </summary>
/// <param name="word">字符串</param>
/// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
/// <returns></returns>
public static string Hash_MD5_32(string word, bool toUpper = true)
{
try
{
System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP
= new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
byte[] bytHash = MD5CSP.ComputeHash(bytValue);
MD5CSP.Clear();
//根据计算得到的Hash码翻译为MD5码
string sHash = "", sTemp = "";
for (int counter = 0; counter < bytHash.Count(); counter++)
{
long i = bytHash[counter] / 16;
if (i > 9)
{
sTemp = ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp = ((char)(i + 0x30)).ToString();
}
i = bytHash[counter] % 16;
if (i > 9)
{
sTemp += ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp += ((char)(i + 0x30)).ToString();
}
sHash += sTemp;
}
//根据大小写规则决定返回的字符串
return toUpper ? sHash : sHash.ToLower();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
2)计算16位MD5码(大小写):Hash_MD5_16
/// <summary>
/// 计算16位MD5码
/// </summary>
/// <param name="word">字符串</param>
/// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
/// <returns></returns>
public static string Hash_MD5_16(string word, bool toUpper = true)
{
try
{
string sHash = Hash_MD5_32(word).Substring(8, 16);
return toUpper ? sHash : sHash.ToLower();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
3)计算32位2重MD5码(大小写):Hash_2_MD5_32
/// <summary>
/// 计算32位2重MD5码
/// </summary>
/// <param name="word">字符串</param>
/// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
/// <returns></returns>
public static string Hash_2_MD5_32(string word, bool toUpper = true)
{
try
{
System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP
= new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
byte[] bytHash = MD5CSP.ComputeHash(bytValue);
//根据计算得到的Hash码翻译为MD5码
string sHash = "", sTemp = "";
for (int counter = 0; counter < bytHash.Count(); counter++)
{
long i = bytHash[counter] / 16;
if (i > 9)
{
sTemp = ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp = ((char)(i + 0x30)).ToString();
}
i = bytHash[counter] % 16;
if (i > 9)
{
sTemp += ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp += ((char)(i + 0x30)).ToString();
}
sHash += sTemp;
}
bytValue = System.Text.Encoding.UTF8.GetBytes(sHash);
bytHash = MD5CSP.ComputeHash(bytValue);
MD5CSP.Clear();
sHash = "";
//根据计算得到的Hash码翻译为MD5码
for (int counter = 0; counter < bytHash.Count(); counter++)
{
long i = bytHash[counter] / 16;
if (i > 9)
{
sTemp = ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp = ((char)(i + 0x30)).ToString();
}
i = bytHash[counter] % 16;
if (i > 9)
{
sTemp += ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp += ((char)(i + 0x30)).ToString();
}
sHash += sTemp;
}
//根据大小写规则决定返回的字符串
return toUpper ? sHash : sHash.ToLower();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
4)计算16位2重MD5码(大小写):Hash_2_MD5_16
/// <summary>
/// 计算16位2重MD5码
/// </summary>
/// <param name="word">字符串</param>
/// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
/// <returns></returns>
public static string Hash_2_MD5_16(string word, bool toUpper = true)
{
try
{
System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP
= new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
byte[] bytHash = MD5CSP.ComputeHash(bytValue);
//根据计算得到的Hash码翻译为MD5码
string sHash = "", sTemp = "";
for (int counter = 0; counter < bytHash.Count(); counter++)
{
long i = bytHash[counter] / 16;
if (i > 9)
{
sTemp = ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp = ((char)(i + 0x30)).ToString();
}
i = bytHash[counter] % 16;
if (i > 9)
{
sTemp += ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp += ((char)(i + 0x30)).ToString();
}
sHash += sTemp;
}
sHash = sHash.Substring(8, 16);
bytValue = System.Text.Encoding.UTF8.GetBytes(sHash);
bytHash = MD5CSP.ComputeHash(bytValue);
MD5CSP.Clear();
sHash = "";
//根据计算得到的Hash码翻译为MD5码
for (int counter = 0; counter < bytHash.Count(); counter++)
{
long i = bytHash[counter] / 16;
if (i > 9)
{
sTemp = ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp = ((char)(i + 0x30)).ToString();
}
i = bytHash[counter] % 16;
if (i > 9)
{
sTemp += ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp += ((char)(i + 0x30)).ToString();
}
sHash += sTemp;
}
sHash = sHash.Substring(8, 16);
//根据大小写规则决定返回的字符串
return toUpper ? sHash : sHash.ToLower();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
5)计算SHA-1码(大小写):Hash_SHA_1
/// <summary>
/// 计算SHA-1码
/// </summary>
/// <param name="word">字符串</param>
/// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
/// <returns></returns>
public static string Hash_SHA_1(string word, bool toUpper = true)
{
try
{
System.Security.Cryptography.SHA1CryptoServiceProvider SHA1CSP
= new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
byte[] bytHash = SHA1CSP.ComputeHash(bytValue);
SHA1CSP.Clear();
//根据计算得到的Hash码翻译为SHA-1码
string sHash = "", sTemp = "";
for (int counter = 0; counter < bytHash.Count(); counter++)
{
long i = bytHash[counter] / 16;
if (i > 9)
{
sTemp = ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp = ((char)(i + 0x30)).ToString();
}
i = bytHash[counter] % 16;
if (i > 9)
{
sTemp += ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp += ((char)(i + 0x30)).ToString();
}
sHash += sTemp;
}
//根据大小写规则决定返回的字符串
return toUpper ? sHash : sHash.ToLower();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
6)计算SHA-256码(大小写):Hash_SHA_256
/// <summary>
/// 计算SHA-256码
/// </summary>
/// <param name="word">字符串</param>
/// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
/// <returns></returns>
public static string Hash_SHA_256(string word, bool toUpper = true)
{
try
{
System.Security.Cryptography.SHA256CryptoServiceProvider SHA256CSP
= new System.Security.Cryptography.SHA256CryptoServiceProvider();
byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
byte[] bytHash = SHA256CSP.ComputeHash(bytValue);
SHA256CSP.Clear();
//根据计算得到的Hash码翻译为SHA-1码
string sHash = "", sTemp = "";
for (int counter = 0; counter < bytHash.Count(); counter++)
{
long i = bytHash[counter] / 16;
if (i > 9)
{
sTemp = ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp = ((char)(i + 0x30)).ToString();
}
i = bytHash[counter] % 16;
if (i > 9)
{
sTemp += ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp += ((char)(i + 0x30)).ToString();
}
sHash += sTemp;
}
//根据大小写规则决定返回的字符串
return toUpper ? sHash : sHash.ToLower();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
7)计算SHA-384码(大小写):Hash_SHA_384
/// <summary>
/// 计算SHA-384码
/// </summary>
/// <param name="word">字符串</param>
/// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
/// <returns></returns>
public static string Hash_SHA_384(string word, bool toUpper = true)
{
try
{
System.Security.Cryptography.SHA384CryptoServiceProvider SHA384CSP
= new System.Security.Cryptography.SHA384CryptoServiceProvider();
byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
byte[] bytHash = SHA384CSP.ComputeHash(bytValue);
SHA384CSP.Clear();
//根据计算得到的Hash码翻译为SHA-1码
string sHash = "", sTemp = "";
for (int counter = 0; counter < bytHash.Count(); counter++)
{
long i = bytHash[counter] / 16;
if (i > 9)
{
sTemp = ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp = ((char)(i + 0x30)).ToString();
}
i = bytHash[counter] % 16;
if (i > 9)
{
sTemp += ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp += ((char)(i + 0x30)).ToString();
}
sHash += sTemp;
}
//根据大小写规则决定返回的字符串
return toUpper ? sHash : sHash.ToLower();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
8)计算SHA-512码(大小写):Hash_SHA_512
/// <summary>
/// 计算SHA-512码
/// </summary>
/// <param name="word">字符串</param>
/// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
/// <returns></returns>
public static string Hash_SHA_512(string word, bool toUpper = true)
{
try
{
System.Security.Cryptography.SHA512CryptoServiceProvider SHA512CSP
= new System.Security.Cryptography.SHA512CryptoServiceProvider();
byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word);
byte[] bytHash = SHA512CSP.ComputeHash(bytValue);
SHA512CSP.Clear();
//根据计算得到的Hash码翻译为SHA-1码
string sHash = "", sTemp = "";
for (int counter = 0; counter < bytHash.Count(); counter++)
{
long i = bytHash[counter] / 16;
if (i > 9)
{
sTemp = ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp = ((char)(i + 0x30)).ToString();
}
i = bytHash[counter] % 16;
if (i > 9)
{
sTemp += ((char)(i - 10 + 0x41)).ToString();
}
else
{
sTemp += ((char)(i + 0x30)).ToString();
}
sHash += sTemp;
}
//根据大小写规则决定返回的字符串
return toUpper ? sHash : sHash.ToLower();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
三、函数调用
建立项目ComputeHash,添加对HashTools.dll库的引用。并添加代码:
using HashTools;
然后在Main函数中添加下列代码:
static void Main(string[] args)
{
Console.WriteLine("MD5 of \"abc\"");
Console.WriteLine("MD5_32(Upper): {0}",
HashHelper.Hash_MD5_32("abc"));
Console.WriteLine("MD5_32(Lower): {0}",
HashHelper.Hash_MD5_32("abc", false));
Console.WriteLine("MD5_16(Upper): {0}",
HashHelper.Hash_MD5_16("abc"));
Console.WriteLine("MD5_16(Lower): {0}",
HashHelper.Hash_MD5_16("abc", false));
Console.WriteLine("2_MD5_32(Upper): {0}",
HashHelper.Hash_2_MD5_32("abc"));
Console.WriteLine("2_MD5_32(Lower): {0}",
HashHelper.Hash_2_MD5_32("abc", false));
Console.WriteLine("2_MD5_32(Upper): {0}",
HashHelper.Hash_2_MD5_16("abc"));
Console.WriteLine("2_MD5_32(Lower): {0}",
HashHelper.Hash_2_MD5_16("abc", false));
Console.WriteLine("SHA of \"abc\"");
Console.WriteLine("SHA-1(Upper): {0}",
HashHelper.Hash_SHA_1("abc"));
Console.WriteLine("SHA-1(Lower): {0}",
HashHelper.Hash_SHA_1("abc", false));
Console.WriteLine("SHA-256(Upper): {0}",
HashHelper.Hash_SHA_256("abc"));
Console.WriteLine("SHA-256(Lower): {0}",
HashHelper.Hash_SHA_256("abc", false));
Console.WriteLine("SHA-384(Upper): {0}",
HashHelper.Hash_SHA_384("abc"));
Console.WriteLine("SHA-384(Lower): {0}",
HashHelper.Hash_SHA_384("abc", false));
Console.WriteLine("SHA-512(Upper): {0}",
HashHelper.Hash_SHA_512("abc"));
Console.WriteLine("SHA-512(Lower): {0}",
HashHelper.Hash_SHA_512("abc", false));
Console.ReadLine();
}
运行结果如下:
END
C#SHA-256与Java SHA-256.结果不同?
Java代码:
private static final byte[] SALT = "NJui8*&N823bVvy03^4N".getBytes(); public static final String getSHA256Hash(String secret) { try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(secret.getBytes()); byte[] hash = digest.digest(SALT); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { hexString.append(Integer.toHexString(0xFF & hash[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printstacktrace(); } throw new RuntimeException("SHA-256 realization algorithm not found in JDK!"); }
当我尝试使用the SimpleHash class时,我得到了不同的哈希值
更新:
例如:
Java:byte [] hash = digest.digest(SALT);
生成(前6个字节):
[0] = 9 [1] = -95 [2] = -68 [3] = 64 [4] = -11 [5] = 53 ....
C#代码(类SimpleHash):
string hashValue = Convert.ToBase64String(hashWithSaltBytes);
hashWithSaltBytes有(前6个字节):
[0] 175 byte [1] 209 byte [2] 120 byte [3] 74 byte [4] 74 byte [5] 227 byte
解决方法
试试这个:
digest.update(secret.getBytes("UTF-8"));
其次,Integer.toHexString method返回十六进制结果,没有前导0.
我们今天的关于MD5&SHA 加密 util 类和Java的分享就到这里,谢谢您的阅读,如果想了解更多关于BASE64、MD5、SHA、HMAC几种加密算法、C# MD5 与 java MD5 生成的字符串不一致问题、C# 计算字符串的哈希值(MD5、SHA)、C#SHA-256与Java SHA-256.结果不同?的相关信息,可以在本站进行搜索。
本文标签: