什么是Java SecretKeySpec的C#等价物

use*_*618 9 c# java cryptography sha1 hmac

我有以下用Java编写的代码

Mac mac = Mac.getInstance("HmacSHA1");
String secretKey ="sKey";
String content ="Hello";

byte[] secretKeyBArr = secretKey.getBytes();    
byte[] contentBArr = content.getBytes();

SecretKeySpec secret_key = new SecretKeySpec(secretKeyBArr,"HmacSHA1");
byte[] secretKeySpecArr = secret_key.getEncoded();

mac.init(secret_key);

byte[] final = mac.doFinal(contentBArr);
Run Code Online (Sandbox Code Playgroud)

我想在C#中做同样的例子.所以,我写了下面的代码

HMACSHA1 hmacsha1 = new HMACSHA1();
string secretKey = "sKey";
string content = "Hello";

byte[] secretKeyBArr = Encoding.UTF8.GetBytes(secretKey);
byte[] contentBArr = Encoding.UTF8.GetBytes(content);

hmacsha1.Key = secretKeyBArr;
byte[] final = hmacsha1.ComputeHash(contentBArr);
Run Code Online (Sandbox Code Playgroud)

最终结果并不相同.secretKeyBArr和contentBArr是字节数组,它们的值在两个示例中都相同.未知的是传递给mac.init()的SecretKeySpec.那么,什么是C#中相同的同类?

Maa*_*wes 1

结果是相同的,但 Java 使用有符号字节,而 C# 默认使用无符号字节。

此外,SecretKeySpec它本身通常不会改变底层数据。例如,您需要将 DES 密钥规范放入 a 中SecretKeyFactory,以确保奇偶校验位设置正确(在结果中SecretKey)。因此不需要等效的类,因为类本身除了包装数据之外几乎没有做任何事情。