Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the C# equivalent of the Java SecretKeySpec

I have following code written in 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);

I want to make same example in C#. So, I wrote following code

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);

Final results are not equal. secretKeyBArr and contentBArr are byte array and their values are same in both example. What is unknown is SecretKeySpec passed to mac.init(). So, what is equivalent same class in C#?

like image 448
user1810618 Avatar asked Dec 11 '12 22:12

user1810618


People also ask

What is C used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C language in simple words?

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.

What does %c mean in C?

%d is used to print decimal(integer) number ,while %c is used to print character . If you try to print a character with %d format the computer will print the ASCII code of the character.


1 Answers

The results are identical, but Java uses signed bytes while C# uses unsigned bytes by default.

Furthermore, SecretKeySpec itself normally does not change the underlying data. You need to e.g. put a DES key specification in a SecretKeyFactory to make sure that the parity bits are set correctly (in the resulting SecretKey). So there is no need for an equivalent as the class itself does very little except wrapping the data.

like image 134
Maarten Bodewes Avatar answered Sep 20 '22 15:09

Maarten Bodewes