[英]Convert ComputeHash using SHA1 algorithm in C# to Java
I have a function to encrypt a string with the SHA1 algorithm in C#. 我有一个使用C#中的SHA1算法加密字符串的函数。 And now I would like to convert exactly it to Java language. 现在,我想将其准确转换为Java语言。 I have tried, but I don't get the same output for C# and Java. 我已经尝试过,但是对于C#和Java我没有得到相同的输出。
Someone kindly please help me convert it. 有人请帮我转换一下。 I'm really grateful for this. 我对此非常感激。 Thanks. 谢谢。
Here is C# code : 这是C#代码:
public static string ComputeHash(string inString) {
SHA1 sh = SHA1.Create();
byte[] data = UTF8Encoding.UTF8.GetBytes(inString);
byte[] result = sh.ComputeHash(data);
return ToHexString(result);
}
public static string ToHexString(byte[] data) {
string s = "";
for (int i = 0, n = data.Length; i < n; i++) {
s += String.Format("{0:X2}", data[i]);
}
return s;
}
I've changed code and get same output for C# and Java. 我更改了代码,并为C#和Java获得了相同的输出。 Here is my Java Code : 这是我的Java代码:
public static String ComputeHash(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException{
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.reset();
md.update(password.getBytes("UTF-8"));
return toHexString(md.digest());
}
private static String toHexString(byte[] data){
Formatter formatter = new Formatter();
for(byte b : data){
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
With same string input : "abc123", I got same result : 6367C48DD193D56EA7B0BAAD25B19455E529F5EE 使用相同的字符串输入:“ abc123”,我得到相同的结果:6367C48DD193D56EA7B0BAAD25B19455E529F5EE
Thanks M. Schena , I got my solution in your comment. 感谢M. Schena,您的评论中有我的解决方案。 Thank so much ! 非常感谢 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.