I am trying to sign a text using a certificate in my personal store. I am supposed to sign it with RSA2048 and then convert the output to the BASE64 string. The output I am getting is just 172 characters. Can you help understand is better where am I making mistake? As per my understanding, the output base64 length should be more.
RSAParameters privateKey = new RSAParameters();
foreach (X509Certificate2 cert in my.Certificates)
{
if (cert.Subject.Contains(certSubject))
{
using (var rsa = cert.GetRSAPrivateKey())
{
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] data = encoding.GetBytes(text);
return rsa.SignData(data, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
}
}
}
Related
I am using a smart card that is signing a SHA-1 hash of a document, and compute a 256 bytes digital signature.
I am using the code posted on this question - iText signing PDF using external signature with smart card.
My problem is that I get the error:" The document has been altered or corrupted since the signature was applied".
I am using a GUI to create the hash and then send the signed 256 bytes that is computed on the card to the signing functions .
Here is my code:
hash creating code of filepath pdf document:
SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
SHA256 sha2 = SHA256.Create();
//sha2.ComputeHash
byte[] pdfBytes = System.IO.File.ReadAllBytes(filePath);
byte[] hash = null;
hash= sha1.ComputeHash(pdfBytes);
the above code is used in one of the GUI functions to create the hash of the document
namespace EIDSmartCardSign
{
class PdfSignature
{
private string outputPdfPath;
private string certPath;
byte[] messageDigest;
private string inputPdfPath;
public PdfSignature(byte[] messageDigest, string inputPdfPath,string outputPdfPath)
{
this.messageDigest = messageDigest;
this.outputPdfPath = outputPdfPath;
this.inputPdfPath = inputPdfPath;
}
public void setCertPath(string certPath)
{
this.certPath = certPath;
}
public void signPdf()
{
X509Certificate2 cert = new X509Certificate2();
cert.Import(certPath); // .cer file certificate obtained from smart card
X509CertificateParser certParse = new Org.BouncyCastle.X509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[1] ;
chain[0] = certParse.ReadCertificate(cert.RawData);
X509Certificate2[] certs;
PdfReader reader = new PdfReader(inputPdfPath);
FileStream fout = new FileStream(outputPdfPath,FileMode.Create);
PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0',null,true);
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
appearance.SignatureCreator = "Me";
appearance.Reason = "Testing iText";
appearance.Location = "On my Laptop";
iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(50, 50, 250, 100);
appearance.SetVisibleSignature(rec, 1, "Signature");
IExternalSignature extSignature= new MyExternalSignature("SHA-1",this.messageDigest);
MakeSignature.SignDetached(appearance, extSignature, chain, null, null, null, 0, CryptoStandard.CMS);
//MakeSignature.
}
}
}
Your hash creating function
SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
SHA256 sha2 = SHA256.Create();
//sha2.ComputeHash
byte[] pdfBytes = System.IO.File.ReadAllBytes(filePath);
byte[] hash = null;
hash = sha1.ComputeHash(pdfBytes);
calculates the wrong hash value.
Have a look at this answer on Information Security Stack Exchange, in particular the sketch
shows that to get the document bytes to sign you do not take the original PDF but instead have to prepare it for integrating the signature container (add signature field, field value with some space reserved for the signature container, and field visualization) and then hash all the bytes except the space reserved for the signature container.
Furthermore, even this naked hash is not the data to sign. Instead a set of attributes is built, one of them containing the document hash calculated as above, other ones containing references to the signer certificate etc., and these attributes are to be signed.
Thus, instead do what you already claimed to be doing:
I am using the code posted on this question - iText signing PDF using external signature with smart card.
In particular the code there does not sign the hash of the whole file but instead uses the data the method Sign of the IExternalSignature implementation receives as parameter which is constructed as explained above.
More details
In a comment the OP said
The card I am working with expects a 20 bytes hash.
20 bytes would be typical for a naked hash generated by either SHA1 or RIPEMD-160. According to your question text, I assume the former algorithm is used. (This by the way indicates that the context does not require a high security level as SHA1 effectively is already phased out or in the process of being phased out for such use cases.)
What steps are needed to further create this hash After hashing the contents of the pdf?
Simply do as in the IExternalSignature implementation in the question you referenced:
public virtual byte[] Sign(byte[] message) {
byte[] hash = null;
using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
{
hash = sha1.ComputeHash(message);
}
byte[] sig = MySC.GetSignature(hash);
return sig;
}
(Obviously chances are that your smart card signing routine is not called MySC.GetSignature and you have to replace that call accordingly...)
As your card appears to expect a naked hash value in contrast to the card of the OP of the referenced question, this should work for you.
Where can I find examples of creating the aformentioned integrated signature container?
In the examples to the iText white paper Digital Signatures for PDF Documents.
After the signature process, I have 256 bytes signed data, 3 .cer certificates exported from the card.
256 bytes signed data sounds like a naked signature generated using RSA or RSASSA-PSS with a 2048 bit key size.
That been said, you need the signer certificate before signing: In most relevant profiles the signed attributes have to contain a reference to the signer certificate. In the code in the question you referenced that signer certificate is handled here
public void StartTest(){
X509Certificate2 cert = new X509Certificate2();
cert.Import("cert.cer"); // certificate obtained from smart card
X509CertificateParser certParse = new Org.BouncyCastle.X509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { certParse.ReadCertificate(cert.RawData) };
[...]
MyMakeSignature.SignDetached(appearance, externalSignature, chain, null, null, tsc, 0, CryptoStandard.CADES);
In particular you have to identify the correct signer certificate among those three certificate your card returns; otherwise you might have the same issue as the OP in the referenced question.
How do I create the Contents object when I have all of this data?
Considering what you said about your use case, chances are good that you really merely have to use the code posted of the question iText signing PDF using external signature with smart card with minor adaptions.
When i use C# to get certificate issuer, it returns correctly.
Here is my code:
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 mCert in store.Certificates)
{
Trace.WriteLine(mCert.SubjectName.Name);
}
Result: C=VN, L=HÀ NỘI, CN=TẬP ĐOÀN VIỄN THÔNG QUÂN ĐỘI (test)...
But in Java, i cannot get alias with Unicode character.
Here is my code :
KeyStore ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null);
Enumeration e = ks.aliases();
while (e.hasMoreElements()) {
String alias = (String) e.nextElement();
System.out.println(alias);
}
Result is T?P ÐOÀN VI?N THÔNG QUÂN Ð?I (test)
So, how can i get alias Unicode characters in Java like C# ? Thank you very much.
What I'm trying to do is use SHA1 UTF-8 encryption and then base64 encoding and on a password string value. However, I needed to do the encryption first, then the encoding, but I did it the other way around.
Here is the code:
# Create Input Data
$enc = [system.Text.Encoding]::UTF8
$string1 = "This is a string to hash"
$data1 = $enc.GetBytes($string1)
# Create a New SHA1 Crypto Provider
$sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider
$# Now hash and display results
$result1 = $sha.ComputeHash($data1)
So, when I went to do the hashing I realized I had to have a byte[] from the string and I'm not sure how to do that. I'm thinking there is a simple way from the .Net libraries, but couldn't find an example.
So if I have a string, like:
$string = "password"
How do I convert that into a byte array that I can use on :: ComputeHash($string)?
So what I have to end up with is an encrypted SHA-1 and base 64 encoded UTF-8 password, which the code above does, but it's coming back different than when I coded this same thing in java, where I encrypted it first, then converted that result to base 64 encoding.
I'm making the assumption that while encrypting a string directly isn't supported in the api, there may be a work-around that will allow you to do this. That is what I'm attempting to do.
So I'm assuming my issue with the code is that I had to encrypt it first and then encode it to get the correct value. Correct or am I missing something here?
Here is the pertinent java code that does work:
//First method call uses a swing component to get the user entered password.
String password = getPassword();
//This line is where the work starts with the second and third methods below.
String hashed = byteToBase64(getHash(password));
//The second method call here gets the encryption.
public static byte[] getHash(String password) {
MessageDigest digest = null;
byte[] input = null;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
digest.reset();
try {
input = digest.digest(password.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return input;
}
//Then the third method call here gets the encoding, FROM THE ENCRYPTED STRING.
public static String byteToBase64(byte[] data){
return new String(Base64.encodeBase64(data));
When I run the java code with the password string of "password" I get
[91, -86, 97, -28, -55, -71, 63, 63, 6, -126, 37, 11, 108, -8, 51, 27, 126, -26, -113, -40]
which is the encryption.
Then I when the encoding in java I get this:
W6ph5Mm5Pz8GgiULbPgzG37mj9g=
but when I run it in PowerShell I get this because it's encoded first for UTF8:
91 170 97 228 201 185 63 63 6 130 37 11 108 248 51 27 126 230 143 216
Then when I run this line of code to convert it I get an error:
$base64 = [System.Convert]::FromBase64String($result)
Exception calling "FromBase64String" with "1" argument(s): "Invalid length for a Base-64 char array."
At line:1 char:45
However, if I run the new line of code to make it hex from below I get:
$hexResult = [String]::Join("", ($result | % { "{0:X2}" -f $_}))
PS C:\Program Files (x86)\PowerGUI> Write-Host $hexResult
5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8
but I need to end up with this value:
W6ph5Mm5Pz8GgiULbPgzG37mj9g=
Again, this may not even be possible to do, but I'm trying to find a work-around to see.
You most likely just need to convert your hash to base64 after the last line.
$enc = [system.Text.Encoding]::UTF8
$string1 = "This is a string to hash"
$data1 = $enc.GetBytes($string1)
# Create a New SHA1 Crypto Provider
$sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider
# Now hash and display results
$result1 = $sha.ComputeHash($data1)
[System.Convert]::ToBase64String($result1)
Text->Bytes->Encrypt/Hash->Base64
That's a very common pattern for sending cryptographic data in a text format.
It looks like you're on the right track. You have to pick a character encoding to convert between a string and a byte array. You picked UTF-8 above, but there are other options (e.g. ASCII, UTF-16, etc.).
Encrypting a string directly is not supported.
The problem seems to be that in first bytearray, you are have signed bytes (-86 = 10101010) and in the second one unsigned bytes (170 = 10101010).
I am trying to do some symmetric encryption on some data with the Zend_Filter_Encrypt function. The problem is if i encrypt some data and then later decrypt it, there are nullbytes behind the decrypted data and I have no idea why.
For instance:
Plaintext: test Encrypted: ����pk� Decrypted: test����
It seems to be padding nullbytes at the end of the decrypted text to make it's length equal to some 2^n (a string with 11 characters is padded to fit 16 => 2^4). The most obvious thing would be to just strip these characters but I want to know why this is happening...
This is the code I'm using, which is different than how the documentation wants you to do it because their code just doesn't work for me (see: http://framework.zend.com/manual/en/zend.filter.set.html)
define('VECTOR','EXfPCW23'); //example, not the actual used VECTOR / KEY
$key = 'lolwatlolwat';
public function encryptPassword($password, $key)
{
$filter = new Zend_Filter_Encrypt();
$filter->setEncryption(array('key' => $key));
$filter->setVector(VECTOR);
return $filter->filter($password);
}
public function decryptPassword($password, $key)
{
$filter = new Zend_Filter_Decrypt();
$filter->setEncryption(array('key' => $key));
$filter->setVector(VECTOR);
return $filter->filter($password);
}
You have to use rtrim function on Decrypt string.
Example:
public function decryptPassword($password, $key)
{
$filter = new Zend_Filter_Decrypt();
$filter->setEncryption(array('key' => $key));
$filter->setVector(VECTOR);
return rtrim($filter->filter($password);
}
Does the Zend documentation tell you how to specify the padding? If so then specify a reversible padding; as you have found, zero padding is not reversible. Otherwise, find out what size padded plaintext Zend is expecting and add PKCS7 padding yourself. This is easily recognisable and removable afterwards.
I made a test suite for math:hmac_* KRL functions. I compare the KRL results with Python results. KRL gives me different results.
code: https://gist.github.com/980788 results: http://ktest.heroku.com/a421x68
How can I get valid signatures from KRL? I'm assuming that they Python results are correct.
UPDATE: It works fine unless you want newline characters in the message. How do I sign a string that includes newline characters?
I suspect that your python SHA library returns a different encoding than is expected by the b64encode library. My library does both the SHA and base64 in one call so I to do some extra work to check the results.
As you show in your KRL, the correct syntax is:
math:hmac_sha1_base64(raw_string,key);
math:hmac_sha256_base64(raw_string,key);
These use the same libraries that I use for the Amazon module which is testing fine right now.
To test those routines specifically, I used the test vectors from the RFC (sha1, sha256). We don't support Hexadecimal natively, so I wasn't able to use all of the test vectors, but I was able to use a simple one:
HMAC SHA1
test_case = 2
key = "Jefe"
key_len = 4
data = "what do ya want for nothing?"
data_len = 28
digest = 0xeffcdf6ae5eb2fa2d27416d5f184df9c259a7c79
HMAC SHA256
Key = 4a656665 ("Jefe")
Data = 7768617420646f2079612077616e7420666f72206e6f7468696e673f ("what do ya want for nothing?")
HMAC-SHA-256 = 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
Here is my code:
global {
raw_string = "what do ya want for nothing?";
mkey = "Jefe";
}
rule first_rule {
select when pageview ".*" setting ()
pre {
hmac_sha1 = math:hmac_sha1_hex(raw_string,mkey);
hmac_sha1_64 = math:hmac_sha1_base64(raw_string,mkey);
bhs256c = math:hmac_sha256_hex(raw_string,mkey);
bhs256c64 = math:hmac_sha256_base64(raw_string,mkey);
}
{
notify("HMAC sha1", "#{hmac_sha1}") with sticky = true;
notify("hmac sha1 base 64", "#{hmac_sha1_64}") with sticky = true;
notify("hmac sha256", "#{bhs256c}") with sticky = true;
notify("hmac sha256 base 64", "#{bhs256c64}") with sticky = true;
}
}
var hmac_sha1 = 'effcdf6ae5eb2fa2d27416d5f184df9c259a7c79';
var hmac_sha1_64 = '7/zfauXrL6LSdBbV8YTfnCWafHk';
var bhs256c = '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843';
var bhs256c64 = 'W9zBRr9gdU5qBCQmCJV1x1oAPwidJzmDnexYuWTsOEM';
The HEX results for SHA1 and SHA256 match the test vectors of the simple case.
I tested the base64 results by decoding the HEX results and putting them through the base64 encoder here
My results were:
7/zfauXrL6LSdBbV8YTfnCWafHk=
W9zBRr9gdU5qBCQmCJV1x1oAPwidJzmDnexYuWTsOEM=
Which match my calculations for HMAC SHA1 base64 and HMAC SHA256 base64 respectively.
If you are still having problems, could you provide me the base64 and SHA results from python separately so I can identify the disconnect?