简体   繁体   中英

Digital Signature Verification using BouncyCastle - ECDSA with SHA 256, C#

Following is my scenario - I read data from a barcode and its converted into a plain text. This text is a combination of barcode data + digital signature. Digital signature is appended to the end, which enables me to separate out the actual data and digital signature data. Digital signature data is hashed using sha256 -User send me a public key as windows certificate file ( .cer extension ).

Required implementation : -Need to extract public key from the certificate and validate the public key against the barcode data and the digital signature provided.

Here is the code I am trying to use to verify signature

//Note : 
//1.  certPath : is the path where my certificate is located 
//2. GetStreamdata  get the stream of data from the certificate. 

//Get the certificate data here 
                Org.BouncyCastle.X509.X509Certificate cert1 = new X509CertificateParser().ReadCertificate(GetStreamData(cerPath)); 
//get the public key 
                ECPublicKeyParameters ecPublic = (ECPublicKeyParameters)cert1.GetPublicKey(); 
//create a signerutility with type SHA-256withECDSA 
                ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA"); 
//initial signer with the public key 
                signer.Init(false, ecPublic); 
//get signature in bytes : digitalsignature parameter contains signature that should be used. 
                byte[] dBytes = encoding.GetBytes(digitalsignature); 
//block/finalise update to signer : data : is the actual data. 
                signer.BlockUpdate(data, 0, data.Length); 
                    try 
                    { 
//verify signature 
                         verified =  signer.VerifySignature(dBytes); 
                    } 
                catch(Exception ex) 
                    { 
                        _log.LogException(ex); 
                    } 

what was I able to achieve was : extract public using bouncy castle libraries

Problem :

Exception thrown on signer.verifysignature
  Message=Unable to cast object of type 'Org.BouncyCastle.Asn1.DerApplicationSpecific' to type 'Org.BouncyCastle.Asn1.Asn1Sequence'. 
  Source=BouncyCastle.Crypto 

The problem was that I had to encode digitalsignature value in iso-8859-1. I was encoding in ASCII before. This solves the problem and I was able to validate signature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM