public static byte[] Digest(string algo, byte[] b) { return(Digest(DigestUtilities.GetDigest(algo), b, 0, b.Length)); }
internal SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random) { AlgorithmIdentifier digAlgId = DigestAlgorithmID; string digestName = Helper.GetDigestAlgName(digestOID); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); byte[] hash; if (outer._digests.Contains(digestOID)) { hash = (byte[])outer._digests[digestOID]; } else { IDigest dig = Helper.GetDigestInstance(digestName); if (content != null) { content.Write(new DigOutputStream(dig)); } hash = DigestUtilities.DoFinal(dig); outer._digests.Add(digestOID, hash.Clone()); } IStreamCalculator calculator = sigCalc.CreateCalculator(); #if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT Stream sigStr = new SigOutputStream(calculator.Stream); #else Stream sigStr = new BufferedStream(calculator.Stream); #endif Asn1Set signedAttr = null; if (sAttr != null) { IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); // Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters); if (contentType == null) //counter signature { if (signed != null && signed[CmsAttributes.ContentType] != null) { IDictionary tmpSigned = signed.ToDictionary(); tmpSigned.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(tmpSigned); } } // TODO Validate proposed signed attributes signedAttr = outer.GetAttributeSet(signed); // sig must be composed from the DER encoding. new DerOutputStream(sigStr).WriteObject(signedAttr); } else if (content != null) { // TODO Use raw signature of the hash value instead content.Write(sigStr); } sigStr.Close(); byte[] sigBytes = ((IBlockResult)calculator.GetResult()).DoFinal(); Asn1Set unsignedAttr = null; if (unsAttr != null) { IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)); Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters); // TODO Validate proposed unsigned attributes unsignedAttr = outer.GetAttributeSet(unsigned); } // TODO[RSAPSS] Need the ability to specify non-default parameters Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName); AlgorithmIdentifier encAlgId = Helper.GetEncAlgorithmIdentifier( new DerObjectIdentifier(encOID), sigX509Parameters); return(new SignerInfo(signerIdentifier, digAlgId, signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr)); }
public static ICipherParameters GenerateCipherParameters(string algorithm, char[] password, bool wrongPkcs12Zero, Asn1Encodable pbeParameters) { string text = (string)algorithms[Platform.ToUpperInvariant(algorithm)]; byte[] array = null; byte[] salt = null; int iterationCount = 0; if (IsPkcs12(text)) { Pkcs12PbeParams instance = Pkcs12PbeParams.GetInstance(pbeParameters); salt = instance.GetIV(); iterationCount = instance.Iterations.IntValue; array = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero); } else if (!IsPkcs5Scheme2(text)) { PbeParameter instance2 = PbeParameter.GetInstance(pbeParameters); salt = instance2.GetSalt(); iterationCount = instance2.IterationCount.IntValue; array = PbeParametersGenerator.Pkcs5PasswordToBytes(password); } ICipherParameters parameters = null; if (IsPkcs5Scheme2(text)) { PbeS2Parameters instance3 = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object()); AlgorithmIdentifier encryptionScheme = instance3.EncryptionScheme; DerObjectIdentifier algorithm2 = encryptionScheme.Algorithm; Asn1Object obj = encryptionScheme.Parameters.ToAsn1Object(); Pbkdf2Params instance4 = Pbkdf2Params.GetInstance(instance3.KeyDerivationFunc.Parameters.ToAsn1Object()); byte[] array2; if (algorithm2.Equals(PkcsObjectIdentifiers.RC2Cbc)) { RC2CbcParameter instance5 = RC2CbcParameter.GetInstance(obj); array2 = instance5.GetIV(); } else { array2 = Asn1OctetString.GetInstance(obj).GetOctets(); } salt = instance4.GetSalt(); iterationCount = instance4.IterationCount.IntValue; array = PbeParametersGenerator.Pkcs5PasswordToBytes(password); int keySize = (instance4.KeyLength != null) ? (instance4.KeyLength.IntValue * 8) : GeneratorUtilities.GetDefaultKeySize(algorithm2); PbeParametersGenerator pbeParametersGenerator = MakePbeGenerator((string)algorithmType[text], null, array, salt, iterationCount); parameters = pbeParametersGenerator.GenerateDerivedParameters(algorithm2.Id, keySize); if (array2 != null && !Arrays.AreEqual(array2, new byte[array2.Length])) { parameters = new ParametersWithIV(parameters, array2); } } else if (Platform.StartsWith(text, "PBEwithSHA-1")) { PbeParametersGenerator pbeParametersGenerator2 = MakePbeGenerator((string)algorithmType[text], new Sha1Digest(), array, salt, iterationCount); if (text.Equals("PBEwithSHA-1and128bitAES-CBC-BC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 128, 128); } else if (text.Equals("PBEwithSHA-1and192bitAES-CBC-BC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 192, 128); } else if (text.Equals("PBEwithSHA-1and256bitAES-CBC-BC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 256, 128); } else if (text.Equals("PBEwithSHA-1and128bitRC4")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC4", 128); } else if (text.Equals("PBEwithSHA-1and40bitRC4")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC4", 40); } else if (text.Equals("PBEwithSHA-1and3-keyDESEDE-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("DESEDE", 192, 64); } else if (text.Equals("PBEwithSHA-1and2-keyDESEDE-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("DESEDE", 128, 64); } else if (text.Equals("PBEwithSHA-1and128bitRC2-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 128, 64); } else if (text.Equals("PBEwithSHA-1and40bitRC2-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 40, 64); } else if (text.Equals("PBEwithSHA-1andDES-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("DES", 64, 64); } else if (text.Equals("PBEwithSHA-1andRC2-CBC")) { parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 64, 64); } } else if (Platform.StartsWith(text, "PBEwithSHA-256")) { PbeParametersGenerator pbeParametersGenerator3 = MakePbeGenerator((string)algorithmType[text], new Sha256Digest(), array, salt, iterationCount); if (text.Equals("PBEwithSHA-256and128bitAES-CBC-BC")) { parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 128, 128); } else if (text.Equals("PBEwithSHA-256and192bitAES-CBC-BC")) { parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 192, 128); } else if (text.Equals("PBEwithSHA-256and256bitAES-CBC-BC")) { parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 256, 128); } } else if (Platform.StartsWith(text, "PBEwithMD5")) { PbeParametersGenerator pbeParametersGenerator4 = MakePbeGenerator((string)algorithmType[text], new MD5Digest(), array, salt, iterationCount); if (text.Equals("PBEwithMD5andDES-CBC")) { parameters = pbeParametersGenerator4.GenerateDerivedParameters("DES", 64, 64); } else if (text.Equals("PBEwithMD5andRC2-CBC")) { parameters = pbeParametersGenerator4.GenerateDerivedParameters("RC2", 64, 64); } else if (text.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL")) { parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 128, 128); } else if (text.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL")) { parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 192, 128); } else if (text.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL")) { parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 256, 128); } } else if (Platform.StartsWith(text, "PBEwithMD2")) { PbeParametersGenerator pbeParametersGenerator5 = MakePbeGenerator((string)algorithmType[text], new MD2Digest(), array, salt, iterationCount); if (text.Equals("PBEwithMD2andDES-CBC")) { parameters = pbeParametersGenerator5.GenerateDerivedParameters("DES", 64, 64); } else if (text.Equals("PBEwithMD2andRC2-CBC")) { parameters = pbeParametersGenerator5.GenerateDerivedParameters("RC2", 64, 64); } } else if (Platform.StartsWith(text, "PBEwithHmac")) { string algorithm3 = text.Substring("PBEwithHmac".Length); IDigest digest = DigestUtilities.GetDigest(algorithm3); PbeParametersGenerator pbeParametersGenerator6 = MakePbeGenerator((string)algorithmType[text], digest, array, salt, iterationCount); int keySize2 = digest.GetDigestSize() * 8; parameters = pbeParametersGenerator6.GenerateDerivedMacParameters(keySize2); } Array.Clear(array, 0, array.Length); return(FixDesParity(text, parameters)); }
public byte[] GetDigest() { IDigest digest = CmsSignedHelper.Instance.GetDigestInstance(alg); return(DigestUtilities.DoFinal(digest, data)); }
public void TestSha1WithRsa() { IList certList = new ArrayList(); IList crlList = new ArrayList(); MemoryStream bOut = new MemoryStream(); certList.Add(OrigCert); certList.Add(SignCert); crlList.Add(SignCrl); crlList.Add(OrigCrl); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); IX509Store x509Crls = X509StoreFactory.Create( "CRL/Collection", new X509CollectionStoreParameters(crlList)); CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1); gen.AddCertificates(x509Certs); gen.AddCrls(x509Crls); Stream sigOut = gen.Open(bOut); byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage); sigOut.Write(testBytes, 0, testBytes.Length); sigOut.Close(); CheckSigParseable(bOut.ToArray()); CmsSignedDataParser sp = new CmsSignedDataParser( new CmsTypedStream(new MemoryStream(testBytes, false)), bOut.ToArray()); sp.GetSignedContent().Drain(); // // compute expected content digest // IDigest md = DigestUtilities.GetDigest("SHA1"); md.BlockUpdate(testBytes, 0, testBytes.Length); byte[] hash = DigestUtilities.DoFinal(md); VerifySignatures(sp, hash); // // try using existing signer // gen = new CmsSignedDataStreamGenerator(); gen.AddSigners(sp.GetSignerInfos()); gen.AddCertificates(sp.GetCertificates("Collection")); gen.AddCrls(sp.GetCrls("Collection")); bOut.SetLength(0); sigOut = gen.Open(bOut, true); sigOut.Write(testBytes, 0, testBytes.Length); sigOut.Close(); VerifyEncodedData(bOut); // // look for the CRLs // ArrayList col = new ArrayList(x509Crls.GetMatches(null)); Assert.AreEqual(2, col.Count); Assert.IsTrue(col.Contains(SignCrl)); Assert.IsTrue(col.Contains(OrigCrl)); }
// gets keylength and revision and uses revison to choose the initial values for permissions virtual public void SetupAllKeys(byte[] userPassword, byte[] ownerPassword, int permissions) { if (ownerPassword == null || ownerPassword.Length == 0) { ownerPassword = DigestAlgorithms.Digest("MD5", CreateDocumentId()); } md5.Reset(); permissions |= (int) ((revision == STANDARD_ENCRYPTION_128 || revision == AES_128 || revision == AES_256) ? (uint)0xfffff0c0 : (uint)0xffffffc0); permissions &= unchecked ((int)0xfffffffc); this.permissions = permissions; if (revision == AES_256) { if (userPassword == null) { userPassword = new byte[0]; } documentID = CreateDocumentId(); byte[] uvs = IVGenerator.GetIV(8); byte[] uks = IVGenerator.GetIV(8); key = IVGenerator.GetIV(32); // Algorithm 3.8.1 IDigest md = DigestUtilities.GetDigest("SHA-256"); md.BlockUpdate(userPassword, 0, Math.Min(userPassword.Length, 127)); md.BlockUpdate(uvs, 0, uvs.Length); userKey = new byte[48]; md.DoFinal(userKey, 0); System.Array.Copy(uvs, 0, userKey, 32, 8); System.Array.Copy(uks, 0, userKey, 40, 8); // Algorithm 3.8.2 md.BlockUpdate(userPassword, 0, Math.Min(userPassword.Length, 127)); md.BlockUpdate(uks, 0, uks.Length); byte[] tempDigest = new byte[32]; md.DoFinal(tempDigest, 0); AESCipherCBCnoPad ac = new AESCipherCBCnoPad(true, tempDigest); ueKey = ac.ProcessBlock(key, 0, key.Length); // Algorithm 3.9.1 byte[] ovs = IVGenerator.GetIV(8); byte[] oks = IVGenerator.GetIV(8); md.BlockUpdate(ownerPassword, 0, Math.Min(ownerPassword.Length, 127)); md.BlockUpdate(ovs, 0, ovs.Length); md.BlockUpdate(userKey, 0, userKey.Length); ownerKey = new byte[48]; md.DoFinal(ownerKey, 0); System.Array.Copy(ovs, 0, ownerKey, 32, 8); System.Array.Copy(oks, 0, ownerKey, 40, 8); // Algorithm 3.9.2 md.BlockUpdate(ownerPassword, 0, Math.Min(ownerPassword.Length, 127)); md.BlockUpdate(oks, 0, oks.Length); md.BlockUpdate(userKey, 0, userKey.Length); md.DoFinal(tempDigest, 0); ac = new AESCipherCBCnoPad(true, tempDigest); oeKey = ac.ProcessBlock(key, 0, key.Length); // Algorithm 3.10 byte[] permsp = IVGenerator.GetIV(16); permsp[0] = (byte)permissions; permsp[1] = (byte)(permissions >> 8); permsp[2] = (byte)(permissions >> 16); permsp[3] = (byte)(permissions >> 24); permsp[4] = (byte)(255); permsp[5] = (byte)(255); permsp[6] = (byte)(255); permsp[7] = (byte)(255); permsp[8] = encryptMetadata ? (byte)'T' : (byte)'F'; permsp[9] = (byte)'a'; permsp[10] = (byte)'d'; permsp[11] = (byte)'b'; ac = new AESCipherCBCnoPad(true, key); perms = ac.ProcessBlock(permsp, 0, permsp.Length); } else { //PDF refrence 3.5.2 Standard Security Handler, Algorithum 3.3-1 //If there is no owner password, use the user password instead. byte[] userPad = PadPassword(userPassword); byte[] ownerPad = PadPassword(ownerPassword); this.ownerKey = ComputeOwnerKey(userPad, ownerPad); documentID = CreateDocumentId(); SetupByUserPad(this.documentID, userPad, this.ownerKey, permissions); } }
virtual public PdfDictionary GetEncryptionDictionary() { PdfDictionary dic = new PdfDictionary(); if (publicKeyHandler.GetRecipientsSize() > 0) { PdfArray recipients = null; dic.Put(PdfName.FILTER, PdfName.PUBSEC); dic.Put(PdfName.R, new PdfNumber(revision)); recipients = publicKeyHandler.GetEncodedRecipients(); if (revision == STANDARD_ENCRYPTION_40) { dic.Put(PdfName.V, new PdfNumber(1)); dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4); dic.Put(PdfName.RECIPIENTS, recipients); } else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata) { dic.Put(PdfName.V, new PdfNumber(2)); dic.Put(PdfName.LENGTH, new PdfNumber(128)); dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S4); dic.Put(PdfName.RECIPIENTS, recipients); } else { if (revision == AES_256) { dic.Put(PdfName.R, new PdfNumber(AES_256)); dic.Put(PdfName.V, new PdfNumber(5)); } else { dic.Put(PdfName.R, new PdfNumber(AES_128)); dic.Put(PdfName.V, new PdfNumber(4)); } dic.Put(PdfName.SUBFILTER, PdfName.ADBE_PKCS7_S5); PdfDictionary stdcf = new PdfDictionary(); stdcf.Put(PdfName.RECIPIENTS, recipients); if (!encryptMetadata) { stdcf.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); } if (revision == AES_128) { stdcf.Put(PdfName.CFM, PdfName.AESV2); stdcf.Put(PdfName.LENGTH, new PdfNumber(128)); } else if (revision == AES_256) { stdcf.Put(PdfName.CFM, PdfName.AESV3); stdcf.Put(PdfName.LENGTH, new PdfNumber(256)); } else { stdcf.Put(PdfName.CFM, PdfName.V2); } PdfDictionary cf = new PdfDictionary(); cf.Put(PdfName.DEFAULTCRYPTFILTER, stdcf); dic.Put(PdfName.CF, cf); if (embeddedFilesOnly) { dic.Put(PdfName.EFF, PdfName.DEFAULTCRYPTFILTER); dic.Put(PdfName.STRF, PdfName.IDENTITY); dic.Put(PdfName.STMF, PdfName.IDENTITY); } else { dic.Put(PdfName.STRF, PdfName.DEFAULTCRYPTFILTER); dic.Put(PdfName.STMF, PdfName.DEFAULTCRYPTFILTER); } } IDigest sh; if (revision == AES_256) { sh = DigestUtilities.GetDigest("SHA-256"); } else { sh = DigestUtilities.GetDigest("SHA-1"); } byte[] encodedRecipient = null; byte[] seed = publicKeyHandler.GetSeed(); sh.BlockUpdate(seed, 0, seed.Length); for (int i = 0; i < publicKeyHandler.GetRecipientsSize(); i++) { encodedRecipient = publicKeyHandler.GetEncodedRecipient(i); sh.BlockUpdate(encodedRecipient, 0, encodedRecipient.Length); } if (!encryptMetadata) { sh.BlockUpdate(metadataPad, 0, metadataPad.Length); } byte[] mdResult = new byte[sh.GetDigestSize()]; sh.DoFinal(mdResult, 0); if (revision == AES_256) { key = mdResult; } else { SetupByEncryptionKey(mdResult, keyLength); } } else { dic.Put(PdfName.FILTER, PdfName.STANDARD); dic.Put(PdfName.O, new PdfLiteral(StringUtils.EscapeString(ownerKey))); dic.Put(PdfName.U, new PdfLiteral(StringUtils.EscapeString(userKey))); dic.Put(PdfName.P, new PdfNumber(permissions)); dic.Put(PdfName.R, new PdfNumber(revision)); if (revision == STANDARD_ENCRYPTION_40) { dic.Put(PdfName.V, new PdfNumber(1)); } else if (revision == STANDARD_ENCRYPTION_128 && encryptMetadata) { dic.Put(PdfName.V, new PdfNumber(2)); dic.Put(PdfName.LENGTH, new PdfNumber(128)); } else if (revision == AES_256) { if (!encryptMetadata) { dic.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); } dic.Put(PdfName.OE, new PdfLiteral(StringUtils.EscapeString(oeKey))); dic.Put(PdfName.UE, new PdfLiteral(StringUtils.EscapeString(ueKey))); dic.Put(PdfName.PERMS, new PdfLiteral(StringUtils.EscapeString(perms))); dic.Put(PdfName.V, new PdfNumber(revision)); dic.Put(PdfName.LENGTH, new PdfNumber(256)); PdfDictionary stdcf = new PdfDictionary(); stdcf.Put(PdfName.LENGTH, new PdfNumber(32)); if (embeddedFilesOnly) { stdcf.Put(PdfName.AUTHEVENT, PdfName.EFOPEN); dic.Put(PdfName.EFF, PdfName.STDCF); dic.Put(PdfName.STRF, PdfName.IDENTITY); dic.Put(PdfName.STMF, PdfName.IDENTITY); } else { stdcf.Put(PdfName.AUTHEVENT, PdfName.DOCOPEN); dic.Put(PdfName.STRF, PdfName.STDCF); dic.Put(PdfName.STMF, PdfName.STDCF); } stdcf.Put(PdfName.CFM, PdfName.AESV3); PdfDictionary cf = new PdfDictionary(); cf.Put(PdfName.STDCF, stdcf); dic.Put(PdfName.CF, cf); } else { if (!encryptMetadata) { dic.Put(PdfName.ENCRYPTMETADATA, PdfBoolean.PDFFALSE); } dic.Put(PdfName.R, new PdfNumber(AES_128)); dic.Put(PdfName.V, new PdfNumber(4)); dic.Put(PdfName.LENGTH, new PdfNumber(128)); PdfDictionary stdcf = new PdfDictionary(); stdcf.Put(PdfName.LENGTH, new PdfNumber(16)); if (embeddedFilesOnly) { stdcf.Put(PdfName.AUTHEVENT, PdfName.EFOPEN); dic.Put(PdfName.EFF, PdfName.STDCF); dic.Put(PdfName.STRF, PdfName.IDENTITY); dic.Put(PdfName.STMF, PdfName.IDENTITY); } else { stdcf.Put(PdfName.AUTHEVENT, PdfName.DOCOPEN); dic.Put(PdfName.STRF, PdfName.STDCF); dic.Put(PdfName.STMF, PdfName.STDCF); } if (revision == AES_128) { stdcf.Put(PdfName.CFM, PdfName.AESV2); } else { stdcf.Put(PdfName.CFM, PdfName.V2); } PdfDictionary cf = new PdfDictionary(); cf.Put(PdfName.STDCF, stdcf); dic.Put(PdfName.CF, cf); } } return(dic); }
/// <summary> /// Computes the hash of the specified buffer. /// </summary> /// <param name="data">The data to hash.</param> /// <returns> /// The computed hash. /// </returns> public override byte[] Hash(byte[] data) { return(DigestUtilities.CalculateDigest(this.HashAlgorithmName, data)); }
/** * create with a signer with extra signed/unsigned attributes. */ public TimeStampTokenGenerator( AsymmetricKeyParameter key, X509Certificate cert, string digestOID, string tsaPolicyOID, Asn1.Cms.AttributeTable signedAttr, Asn1.Cms.AttributeTable unsignedAttr) { this.key = key; this.cert = cert; this.digestOID = digestOID; this.tsaPolicyOID = tsaPolicyOID; this.unsignedAttr = unsignedAttr; TspUtil.ValidateCertificate(cert); // // add the essCertid // Hashtable signedAttrs = null; if (signedAttr != null) { signedAttrs = signedAttr.ToHashtable(); } else { signedAttrs = new Hashtable(); } IDigest digest; try { digest = DigestUtilities.GetDigest("SHA-1"); } catch (Exception e) { throw new TspException("Can't find a SHA-1 implementation.", e); } try { byte[] certEncoded = cert.GetEncoded(); digest.BlockUpdate(certEncoded, 0, certEncoded.Length); byte[] hash = DigestUtilities.DoFinal(digest); EssCertID essCertid = new EssCertID(hash); Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute( PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(new SigningCertificate(essCertid))); signedAttrs[attr.AttrType] = attr; } catch (CertificateEncodingException e) { throw new TspException("Exception processing certificate.", e); } this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs); }
internal SignerInfo ToSignerInfo( DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random, bool isCounterSignature) { AlgorithmIdentifier digAlgId = DigestAlgorithmID; string digestName = Helper.GetDigestAlgName(digestOID); IDigest dig = Helper.GetDigestInstance(digestName); string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); ISigner sig = Helper.GetSignatureInstance(signatureName); // TODO Optimise the case where more than one signer with same digest if (content != null) { content.Write(new DigOutputStream(dig)); } byte[] hash = DigestUtilities.DoFinal(dig); outer._digests.Add(digestOID, hash.Clone()); sig.Init(true, new ParametersWithRandom(key, random)); Stream sigStr = new BufferedStream(new SigOutputStream(sig)); Asn1Set signedAttr = null; if (sAttr != null) { IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash); // Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters); if (isCounterSignature) { Hashtable tmpSigned = signed.ToHashtable(); tmpSigned.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(tmpSigned); } // TODO Validate proposed signed attributes signedAttr = outer.GetAttributeSet(signed); // sig must be composed from the DER encoding. new DerOutputStream(sigStr).WriteObject(signedAttr); } else if (content != null) { // TODO Use raw signature of the hash value instead content.Write(sigStr); } sigStr.Close(); byte[] sigBytes = sig.GenerateSignature(); Asn1Set unsignedAttr = null; if (unsAttr != null) { IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)); Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters); // TODO Validate proposed unsigned attributes unsignedAttr = outer.GetAttributeSet(unsigned); } // TODO[RSAPSS] Need the ability to specify non-default parameters Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName); AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier( new DerObjectIdentifier(encOID), sigX509Parameters); return(new SignerInfo(signerIdentifier, digAlgId, signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr)); }
/** * Validate the time stamp token. * <p> * To be valid the token must be signed by the passed in certificate and * the certificate must be the one referred to by the SigningCertificate * attribute included in the hashed attributes of the token. The * certificate must also have the ExtendedKeyUsageExtension with only * KeyPurposeID.IdKPTimeStamping and have been valid at the time the * timestamp was created. * </p> * <p> * A successful call to validate means all the above are true. * </p> */ public void Validate( X509Certificate cert) { try { byte[] hash = DigestUtilities.CalculateDigest( certID.GetHashAlgorithmName(), cert.GetEncoded()); if (!Arrays.ConstantTimeAreEqual(certID.GetCertHash(), hash)) { throw new TspValidationException("certificate hash does not match certID hash."); } if (certID.IssuerSerial != null) { if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber)) { throw new TspValidationException("certificate serial number does not match certID for signature."); } GeneralName[] names = certID.IssuerSerial.Issuer.GetNames(); X509Name principal = PrincipalUtilities.GetIssuerX509Principal(cert); bool found = false; for (int i = 0; i != names.Length; i++) { if (names[i].TagNo == 4 && X509Name.GetInstance(names[i].Name).Equivalent(principal)) { found = true; break; } } if (!found) { throw new TspValidationException("certificate name does not match certID for signature. "); } } TspUtil.ValidateCertificate(cert); cert.CheckValidity(tstInfo.GenTime); if (!tsaSignerInfo.Verify(cert)) { throw new TspValidationException("signature not created by certificate."); } } catch (CmsException e) { if (e.InnerException != null) { throw new TspException(e.Message, e.InnerException); } throw new TspException("CMS exception: " + e, e); } catch (CertificateEncodingException e) { throw new TspException("problem processing certificate: " + e, e); } catch (SecurityUtilityException e) { throw new TspException("cannot find algorithm: " + e.Message, e); } }
internal IDigest GetHashClass() { return(DigestUtilities.GetDigest(GetHashAlgorithm())); }
public void MD5Digest_CalculatesDigest() { var buffer = Encoding.ASCII.GetBytes("Hello world!"); Assert.AreEqual("86fb269d190d2c85f6e0468ceca42a20", Hex.ToHexString(DigestUtilities.CalculateDigest("MD5", buffer))); }
public static object CreateFromName(string name) { switch (name) { case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315": return(new XmlDsigC14NTransform()); case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments": return(new XmlDsigC14NWithCommentsTransform()); case "http://www.w3.org/2001/10/xml-exc-c14n#": return(new XmlDsigExcC14NTransform()); case "http://www.w3.org/2001/10/xml-exc-c14n#WithComments": return(new XmlDsigExcC14NWithCommentsTransform()); case "http://www.w3.org/2000/09/xmldsig#base64": return(new XmlDsigBase64Transform()); case "http://www.w3.org/TR/1999/REC-xpath-19991116": return(new XmlDsigXPathTransform()); case "http://www.w3.org/TR/1999/REC-xslt-19991116": return(new XmlDsigXsltTransform()); case "http://www.w3.org/2000/09/xmldsig#enveloped-signature": return(new XmlDsigEnvelopedSignatureTransform()); //case "http://www.w3.org/2002/07/decrypt#XML": // return new XmlDecryptionTransform(); //case "urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform": // return new XmlLicenseTransform(); case "http://www.w3.org/2000/09/xmldsig# X509Data": return(new KeyInfoX509Data()); case "http://www.w3.org/2000/09/xmldsig# KeyName": return(new KeyInfoName()); case "http://www.w3.org/2000/09/xmldsig# KeyValue/DSAKeyValue": return(new DSAKeyValue()); case "http://www.w3.org/2000/09/xmldsig# KeyValue/RSAKeyValue": return(new RSAKeyValue()); case "http://www.w3.org/2000/09/xmldsig# RetrievalMethod": return(new KeyInfoRetrievalMethod()); //case "http://www.w3.org/2001/04/xmlenc# EncryptedKey": // return new KeyInfoEncryptedKey(); case "http://www.w3.org/2000/09/xmldsig#dsa-sha1": case "System.Security.Cryptography.DSASignatureDescription": return(SignerUtilities.GetSigner("DSAWITHSHA1")); case "http://www.w3.org/2000/09/xmldsig#rsa-sha1": case "System.Security.Cryptography.RSASignatureDescription": return(SignerUtilities.GetSigner("SHA1WITHRSA")); case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256": return(SignerUtilities.GetSigner("SHA256WITHRSA")); case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384": return(SignerUtilities.GetSigner("SHA384WITHRSA")); case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512": return(SignerUtilities.GetSigner("SHA512WITHRSA")); case "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411": case "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411": return(SignerUtilities.GetSigner("GOST3411WITHECGOST3410")); case "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102012-gostr34112012256": return(new Gost3410DigestSigner(new ECGost3410Signer(), new GOST3411_2012_256Digest())); case "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102012-gostr34112012512": return(new Gost3410DigestSigner(new ECGost3410Signer(), new GOST3411_2012_512Digest())); // workarounds for issue https://github.com/dotnet/corefx/issues/16563 // remove attribute from this method when removing them case "http://www.w3.org/2000/09/xmldsig#sha1": return(DigestUtilities.GetDigest("SHA-1")); case "MD5": return(DigestUtilities.GetDigest("MD5")); case "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411": case "http://www.w3.org/2001/04/xmldsig-more#gostr3411": return(DigestUtilities.GetDigest("GOST3411")); case "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34112012-256": return(DigestUtilities.GetDigest("GOST3411-2012-256")); case "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34112012-512": return(DigestUtilities.GetDigest("GOST3411-2012-512")); case "http://www.w3.org/2001/04/xmldsig-more#hmac-md5": return(MacUtilities.GetMac("HMAC-MD5")); case "http://www.w3.org/2001/04/xmlenc#tripledes-cbc": return(CipherUtilities.GetCipher("DESede/CBC/PKCS7Padding")); } throw new NotSupportedException(name); }
public bool Match( // Certificate cert) X509Certificate x509Cert) { // if (!(cert is X509Certificate)) // { // return false; // } // // X509Certificate x509Cert = (X509Certificate)cert; try { if (holder.BaseCertificateID != null) { return(holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber) && MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer)); } if (holder.EntityName != null) { if (MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName)) { return(true); } } if (holder.ObjectDigestInfo != null) { IDigest md = null; try { md = DigestUtilities.GetDigest(DigestAlgorithm); } catch (Exception) { return(false); } switch (DigestedObjectType) { case ObjectDigestInfo.PublicKey: { // TODO: DSA Dss-parms //byte[] b = x509Cert.GetPublicKey().getEncoded(); // TODO Is this the right way to encode? byte[] b = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo( x509Cert.GetPublicKey()).GetEncoded(); md.BlockUpdate(b, 0, b.Length); break; } case ObjectDigestInfo.PublicKeyCert: { byte[] b = x509Cert.GetEncoded(); md.BlockUpdate(b, 0, b.Length); break; } // TODO Default handler? } // TODO Shouldn't this be the other way around? if (!Arrays.AreEqual(DigestUtilities.DoFinal(md), GetObjectDigest())) { return(false); } } } catch (CertificateEncodingException) { return(false); } return(false); }
/// <summary>Return a signature object containing the current signature state.</summary> public PgpSignature Generate() { SignatureSubpacket[] hPkts = hashed, unhPkts = unhashed; if (!packetPresent(hashed, SignatureSubpacketTag.CreationTime)) { hPkts = insertSubpacket(hPkts, new SignatureCreationTime(false, DateTime.UtcNow)); } if (!packetPresent(hashed, SignatureSubpacketTag.IssuerKeyId) && !packetPresent(unhashed, SignatureSubpacketTag.IssuerKeyId)) { unhPkts = insertSubpacket(unhPkts, new IssuerKeyId(false, privKey.KeyId)); } int version = 4; byte[] hData; try { MemoryStream hOut = new MemoryStream(); for (int i = 0; i != hPkts.Length; i++) { hPkts[i].Encode(hOut); } byte[] data = hOut.ToArray(); MemoryStream sOut = new MemoryStream(data.Length + 6); sOut.WriteByte((byte)version); sOut.WriteByte((byte)signatureType); sOut.WriteByte((byte)keyAlgorithm); sOut.WriteByte((byte)hashAlgorithm); sOut.WriteByte((byte)(data.Length >> 8)); sOut.WriteByte((byte)data.Length); sOut.Write(data, 0, data.Length); hData = sOut.ToArray(); } catch (IOException e) { throw new PgpException("exception encoding hashed data.", e); } sig.BlockUpdate(hData, 0, hData.Length); dig.BlockUpdate(hData, 0, hData.Length); hData = new byte[] { (byte)version, 0xff, (byte)(hData.Length >> 24), (byte)(hData.Length >> 16), (byte)(hData.Length >> 8), (byte)hData.Length }; sig.BlockUpdate(hData, 0, hData.Length); dig.BlockUpdate(hData, 0, hData.Length); byte[] sigBytes = sig.GenerateSignature(); byte[] digest = DigestUtilities.DoFinal(dig); byte[] fingerPrint = new byte[] { digest[0], digest[1] }; // an RSA signature bool isRsa = keyAlgorithm == PublicKeyAlgorithmTag.RsaSign || keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral; MPInteger[] sigValues = isRsa ? PgpUtilities.RsaSigToMpi(sigBytes) : PgpUtilities.DsaSigToMpi(sigBytes); return(new PgpSignature( new SignaturePacket(signatureType, privKey.KeyId, keyAlgorithm, hashAlgorithm, hPkts, unhPkts, fingerPrint, sigValues))); }
public PdfEncryption() { md5 = DigestUtilities.GetDigest("MD5"); publicKeyHandler = new PdfPublicKeySecurityHandler(); }
public static KeyParameter MakeKeyFromPassPhrase( SymmetricKeyAlgorithmTag algorithm, S2k s2k, char[] passPhrase) { int keySize = GetKeySize(algorithm); byte[] pBytes = Strings.ToByteArray(new string(passPhrase)); byte[] keyBytes = new byte[(keySize + 7) / 8]; int generatedBytes = 0; int loopCount = 0; while (generatedBytes < keyBytes.Length) { IDigest digest; if (s2k != null) { string digestName = GetDigestName(s2k.HashAlgorithm); try { digest = DigestUtilities.GetDigest(digestName); } catch (Exception e) { throw new PgpException("can't find S2k digest", e); } for (int i = 0; i != loopCount; i++) { digest.Update(0); } byte[] iv = s2k.GetIV(); switch (s2k.Type) { case S2k.Simple: digest.BlockUpdate(pBytes, 0, pBytes.Length); break; case S2k.Salted: digest.BlockUpdate(iv, 0, iv.Length); digest.BlockUpdate(pBytes, 0, pBytes.Length); break; case S2k.SaltedAndIterated: long count = s2k.IterationCount; digest.BlockUpdate(iv, 0, iv.Length); digest.BlockUpdate(pBytes, 0, pBytes.Length); count -= iv.Length + pBytes.Length; while (count > 0) { if (count < iv.Length) { digest.BlockUpdate(iv, 0, (int)count); break; } else { digest.BlockUpdate(iv, 0, iv.Length); count -= iv.Length; } if (count < pBytes.Length) { digest.BlockUpdate(pBytes, 0, (int)count); count = 0; } else { digest.BlockUpdate(pBytes, 0, pBytes.Length); count -= pBytes.Length; } } break; default: throw new PgpException("unknown S2k type: " + s2k.Type); } } else { try { digest = DigestUtilities.GetDigest("MD5"); for (int i = 0; i != loopCount; i++) { digest.Update(0); } digest.BlockUpdate(pBytes, 0, pBytes.Length); } catch (Exception e) { throw new PgpException("can't find MD5 digest", e); } } byte[] dig = DigestUtilities.DoFinal(digest); if (dig.Length > (keyBytes.Length - generatedBytes)) { Array.Copy(dig, 0, keyBytes, generatedBytes, keyBytes.Length - generatedBytes); } else { Array.Copy(dig, 0, keyBytes, generatedBytes, dig.Length); } generatedBytes += dig.Length; loopCount++; } Array.Clear(pBytes, 0, pBytes.Length); return(MakeKey(algorithm, keyBytes)); }
virtual public bool ReadKey(PdfDictionary enc, byte[] password) { if (password == null) { password = new byte[0]; } byte[] oValue = DocWriter.GetISOBytes(enc.Get(PdfName.O).ToString()); byte[] uValue = DocWriter.GetISOBytes(enc.Get(PdfName.U).ToString()); byte[] oeValue = DocWriter.GetISOBytes(enc.Get(PdfName.OE).ToString()); byte[] ueValue = DocWriter.GetISOBytes(enc.Get(PdfName.UE).ToString()); byte[] perms = DocWriter.GetISOBytes(enc.Get(PdfName.PERMS).ToString()); PdfNumber pValue = (PdfNumber)enc.Get(PdfName.P); this.oeKey = oeValue; this.ueKey = ueValue; this.perms = perms; this.ownerKey = oValue; this.userKey = uValue; this.permissions = pValue.LongValue; bool isUserPass = false; IDigest md = DigestUtilities.GetDigest("SHA-256"); md.BlockUpdate(password, 0, Math.Min(password.Length, 127)); md.BlockUpdate(oValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); md.BlockUpdate(uValue, 0, OU_LENGHT); byte[] hash = DigestUtilities.DoFinal(md); bool isOwnerPass = CompareArray(hash, oValue, 32); AESCipherCBCnoPad ac; if (isOwnerPass) { md.BlockUpdate(password, 0, Math.Min(password.Length, 127)); md.BlockUpdate(oValue, KEY_SALT_OFFSET, SALT_LENGHT); md.BlockUpdate(uValue, 0, OU_LENGHT); md.DoFinal(hash, 0); ac = new AESCipherCBCnoPad(false, hash); key = ac.ProcessBlock(oeValue, 0, oeValue.Length); } else { md.BlockUpdate(password, 0, Math.Min(password.Length, 127)); md.BlockUpdate(uValue, VALIDATION_SALT_OFFSET, SALT_LENGHT); md.DoFinal(hash, 0); isUserPass = CompareArray(hash, uValue, 32); if (!isUserPass) { throw new BadPasswordException(MessageLocalization.GetComposedMessage("bad.user.password")); } md.BlockUpdate(password, 0, Math.Min(password.Length, 127)); md.BlockUpdate(uValue, KEY_SALT_OFFSET, SALT_LENGHT); md.DoFinal(hash, 0); ac = new AESCipherCBCnoPad(false, hash); key = ac.ProcessBlock(ueValue, 0, ueValue.Length); } ac = new AESCipherCBCnoPad(false, key); byte[] decPerms = ac.ProcessBlock(perms, 0, perms.Length); if (decPerms[9] != (byte)'a' || decPerms[10] != (byte)'d' || decPerms[11] != (byte)'b') { throw new BadPasswordException(MessageLocalization.GetComposedMessage("bad.user.password")); } permissions = (decPerms[0] & 0xff) | ((decPerms[1] & 0xff) << 8) | ((decPerms[2] & 0xff) << 16) | ((decPerms[2] & 0xff) << 24); encryptMetadata = decPerms[8] == (byte)'T'; return(isOwnerPass); }
public override void Close() { this._digestReceiver.ReceiveDigest(this._fileName, DigestUtilities.DoFinal(ReadDigest())); base.Close(); }
/** * Signs the document using the detached mode, CMS or CAdES equivalent. * @param sap the PdfSignatureAppearance * @param externalSignature the interface providing the actual signing * @param chain the certificate chain * @param crlList the CRL list * @param ocspClient the OCSP client * @param tsaClient the Timestamp client * @param provider the provider or null * @param estimatedSize the reserved size for the signature. It will be estimated if 0 * @param cades true to sign CAdES equivalent PAdES-BES, false to sign CMS * @throws DocumentException * @throws IOException * @throws GeneralSecurityException * @throws NoSuchAlgorithmException * @throws Exception */ public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature, ICollection <X509Certificate> chain, ICollection <ICrlClient> crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype) { List <X509Certificate> certa = new List <X509Certificate>(chain); ICollection <byte[]> crlBytes = null; int i = 0; while (crlBytes == null && i < certa.Count) { crlBytes = ProcessCrl(certa[i++], crlList); } if (estimatedSize == 0) { estimatedSize = 8192; if (crlBytes != null) { foreach (byte[] element in crlBytes) { estimatedSize += element.Length + 10; } } if (ocspClient != null) { //jbonilla - La respuesta del OCSP del BCE es de 6819 estimatedSize += 7168; } //estimatedSize += 4192; if (tsaClient != null) { estimatedSize += 4192; } } sap.Certificate = certa[0]; if (sigtype == CryptoStandard.CADES) { sap.AddDeveloperExtension(PdfDeveloperExtension.ESIC_1_7_EXTENSIONLEVEL2); } PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, sigtype == CryptoStandard.CADES ? PdfName.ETSI_CADES_DETACHED : PdfName.ADBE_PKCS7_DETACHED); dic.Reason = sap.Reason; dic.Location = sap.Location; dic.Contact = sap.Contact; dic.Date = new PdfDate(sap.SignDate); // time-stamp will over-rule this sap.CryptoDictionary = dic; Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = estimatedSize * 2 + 2; sap.PreClose(exc); String hashAlgorithm = externalSignature.GetHashAlgorithm(); PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, false); IDigest messageDigest = DigestUtilities.GetDigest(hashAlgorithm); Stream data = sap.GetRangeStream(); byte[] hash = DigestAlgorithms.Digest(data, hashAlgorithm); DateTime cal = DateTime.Now; byte[] ocsp = null; if (chain.Count >= 2 && ocspClient != null) { ocsp = ocspClient.GetEncoded(certa[0], certa[1], null); } byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp, crlBytes, sigtype); byte[] extSignature = externalSignature.Sign(sh); sgn.SetExternalDigest(extSignature, null, externalSignature.GetEncryptionAlgorithm()); byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal, tsaClient, ocsp, crlBytes, sigtype); if (estimatedSize < encodedSig.Length) { throw new IOException("Not enough space"); } byte[] paddedSig = new byte[estimatedSize]; System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); PdfDictionary dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); }
void doTest( string algorithm) { byte[] message = Encoding.ASCII.GetBytes("hello world"); IDigest digest = DigestUtilities.GetDigest(algorithm); // byte[] result = digest.digest(message); digest.BlockUpdate(message, 0, message.Length); byte[] result = DigestUtilities.DoFinal(digest); // byte[] result2 = digest.digest(message); digest.BlockUpdate(message, 0, message.Length); byte[] result2 = DigestUtilities.DoFinal(digest); // test one digest the same message with the same instance if (!AreEqual(result, result2)) { Fail("Result object 1 not equal"); } // test two, single byte updates for (int i = 0; i < message.Length; i++) { digest.Update(message[i]); } // result2 = digest.digest(); result2 = DigestUtilities.DoFinal(digest); if (!AreEqual(result, result2)) { Fail("Result object 2 not equal"); } // test three, two half updates digest.BlockUpdate(message, 0, message.Length / 2); digest.BlockUpdate(message, message.Length / 2, message.Length - message.Length / 2); // result2 = digest.digest(); result2 = DigestUtilities.DoFinal(digest); if (!AreEqual(result, result2)) { Fail("Result object 3 not equal"); } // TODO Should we support Clone'ing of digests? // // test four, clone test // digest.BlockUpdate(message, 0, message.Length/2); // IDigest d = (IDigest)digest.Clone(); // digest.BlockUpdate(message, message.Length/2, message.Length-message.Length/2); //// result2 = digest.digest(); // result2 = new byte[digest.GetDigestSize()]; // digest.DoFinal(result2, 0); // // if (!AreEqual(result, result2)) // { // Fail("Result object 4(a) not equal"); // } // // d.BlockUpdate(message, message.Length/2, message.Length-message.Length/2); //// result2 = d.digest(); // result2 = new byte[d.GetDigestSize()]; // d.DoFinal(result2, 0); // // if (!AreEqual(result, result2)) // { // Fail("Result object 4(b) not equal"); // } // test five, check reset() method digest.BlockUpdate(message, 0, message.Length / 2); digest.Reset(); digest.BlockUpdate(message, 0, message.Length / 2); digest.BlockUpdate(message, message.Length / 2, message.Length - message.Length / 2); // result2 = digest.digest(); result2 = DigestUtilities.DoFinal(digest); if (!AreEqual(result, result2)) { Fail("Result object 5 not equal"); } }
public Stream GetDataStream(PgpPrivateKey privKey) { //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) byte[] array = RecoverSessionData(privKey); if (!ConfirmCheckSum(array)) { throw new PgpKeyValidationException("key checksum failed"); } SymmetricKeyAlgorithmTag symmetricKeyAlgorithmTag = (SymmetricKeyAlgorithmTag)array[0]; if (symmetricKeyAlgorithmTag == SymmetricKeyAlgorithmTag.Null) { return((Stream)(object)encData.GetInputStream()); } string symmetricCipherName = PgpUtilities.GetSymmetricCipherName(symmetricKeyAlgorithmTag); string text = symmetricCipherName; IBufferedCipher cipher; try { text = ((!(encData is SymmetricEncIntegrityPacket)) ? (text + "/OpenPGPCFB/NoPadding") : (text + "/CFB/NoPadding")); cipher = CipherUtilities.GetCipher(text); } catch (PgpException ex) { throw ex; } catch (global::System.Exception exception) { throw new PgpException("exception creating cipher", exception); } try { KeyParameter parameters = ParameterUtilities.CreateKeyParameter(symmetricCipherName, array, 1, array.Length - 3); byte[] array2 = new byte[cipher.GetBlockSize()]; cipher.Init(forEncryption: false, new ParametersWithIV(parameters, array2)); encStream = (Stream)(object)BcpgInputStream.Wrap((Stream)(object)new CipherStream((Stream)(object)encData.GetInputStream(), cipher, null)); if (encData is SymmetricEncIntegrityPacket) { truncStream = new TruncatedStream(encStream); string digestName = PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1); IDigest digest = DigestUtilities.GetDigest(digestName); encStream = (Stream)(object)new DigestStream((Stream)(object)truncStream, digest, null); } if (Streams.ReadFully(encStream, array2, 0, array2.Length) < array2.Length) { throw new EndOfStreamException("unexpected end of stream."); } int num = encStream.ReadByte(); int num2 = encStream.ReadByte(); if (num < 0 || num2 < 0) { throw new EndOfStreamException("unexpected end of stream."); } return(encStream); } catch (PgpException ex2) { throw ex2; } catch (global::System.Exception exception2) { throw new PgpException("Exception starting decryption", exception2); } }
private void DoClose() { Platform.Dispose(_out); // TODO Parent context(s) should really be be closed explicitly _eiGen.Close(); outer._digests.Clear(); // clear the current preserved digest state if (outer._certs.Count > 0) { Asn1Set certs = CmsUtilities.CreateBerSetFromList(outer._certs); WriteToGenerator(_sigGen, new BerTaggedObject(false, 0, certs)); } if (outer._crls.Count > 0) { Asn1Set crls = CmsUtilities.CreateBerSetFromList(outer._crls); WriteToGenerator(_sigGen, new BerTaggedObject(false, 1, crls)); } // // Calculate the digest hashes // foreach (DictionaryEntry de in outer._messageDigests) { outer._messageHashes.Add(de.Key, DigestUtilities.DoFinal((IDigest)de.Value)); } // TODO If the digest OIDs for precalculated signers weren't mixed in with // the others, we could fill in outer._digests here, instead of SignerInfoGenerator.Generate // // collect all the SignerInfo objects // Asn1EncodableVector signerInfos = new Asn1EncodableVector(); // // add the generated SignerInfo objects // { foreach (DigestAndSignerInfoGeneratorHolder holder in outer._signerInfs) { AlgorithmIdentifier digestAlgorithm = holder.DigestAlgorithm; byte[] calculatedDigest = (byte[])outer._messageHashes[ Helper.GetDigestAlgName(holder.digestOID)]; outer._digests[holder.digestOID] = calculatedDigest.Clone(); signerInfos.Add(holder.signerInf.Generate(_contentOID, digestAlgorithm, calculatedDigest)); } } // // add the precalculated SignerInfo objects. // { foreach (SignerInformation signer in outer._signers) { // TODO Verify the content type and calculated digest match the precalculated SignerInfo // if (!signer.ContentType.Equals(_contentOID)) // { // // TODO The precalculated content type did not match - error? // } // // byte[] calculatedDigest = (byte[])outer._digests[signer.DigestAlgOid]; // if (calculatedDigest == null) // { // // TODO We can't confirm this digest because we didn't calculate it - error? // } // else // { // if (!Arrays.AreEqual(signer.GetContentDigest(), calculatedDigest)) // { // // TODO The precalculated digest did not match - error? // } // } signerInfos.Add(signer.ToSignerInfo()); } } WriteToGenerator(_sigGen, new DerSet(signerInfos)); _sigGen.Close(); _sGen.Close(); }
internal IDigest GetDigestInstance( string algorithm) { return(DigestUtilities.GetDigest(algorithm)); }
/// <summary> /// Gets the data stream. /// </summary> /// <param name="privKey">The priv key.</param> /// <param name="encryptionAlgorithm">The encryption algorithm.</param> /// <returns></returns> /// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException"> /// exception creating cipher /// or /// Exception starting decryption /// </exception> /// <exception cref="System.IO.EndOfStreamException"> /// unexpected end of stream. /// or /// unexpected end of stream. /// </exception> public Stream GetDataStream(IPgpPrivateKey privKey, out SymmetricKeyAlgorithmTag encryptionAlgorithm) { var plain = this.FetchSymmetricKeyData(privKey); encryptionAlgorithm = (SymmetricKeyAlgorithmTag)plain[0]; IBufferedCipher c2; var cipherName = PgpUtilities.GetSymmetricCipherName(encryptionAlgorithm); var cName = cipherName; try { if (EncData is SymmetricEncIntegrityPacket) { cName += "/CFB/NoPadding"; } else { cName += "/OpenPGPCFB/NoPadding"; } c2 = CipherUtilities.GetCipher(cName); } catch (PgpException) { throw; } catch (Exception e) { throw new PgpException("exception creating cipher", e); } if (c2 == null) { return(EncData.GetInputStream()); } try { var key = ParameterUtilities.CreateKeyParameter(cipherName, plain, 1, plain.Length - 3); var iv = new byte[c2.GetBlockSize()]; c2.Init(false, new ParametersWithIV(key, iv)); this.EncStream = BcpgInputStream.Wrap(new CipherStream(EncData.GetInputStream(), c2, null)); if (this.EncData is SymmetricEncIntegrityPacket) { this.TruncStream = new TruncatedStream(this.EncStream); var digest = DigestUtilities.GetDigest(PgpUtilities.GetDigestName(HashAlgorithmTag.Sha1)); EncStream = new DigestStream(TruncStream, digest, null); } if (Streams.ReadFully(EncStream, iv, 0, iv.Length) < iv.Length) { throw new EndOfStreamException("unexpected end of stream."); } var v1 = this.EncStream.ReadByte(); var v2 = this.EncStream.ReadByte(); if (v1 < 0 || v2 < 0) { throw new EndOfStreamException("unexpected end of stream."); } // Note: the oracle attack on the "quick check" bytes is deemed // a security risk for typical public key encryption usages, // therefore we do not perform the check. // bool repeatCheckPassed = // iv[iv.Length - 2] == (byte)v1 // && iv[iv.Length - 1] == (byte)v2; // // // Note: some versions of PGP appear to produce 0 for the extra // // bytes rather than repeating the two previous bytes // bool zeroesCheckPassed = // v1 == 0 // && v2 == 0; // // if (!repeatCheckPassed && !zeroesCheckPassed) // { // throw new PgpDataValidationException("quick check failed."); // } return(this.EncStream); } catch (PgpException) { throw; } catch (Exception e) { throw new PgpException("Exception starting decryption", e); } }
public DeterministicECDSA(string hashName) : base(new HMacDsaKCalculator(DigestUtilities.GetDigest(hashName))) { _digest = DigestUtilities.GetDigest(hashName); }
/// <exception cref="Org.BouncyCastle.Security.SecurityUtilityException"/> private static byte[] HashBytesSha1(byte[] b) { IDigest sh = DigestUtilities.GetDigest("SHA1"); return(sh.Digest(b)); }
private void Init() { IBcpgKey key = publicPk.Key; if (publicPk.Version <= 3) { RsaPublicBcpgKey rK = (RsaPublicBcpgKey)key; this.keyId = rK.Modulus.LongValue; try { IDigest digest = DigestUtilities.GetDigest("MD5"); byte[] bytes = rK.Modulus.ToByteArrayUnsigned(); digest.BlockUpdate(bytes, 0, bytes.Length); bytes = rK.PublicExponent.ToByteArrayUnsigned(); digest.BlockUpdate(bytes, 0, bytes.Length); this.fingerprint = DigestUtilities.DoFinal(digest); } //catch (NoSuchAlgorithmException) catch (Exception e) { throw new IOException("can't find MD5", e); } this.keyStrength = rK.Modulus.BitLength; } else { byte[] kBytes = publicPk.GetEncodedContents(); try { IDigest digest = DigestUtilities.GetDigest("SHA1"); digest.Update(0x99); digest.Update((byte)(kBytes.Length >> 8)); digest.Update((byte)kBytes.Length); digest.BlockUpdate(kBytes, 0, kBytes.Length); this.fingerprint = DigestUtilities.DoFinal(digest); } catch (Exception e) { throw new IOException("can't find SHA1", e); } this.keyId = (long)(((ulong)fingerprint[fingerprint.Length - 8] << 56) | ((ulong)fingerprint[fingerprint.Length - 7] << 48) | ((ulong)fingerprint[fingerprint.Length - 6] << 40) | ((ulong)fingerprint[fingerprint.Length - 5] << 32) | ((ulong)fingerprint[fingerprint.Length - 4] << 24) | ((ulong)fingerprint[fingerprint.Length - 3] << 16) | ((ulong)fingerprint[fingerprint.Length - 2] << 8) | (ulong)fingerprint[fingerprint.Length - 1]); if (key is RsaPublicBcpgKey) { this.keyStrength = ((RsaPublicBcpgKey)key).Modulus.BitLength; } else if (key is DsaPublicBcpgKey) { this.keyStrength = ((DsaPublicBcpgKey)key).P.BitLength; } else if (key is ElGamalPublicBcpgKey) { this.keyStrength = ((ElGamalPublicBcpgKey)key).P.BitLength; } } }
public static byte[] Digest(string algo, byte[] b, int offset, int len) { return(Digest(DigestUtilities.GetDigest(algo), b, offset, len)); }