Apply HMAC SHA-512 algorithm using a secret key in python - c#

I am trying to Apply HMAC SHA-512 algorithm using a secret key in python but I am not finding the correct way to sign.
I was able to do using nodejs and c# but not for python
in nodejs
return crypto.createHmac('sha512', new Buffer(secretString, 'base64')).update(new Buffer(stringToSign)).digest('base64');
in c#
byte[] secretkeyBytes = Encoding.UTF8.GetBytes(apiSecret);
byte[] inputBytes = Encoding.UTF8.GetBytes(stringToSign);
using (var hmac = new HMACSHA512(secretkeyBytes))
{
byte[] hashValue = hmac.ComputeHash(inputBytes);
signature = System.Convert.ToBase64String(hashValue);
}
but in python I am not figuring a way to do that.
I already tried:
b_secret_string=base64.b64encode(secret_string.encode('utf-8'))
hash = hmac.new(base64.b64encode(b_secret_string),'',sha512)
hash.update(string_to_sign.encode('utf-8'))
signature = base64.b64encode(hash.digest())
and
hashed = hmac.new(str(secret_string.encode('utf-8')),'',sha512)
hashed.update(string_to_sign.encode('utf-8'))
signature = base64.b64encode(hashed.digest())
but it is not working. If possible can someone give me a light? I really appreciate it.
UPDATE:
Also tried with the following:
string_to_sign = string_to_sign.encode('utf-8')
secret_string = secret_string.encode('utf-8')
hash = hmac.new(secret_string, string_to_sign, hashlib.sha512)
signature = base64.b64encode(hash.digest())
tried using hexdigest() too:
signature = base64.b64encode(hash.hexdigest())
if someone wants to test it. Should return the same as this code in nodejs.
var crypto = require('crypto');
a = new Buffer('PRIVATE_KEY', 'base64');
hash = crypto.createHmac('sha512', a)
stringToSign = 'Stack OverFlow Funtime';
hash.update(new Buffer(stringToSign));
console.log(hash.digest('base64'));
$ node example.js
ugmH0VdttdAxGdpzNJnaNn1KlVS4wBzoK//dsPuvK65Zsl8FgT+3aLGnsEubThlv5/3chfyMmsUH//LdS1MXqg==

I found a way to do the same in python. Answering here if someone pass for the same issue in future.
hmac_key = base64.b64decode(secret_string)
signature = hmac.new(hmac_key, string_to_sign, hashlib.sha512)
signature_b64 = signature.digest().encode('base64')
signature_lines = signature_b64.splitlines()
signature_b64 = ''.join(signature_lines)

How about:
import hashlib
print hashlib.sha512('some string').hexdigest()

Related

bouncycastle How to determine first byte (recovery ID) for ECDSA signatures

I'm using BouncyCastle to sign transactions for the EOS blockchain. Similar to Bitcoin signatures, the signature needs to have a "recovery ID" as the 1st bytes. My code looks as follows:
var curve = SecNamedCurves.GetByName("secp256r1");
var domain = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
var p = new Org.BouncyCastle.Math.BigInteger(privateKey);
var keyParameters = new ECPrivateKeyParameters(
new Org.BouncyCastle.Math.BigInteger(1,privateKey),
domain);
ISigner signer = SignerUtilities.GetSigner("SHA-256withPLAIN-ECDSA");
signer.Init(true, keyParameters);
signer.BlockUpdate(message, 0, message.Length);
var signature = signer.GenerateSignature();
This seems to work as expected but I'm unable to get the recovery ID.
Here's an example of how another library does this.
https://github.com/EOSIO/eosjs-ecc/blob/a806b93fbbccec8d38c0c02998d204ff2040a6ae/src/ecdsa.js#L199
Can someone explain how I can do that same using BouncyCastle please?
This was another post that seemed helpful, but wasn't specific to how to do this with BouncyCastle https://bitcoin.stackexchange.com/questions/83035/how-to-determine-first-byte-recovery-id-for-signatures-message-signing

Importing an Objective-C RSA public key into c# RSACryptoServiceProvider

Here is the Objective-C we are using to generate the RSA object using the following lib: https://github.com/kuapay/iOS-Certificate--Key--and-Trust-Sample-Project
BDRSACryptor *rsa = [[BDRSACryptor alloc] init];
BDRSACryptorKeyPair *RSAKeyPair = [rsa generateKeyPairWithKeyIdentifier:nil error:error];
We then pass RSAKeyPair.publicKey to our c#, where using the BouncyCastles library:
using (TextReader sr = new StringReader(pempublic))
{
var pemReader = new PemReader(sr);
var temp = (RsaKeyParameters)pemReader.ReadObject();
var RSAKeyInfo = new RSAParameters
{
Modulus = temp.Modulus.ToByteArray(),
Exponent = temp.Exponent.ToByteArray()
};
var rsaEncryptor = new RSACryptoServiceProvider();
rsaEncryptor.ImportParameters(RSAKeyInfo);
}
There are no errors, but the encryption is different. The same string encrypted in c# and obj-c are different, and we are unable to encrypt on one end and decrypt on the other.
Help!
Edit: Willing to consider any methodology of exchanging public keys between c# and obj-c. This is just the closest we have come so far.
Edit2: Contents of pempublic
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/ugxekK+lY0VLeD8qA5nEhIn7IzBkgcrpiEM109chFxHobtvWEZbu8TqTIBtIgtISNp4idcEvahPniEyUawjmRSWB7uYmcHJ3pWaIo5/wBthmGrqS/XjedVXT6RuzaoPf9t0YXyW6YiH1kQZn4gjZF51O6iIk2+VnfkYVqeKBtQIDAQAB-----END PUBLIC KEY-----
Edit3: Regarding padding: C# and obj-c are both using OEAP padding.
Edit4: How the text is being encrypted: c#
byte[] testBytes = Encoding.UTF8.GetBytes("1234567890");
byte[] encryptedBytes = rsaEncryptor.Encrypt(testBytes, true);
string base64 = Convert.ToBase64String(encryptedBytes);
obj-c
NSString *encrypted = [rsa encrypt:#"1234567890" key:RSAKeyPair.publicKey error:error];
Final Edit:
Solved by using the Chilkat encryption library on the .NET server. We are now able to load an RSA encryptor from a public key in both XML and PEM format generated from a .NET, Java, or Objective-C Client. If anyone could explain why the .NET RSACryptoServiceProvider wouldn't work, we are all quite curious.
please check my answer to my own question
RSA C# encryption with public key to use with PHP openssl_private_decrypt(): Chilkat, BouncyCastle, RSACryptoServiceProvider
i think it may be helpful
to make it short, try using temp.Modulus.ToByteArrayUnsigned()
I wrote RSA and AES implementation using CommonCrypto, implementation is done in order to be interoperable with .NET
Check it out
https://github.com/ozgurshn/EncryptionForiOS
I used base64 encoding
.NET side could be
public string RsaDecryption(byte[] cipherText, string privateKey)
{
var cspDecryption = new RSACryptoServiceProvider();
cspDecryption.FromXmlString(privateKey);
var bytesPlainTextData = cspDecryption.Decrypt(cipherText, false);
return Encoding.UTF8.GetString(bytesPlainTextData);
}
public byte[] RsaEncryption(string plainText, string publicKey)
{
var cspEncryption = new RSACryptoServiceProvider();
cspEncryption.FromXmlString(publicKey);
var bytesPlainTextData = Encoding.UTF8.GetBytes(plainText);
var bytesCypherText = cspEncryption.Encrypt(bytesPlainTextData, false);
return bytesCypherText;
}

Using an RSA Public key to decrypt a string that was encrypted using an RSA private key

This is a duplicate of an unanswered question here: Using an RSA Public Key to decrypt a string that was encrypted using RSA Private Key
You can see the author found a solution using some code from here:
http://www.codeproject.com/KB/security/PrivateEncryption.aspx
Using code from that link looks very promising. The only thing missing is the padding. I typically use PKCS1.5 padding which is the default for OpenSSL RSA.
I know the answer to this question is very close. I know the only thing holding back decryption is the pkcs1.5 padding on the encrypted openssl ciphertext.
I was surprised to see how little information is out there on this subject because there are many situations where you would need a server to encrypt something, sign something, etc, and have a client application verify, decrypt, etc with the public key.
I also extensively tried using the RSACryptoServiceProvider to verify hash's resulting from the encryption using OpenSSL. For example, I would do a private key encryption using a SHA256 hash of the plaintext, then try to do a RSACryptoServiceProvider verify on that signature, and it does not work. I think the way MS does this is non standard and there are perhaps special customization at work with that.
So, the alternative is this question, which is simply taking private key encrypted ciphertext and using C# to decrypt it, thus, verifying it's authenticity. Hashes can be incorporated to make a simple signature verification system for data objects signed by the server and verified on the client.
I've looked through the PKCS1 RFC's, OpenSSL rsa source code, and other projects, I cannot get a solid answer on how to account for PKCS1 padding when doing my RSA Decrypt. I cannot locate where in the OpenSSL source code they handle the PKCS1 padding, otherwise, I might have an answer by now.
Also, this is my first question, I know it's a duplicate of an unanswered question, so, what to do? I googled that too, and found nothing.
The other thing I don't understand is why my decrypt method doesn't work. Since padding is removed after decryption, my decrypted data should resemble plaintext, and it's not even close. So, I'm almost sure that pkcs1 padding means that other things are happening, specifically, to the ciphertext which means that the ciphertext must be preprocessed prior to decryption to remove padding elements.
Perhaps simply filtering the ciphertext to remove padding elements is the simplest solution here...
Here is my Decrypt method:
public static byte[] PublicDecryption(this RSACryptoServiceProvider rsa, byte[] cipherData)
{
if (cipherData == null)
throw new ArgumentNullException("cipherData");
BigInteger numEncData = new BigInteger(cipherData);
RSAParameters rsaParams = rsa.ExportParameters(false);
BigInteger Exponent = GetBig(rsaParams.Exponent);
BigInteger Modulus = GetBig(rsaParams.Modulus);
BigInteger decData = BigInteger.ModPow(numEncData, Exponent, Modulus);
byte[] data = decData.ToByteArray();
byte[] result = new byte[data.Length - 1];
Array.Copy(data, result, result.Length);
result = RemovePadding(result);
Array.Reverse(result);
return result;
}
private static byte[] RemovePadding(byte[] data)
{
byte[] results = new byte[data.Length - 4];
Array.Copy(data, results, results.Length);
return results;
}
The problem isn't with the padding. In fact, removing padding values from decrypted ciphertext is actually very simple. The problem was with the software at this location:
You can see the author found a solution using some code from here: http://www.codeproject.com/KB/security/PrivateEncryption.aspx
And with Microsoft's implementation of System.Numeric which simply cannot handle larger integers...
To fix the issue, I looked at previous releases of code on the codeproject site and ended up with this PublicDecrypt method.
public static byte[] PublicDecryption(this RSACryptoServiceProvider rsa, byte[] cipherData)
{
if (cipherData == null)
throw new ArgumentNullException("cipherData");
BigInteger numEncData = new BigInteger(cipherData);
RSAParameters rsaParams = rsa.ExportParameters(false);
BigInteger Exponent = new BigInteger(rsaParams.Exponent);
BigInteger Modulus = new BigInteger(rsaParams.Modulus);
BigInteger decData2 = numEncData.modPow(Exponent, Modulus);
byte[] data = decData2.getBytes();
bool first = false;
List<byte> bl = new List<byte>();
for (int i = 0; i < data.Length; ++i)
{
if (!first && data[i] == 0x00)
{
first = true;
}
else if (first)
{
if (data[i] == 0x00)
{
return bl.ToArray();
}
bl.Add(data[i]);
}
}
if (bl.Count > 0)
return bl.ToArray();
return new byte[0];
}
That will perfectly decrypt ciphertext created by openssl using the rsautl utility, or the Perl Crypt::OpenSSL::RSA private_encrypt method.
The other big change was dropping the Microsoft BitInteger library which simply didn't work. I ended up using the one mentioned in the Code Project article , and found here:
http://www.codeproject.com/Articles/2728/C-BigInteger-Class
The key here is to set the maxintsize in the library to a value which is larger based on how big of a key size you are using. For 4096 bit, a value of 500 worked fine (approx length of the modulus).
Here is the calling method:
var encmsg3 = "JIA7qtOrbBthptILxnurAeiQM3JzSoi5WiPCpZrIIqURKfVQMN1BrondF9kyNzbjTs1DaEKEuMBVwKExZe22yCvXXpm8pwcEGc9EHcVK2MPqNo89tIF8LJcaDqBMwLvxdaa/QgebtpmOVN/TIWfuiV8KR+Wn07KwsgV+3SALbNgbOIR3RtCx3IiQ3tZzybJb08+ZKwJEOT011uwvvGmtJskQgq9PC8kr1RPXMgaP6xMX7PHFJ8ORhkuWOFfCh+R4NhY1cItVhnRewKpIC2qVlpzUYRAgKIKdCXuZDqUQdIponR29eTovvLb0DvKQCLTf9WI1SzUm6pKRn0vLsQL7L3UYHWl43ISrTpDdp+3oclhgRF3uITR4WCvoljephbGc6Gelk5z3Vi6lN0oQaazJ7zIen+a/Ts7ZX3KKlwPl4/lAFRjdjoqu7u4IAK7O7u1Jf2xDiGw18C/eGt8UHl09zU4qQf9/u+7gtJ+10z2NERlLSaCDjVqslwmmxu81pG2gCv8LfpR4JlPaFfBZMGfGBihyGryWhJwizUXXo8wgdoYbHRXe8/gL19qro0ea5pA9aAhDjTpX1Zzbwu2rUU7j6wtwQtUDJOGXXCw1VOHsx6WXeW196RkqG72ucVIaSAlx5TFJv8cnj6werEx1Ung5456gth3gj19zHc8E/Mwcpsk=";
byte[] enc = Convert.FromBase64String(encmsg3);
var dec = rsa2.PublicDecryption(enc);
Debug.Print("PLAINTEXT: " + Encoding.UTF8.GetString(dec));
The only last thing someone would need to completely replicate this would be getting the private key into openssl format so that they could pass the private and public keys back and forth between openssl and C#.
I used openssl.net, and created an RSA instance, and set all the variables using bignumbers. Here's the code for that:
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(Properties.Resources.RSAParameters);
RSAParameters par = rsa.ExportParameters(true); // export the private key
using (OpenSSL.Crypto.RSA rsaos = new OpenSSL.Crypto.RSA())
using (BigNumber bnmod = BigNumber.FromArray(par.Modulus))
using (BigNumber bnexp = BigNumber.FromArray(par.Exponent))
using (BigNumber bnD = BigNumber.FromArray(par.D))
using (BigNumber bnP = BigNumber.FromArray(par.P))
using (BigNumber bnQ = BigNumber.FromArray(par.Q))
using (BigNumber bnDmodP = BigNumber.FromArray(par.DP))
using (BigNumber bnDmodQ = BigNumber.FromArray(par.DQ))
using (BigNumber bnInverse = BigNumber.FromArray(par.InverseQ))
{
rsaos.PublicExponent = bnexp;
rsaos.PublicModulus = bnmod;
rsaos.IQmodP = bnInverse;
rsaos.DmodP1 = bnDmodP;
rsaos.DmodQ1 = bnDmodQ;
rsaos.SecretPrimeFactorP = bnP;
rsaos.SecretPrimeFactorQ = bnQ;
rsaos.PrivateExponent = bnD;
string privatekey = rsaos.PrivateKeyAsPEM;
string publickey = rsaos.PublicKeyAsPEM
}
With that you can easily create an RSA key, export everything to OpenSSL, and encrypt/decrypt anything you want within reason. It is enough to handle private key encryption followed by public key decryption.
Cool.
There is a problem in the line in the PublicDecryption function:
BigInteger numEncData = new BigInteger(cipherData);
it shall be:
BigInteger numEncData = GetBig(cipherData);
This line shall also be removed:
Array.Reverse(result);
You may encounter some padding problem, but if you can get the data right, it shall be easy to correct that.

C# RSA Decryption using Bouncy Castle

I have been given a Base64 Encoded encrypted string, which was encrypted in Java using Bouncy Castle. Example Java snippet below:
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
byte[] encryptedText = cipher.doFinal("xxxxx|xxxxx".getBytes("UTF-8"));
String encodedText = new BASE64Encoder().encode(encryptedText);
I need to decrypt the resulting string using Bouncy Castle, but in C#
I have been given a code snippet on how to do this in Java, but I can't convert this for C# (reasons is we are building a .net site, and is going to be an iFrame within a Java site. The Java site is going to passing in the RSA Encrypted string to the .NET site). Example Java code to decrypt below:
Cipher cipherDec = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipherDec.init(Cipher.DECRYPT_MODE, key.getPrivate());
byte[] decodedText = new BASE64Decoder().decodeBuffer(encodedText);
byte[] decryptedText = cipherDec.doFinal(decodedText);
String finalValue = new String(decryptedText, "UTF-8");
I have downloaded the examples from http://www.bouncycastle.org/csharp/ but there doesn't seem to be an example of inputting a string value to get encrypted, and it then going though the encrypt/decrypt process.
I have been given values for modulus, public exponent, private expontent, prime P, prime q, prime exponent p, prime exponent q and crt coefficient.
I have seen that I can use the following:
IAsymmetricBlockCipher signer = new Pkcs1Encoding(new RsaEngine());
signer.Init(true, pubParameters);
But the signer object doesn't seem to have the same methods as the Java examples above.
Only method I can use is
ProcessBlock(byte[] inbuf, int inOff, int inLen);
But I can't see how to use this in my context.
Any help here would be most appreciated.
To Help others, the final code to convert is as follows:
RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef);
RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp);
IAsymmetricBlockCipher eng = new Pkcs1Encoding(new RsaEngine());
eng.Init(false, privParameters);
byte[] encdata = System.Convert.FromBase64String("{the enc string}");
encdata = eng.ProcessBlock(encdata, 0, encdata.Length);
string result = Encoding.UTF8.GetString(encdata);
mod, pubExp etc etc are all BigInteger values:
static BigInteger mod = new BigInteger("big int value");
The Following using directives are required:
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Math;
Which can be obtained from the bouncycastle site. http://www.bouncycastle.org/csharp/
Have you tried converting the base 64 string to a byte array and then using the process block method? There may be more to it than that but it's definitely the first step I would take.
Here's an example of how to do this: http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx
I'm not sure I understand why you must use Bouncycastle. The following small code snippet shows and RSA encryption/decryption example using only .NET classes:
using System;
using System.Text;
using System.Security.Cryptography;
namespace RsaForDotNet
{
class Program
{
static void Main(string[] args)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(512);
var encrypted_msg = rsa.Encrypt(Encoding.UTF8.GetBytes("Secret Data"), false);
var encoded_msg = Convert.ToBase64String(encrypted_msg);
Console.WriteLine(encoded_msg);
var decoded_msg = Convert.FromBase64String(encoded_msg);
var decrypted_msg = Encoding.UTF8.GetString(rsa.Decrypt(decoded_msg, false));
Console.WriteLine(decrypted_msg);
}
}
}

HMACSHA1 from C# To PHP

I am trying to understand these line of code from C# (.Net) method to create a signature. However, I would like to do the same in PHP but not quite understand what it does in C#.
I wonder if any .net developer out there can help me to interpret the code below in 'English'?
Many thanks
HMAC hasher;
Byte[] utf8EncodedString = Encoding.UTF8.GetBytes(String.Format("{0}:{1}:{2}", MethodName, TimeStamp, AccessID));
hasher = HMACSHA1.Create();
hasher.Key = Encoding.UTF8.GetBytes(AccessKey);
Byte[] hashResult = hasher.ComputeHash(utf8EncodedString);
return Convert.ToBase64String(hashResult);
Here is my PHP code. Is this correct?
$signatureString = $methodName.':'.$timeStamp.':'.$accessID;
return hash_hmac('sha1', $signatureString, $accessKey, false);
Update: 30-05-2012
Just got it to work now
$signature = base64_encode(hash_hmac('sha1', $signatureString, $accessKey,true));
Answer on php.net for you http://www.php.net/manual/ru/function.hash-hmac.php#105099

Categories