Currently I perform this operation through openssl, and I have had no problem with the generated file
openssl dgst -sha256 -sign privateKey.key -out file.txt.signature file.txt
Now, we want to automate the generation of the file using C #, but I have not been able to get the same result.
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(CreateToken("key...", "text"));
Console.ReadLine();
}
public static string CreateToken(string key, string message)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(key);
HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
byte[] messageBytes = encoding.GetBytes(message);
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return System.Text.Encoding.UTF8.GetString(hashmessage);
}
}
I'm new to working with this, what would be the right way?
Am I not retrieving the information properly ?, Should I get the content directly from the file?
Thank you very much.
Signature generation is not the same thing as HMAC message authentication and it uses a different key. As HMAC can use a key of any size, it will probably take the private key, but that's not how it is supposed to work. RSA is an asymmetric algorithm that uses private and public keys, MAC uses symmetric, secret keys. The dgst -sign instead uses RSA PKCS#1 v1.5 padding to sign the file.
From the OpenSSL Wiki on dgst:
When signing a file, dgst will automatically determine the algorithm (RSA, ECC, etc) to use for signing based on the private key's ASN.1 info. When verifying signatures, it only handles the RSA, DSA, or ECDSA signature itself, not the related data to identify the signer and algorithm used in formats such as x.509, CMS, and S/MIME.
HMAC is not the same thing as SHA-256 either. RSA signature generation uses a hash, not a HMAC. You should use the SHA256 class to create a hash. HMAC is a message authentication code build using the SHA-256 hash. However, the SHA class is not needed as signature generation usually includes the hash generation (you sign a message, not a hash value).
So to create a signature, take a look at the RSAPKCS1SignatureFormatter class, it includes an example at the bottom. Try again using this example.
Make sure your message only contains ASCII (both in the text file as in your string) or your result may fail as well.
I'm working on some software that exchanges XML documents with a server. The server signs the XML using XMLDSIG and the client should verify the signature before trusting the XML. I'm using RSACryptoServiceProvider to do this. The XML is signed, but not encrypted.
I'm following the basic procedure explained in:
How to Sign XML Documents with Digital Signatures
How to Verify the Digital Signatures of XML Documents
This requires that the client software has the public key available. I want the distribution of the client software to be as simple as possible and I don't want the client to have to deal with certificates. The pair of documents referenced above conveniently skirt around the subject of distributing the public key, simply stating that the user "needs to have the same key". I don't particularly want the end user to even be aware that they have a public key, so asking them to mess around with certificates is out of the question. Since the public key is public, what I would like to do is somehow embed it within the client software. As I see it, my options are:
Install the public key during the setup process
Somehow embed the public key into the software itself, possibly within the App.config file
Is this feasible in practice? What is the simplest way of achieving this that doesn't require any user interaction or awareness?
You don't have to distribute the certificate. One of common approaches is to include the certificate in the signed document, in the KeyInfo/X509Data node.
The validation can use the embedded certificate easily and the only required infrastructure element at the client side is the certificate thumbprint and subject name. In other words, client validates the document using included certificate and then easily checks the certificate agaist the subject name and thumbprint. In case of a match, there is the assumption that a correct certificate has been provided.
Read more about technical details in one of my blog entries (this is a 3 part tutorial so you can also take a look at all other entries). Anyway, no importing certificates and no including certificates with your software, rather you have two string configuration parameters.
The embedded certificate inside the XmlDsigned document has a const size and usually the overhead is neglectable.
http://www.wiktorzychla.com/2012/12/interoperable-xml-digital-signatures-c.html
http://www.wiktorzychla.com/2012/12/interoperable-xml-digital-signatures-c_20.html
Am not sure what problem you're facing without seeing your code but, could this answer from Ji Zhou help?
public static void Main()
{
try
{ //initialze the byte arrays to the public key information.
byte[] PublicKey = {214,46,220,83,160,73,40,39,201,155,19,202,3,11,191,178,56,
74,90,36,248,103,18,144,170,163,145,87,54,61,34,220,222,
207,137,149,173,14,92,120,206,222,158,28,40,24,30,16,175,
108,128,35,230,118,40,121,113,125,216,130,11,24,90,48,194,
240,105,44,76,34,57,249,228,125,80,38,9,136,29,117,207,139,
168,181,85,137,126,10,126,242,120,247,121,8,100,12,201,171,
38,226,193,180,190,117,177,87,143,242,213,11,44,180,113,93,
106,99,179,68,175,211,164,116,64,148,226,254,172,147};
//Values to store encrypted symmetric keys.
byte[] EncryptedSymmetricKey;
byte[] EncryptedSymmetricIV;
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//Get an instance of RSAParameters from ExportParameters function.
RSAParameters RSAKeyInfo = RSA.ExportParameters(false);
//Set RSAKeyInfo to the public key values.
RSAKeyInfo.Modulus = PublicKey;
//Import key parameters into RSA.
RSA.ImportParameters(RSAKeyInfo);
//Create a new instance of the RijndaelManaged class.
RijndaelManaged RM = new RijndaelManaged();
//Encrypt the symmetric key and IV.
EncryptedSymmetricKey = RSA.Encrypt(RM.Key, false);
EncryptedSymmetricIV = RSA.Encrypt(RM.IV, false);
Console.WriteLine("RijndaelManaged Key and IV have been encrypted with RSACryptoServiceProvider.");
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
}
I have a .xml file that has to be signed with digital certificate in format of PKCS#7 version 1.5 (RFC 2315) and DER (ITU-T Recommendation X.690
That .xml will be send to a govt. WebService that only accept the format I mentioned upwards.
What I'm able to do - thanks to this website is digitaly sign .xml with the .pfx file that I generated with Certificate Export Wizard explained below. The class that I'm using to sign is down on mentioned website or here.
From what I tried to understand so far I will need to sign the .xml with .pfx file according to X.690 standards but I'm only able to access this namespace:
using System.Security.Cryptography.X509Certificates;
which is obviously for X.509 format.
Note:
There are several things I'm confused about - to export the certificate into .pfx I'm using Internet Explorer - Certificate Export Wizard from there I'm able to:
Yes - export private keys - then it will be generated in PKCS#12 but .pfx
No - do not export private keys - Certificate according to standards Cryptographic Message Syntax Standard - PKCS#7 that I guess I need but I would receive .p7b file
I must say that I am a newbie in certificates and digital signatures so I'm not even sure if I'm correctly exporting the certificat and the second thing is how I can sign according to X.690 standards.
May I know how to sign according to X.690 format please?
Thank you everyone for your time and replies.
My code is following:
bool res = false;
try
{
byte[] certBytes = System.IO.File.ReadAllBytes(pvkPath);
X509Certificate2 cert = new X509Certificate2(certBytes, certPass);
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
// sign the document with the private key of the certificate
XmlDsig.SignXml(doc, cert);
// save the document
doc.Save(xmlSavePath);
// verify that the document has a signature
bool hasSignature = XmlDsig.HasSignatureElement(doc);
return res = true;
}
catch (Exception)
{ return res; }
foDigital signature in PKCS#7/CMS format is blob that contains your XML data + signer's x509 public key certificate (.cer file) + Digital signature. The entire blob is encoded in ASN 1.0 format(X690). There may be variations in the blob due to the absence of original data or the signer certificate, This variation is called detached signatures.
Digital signature is generated when you sign your xml file with the signer's private key. This signature can be verified when you send your XML file + signer's public key (as X509 .cer file)+ digital signature to the party who are interested in verifying it.
PFX/p12 is a container that contains both the signer's private key and public key. You get this key pair from either your government or your government approved key custodians. You will then use this PFX to perform digital signature.
PKCS#7 is supported by cryptoAPI.
The above are the basics. This should allow you make your queries more clearly.
After looking at how to generate self-signed digital signatures from Creating a self-signed certificate in C#, I can call CreateSelfSignCertificatePfx and get PXF data in a byte array back, which can then be used within an X509Certificate2 object to sign and verify. Example...
byte[] pfx = Certificate.CreateSelfSignCertificatePfx("O=Company,CN=Firstname,SN=Lastname", DateTime.Now, DateTime.Now.AddYears(1), "password");
X509Certificate2 cert = new X509Certificate2(pfx, "password");
byte[] publicBytes = cert.RawData;
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
byte[] signedData = rsa.SignData(new System.Text.UTF8Encoding().GetBytes("Test"), new SHA1CryptoServiceProvider());
RSACryptoServiceProvider rsa2 = (RSACryptoServiceProvider)new X509Certificate2(publicBytes).PublicKey.Key;
bool verified = rsa2.VerifyData(new System.Text.UTF8Encoding().GetBytes("Test"), new SHA1CryptoServiceProvider(), signedData);
This works. My concern though is the original bytes, byte[] pfx from above, need to be stored in a DB (to sign stuff). The question becomes, how secure are the bytes in this format? I know you need the password to construct the new X509Certificate2 with a private key, but in a general sense, how secure are the bytes without the password? I have no problems encrypting these bytes as an added layer, but is that necessary?
According to X509Certificate2.X509Certificate2(Byte[], String) Constructor
Calling this constructor with the correct password decrypts the private key and saves it to a key container.
I just want to ensure the private key is safe without the password.
In my eyes the question is not whether you should put the "bytes" in the database, but more, would you put the file with the private key in your file system.
In the way you're doing it, it's essentially the same thing. You're just storing the bytes that make up the cert file.
I may be failing to understand the difference here, but they bytes and the file are essentially the same thing, the only difference being the fact that one has to gain access to the db to get them.
Use a smartcard or token to store your private key.
UPDATE:
The Pvt key can be accessed by anyone who can access the machine.
The private keys in a PFX (PKCS#12) are stored encrypted, which is of course what the password is for. Not all of a PFX is encrypted, the structural pieces stay plaintext to contain metadata about the contents (like what encryption algorithm was used).
Based on inspecting the file, as of Windows 7 the private keys are encrypted using 3-key (168-bit) 3DES. The key is derived via a complex formula involving your password; there's nothing saved in the file which gives any indication as to what your password was, how long it was, et cetera.
The password is usually proven correct by the addition of a MAC on the contents, which uses the same password for its key derivation function. In the possible case of the MAC password and the encryption password being different (which I've personally never seen) the password is verified by the structural information in the encrypted payload.
DES' weakness mainly lay in the small keysize, it's easily brute forcable today. A 3-key 3DES key has 112 more semantic bits than a (1)DES key, making it take 2^112 (~5 x 10^33) times longer to break.
So, at the end of the day, the private key is cryptographically sound. But like anything with a password-based input, if you use a bad password that is easily guessed then it can be cracked by brute force.
I've generate a self-signed certificates(X509 certificate) and want to use the private key to sign some document to make digital signature and I'm doing it in C#.
How can I import .pvk file? Do I need to import from key store?
And can I use this code to sign and create a digital signature?
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA);
RSAFormatter.SetHashAlgorithm("SHA1");
RSAFormatter.SetKey(cert.PrivateKey);
byte[] SignedHash = RSAFormatter.CreateSignature(data);
Try tho Initialize your RSA like this:
RSACryptoServiceProvider RSA = (RSACryptoServiceProvider)cert.PrivateKey;
To generate a signature I use rsa.SignData(data, "sha1");
First of all you need to determine, in what format the signature should be made. If you deal with certificates, most likely you will create PKCS#7 or CMS signature. There's a class in .NET for CMS signatures.
The next steps depend on whether you need certificate-based PKCS#7 signature or RSA (PKCS#1) signature.
Side note - putting several questions into one makes it hard to answer properly. Also most of your questions have lots of answers if you do the search.