internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory <AlgorithmIdentifier> signerFactory, IDigestFactoryProvider <AlgorithmIdentifier> digesterProvider, ISignatureEncryptionAlgorithmFinder sigEncAlgFinder, bool isDirectSignature) { this.sigId = sigId; this.signer = signerFactory; this.signerCalculator = signerFactory.CreateCalculator(); if (digesterProvider != null) { this.digester = digesterProvider.CreateDigestFactory(digAlgFinder.Find(signer.AlgorithmDetails)); this.digestCalculator = digester.CreateCalculator(); } else { this.digester = null; } this.sigEncAlgFinder = sigEncAlgFinder; this.isDirectSignature = isDirectSignature; if (this.isDirectSignature) { this.signedGen = null; this.unsignedGen = null; } else { this.signedGen = new DefaultSignedAttributeTableGenerator(); this.unsignedGen = null; } }
public SigWithDigestFactory(PublicKeyAlgorithmTag keyAlg, HashAlgorithmTag hashAlg, long keyId, AsymmetricRsaPrivateKey privateKey) { this.keyAlg = keyAlg; this.hashAlg = hashAlg; this.keyId = keyId; this.privateKey = privateKey; sigFact = CryptoServicesRegistrar.CreateService(privateKey, new SecureRandom()).CreateSignatureFactory(FipsRsa.Pkcs1v15.WithDigest((FipsDigestAlgorithm)PgpUtils.digests[hashAlg])); digFact = CryptoServicesRegistrar.CreateService((FipsShs.Parameters)PgpUtils.digests[hashAlg]); }
internal SignerInfoGenerator(SignerIdentifier sigId, ISignatureFactory <AlgorithmIdentifier> contentSigner, IDigestFactoryProvider <AlgorithmIdentifier> digesterProvider, ISignatureEncryptionAlgorithmFinder sigEncAlgFinder, ICmsAttributeTableGenerator signedGen, ICmsAttributeTableGenerator unsignedGen) { this.sigId = sigId; this.signer = contentSigner; this.signerCalculator = contentSigner.CreateCalculator(); if (digesterProvider != null) { this.digester = digesterProvider.CreateDigestFactory(digAlgFinder.Find(signer.AlgorithmDetails)); this.digestCalculator = digester.CreateCalculator(); } else { this.digester = null; } this.sigEncAlgFinder = sigEncAlgFinder; this.signedGen = signedGen; this.unsignedGen = unsignedGen; this.isDirectSignature = false; }
private static byte[] checksum(IDigestFactory <PgpDigestTypeIdentifier> digCalcFactory, byte[] bytes, int length) { if (digCalcFactory != null) { IStreamCalculator <IBlockResult> digCalc = digCalcFactory.CreateCalculator(); Stream dOut = digCalc.Stream; try { dOut.Write(bytes, 0, length); dOut.Close(); } catch (Exception e) { throw new PgpException("checksum digest calculation failed: " + e.Message, e); } return(digCalc.GetResult().Collect()); } else { int checksum = 0; for (int i = 0; i != length; i++) { checksum += bytes[i] & 0xff; } byte[] check = new byte[2]; check[0] = (byte)(checksum >> 8); check[1] = (byte)checksum; return(check); } }
public TimeStampTokenGenerator( SignerInfoGenerator signerInfoGen, IDigestFactory digestCalculator, DerObjectIdentifier tsaPolicy, bool isIssuerSerialIncluded) { this.signerInfoGenerator = signerInfoGen; this.digestCalculator = digestCalculator; this.tsaPolicyOID = tsaPolicy != null ? tsaPolicy.Id : null; if (signerInfoGenerator.certificate == null) { throw new ArgumentException("SignerInfoGenerator must have an associated certificate"); } X509Certificate assocCert = signerInfoGenerator.certificate; TspUtil.ValidateCertificate(assocCert); try { IStreamCalculator calculator = digestCalculator.CreateCalculator(); Stream stream = calculator.Stream; byte[] certEnc = assocCert.GetEncoded(); stream.Write(certEnc, 0, certEnc.Length); stream.Flush(); stream.Close(); if (((AlgorithmIdentifier)digestCalculator.AlgorithmDetails).Algorithm.Equals(OiwObjectIdentifiers.IdSha1)) { EssCertID essCertID = new EssCertID( ((IBlockResult)calculator.GetResult()).Collect(), isIssuerSerialIncluded ? new IssuerSerial( new GeneralNames( new GeneralName(assocCert.IssuerDN)), new DerInteger(assocCert.SerialNumber)) : null); this.signerInfoGenerator = signerInfoGen.NewBuilder() .WithSignedAttributeGenerator(new TableGen(signerInfoGen, essCertID)) .Build(signerInfoGen.contentSigner, signerInfoGen.certificate); } else { AlgorithmIdentifier digestAlgID = new AlgorithmIdentifier( ((AlgorithmIdentifier)digestCalculator.AlgorithmDetails).Algorithm); EssCertIDv2 essCertID = new EssCertIDv2( ((IBlockResult)calculator.GetResult()).Collect(), isIssuerSerialIncluded ? new IssuerSerial( new GeneralNames( new GeneralName(assocCert.IssuerDN)), new DerInteger(assocCert.SerialNumber)) : null); this.signerInfoGenerator = signerInfoGen.NewBuilder() .WithSignedAttributeGenerator(new TableGen2(signerInfoGen, essCertID)) .Build(signerInfoGen.contentSigner, signerInfoGen.certificate); } } catch (Exception ex) { throw new TspException("Exception processing certificate", ex); } }
private bool doVerify(bool isRawVerifier, IVerifierFactory <AlgorithmIdentifier> verifierFactory, IDigestFactory <AlgorithmIdentifier> digestFactory) { IStreamCalculator <IVerifier> contentVerifier = verifierFactory.CreateCalculator(); Stream sigOut = contentVerifier.Stream; try { if (resultDigest == null) { IStreamCalculator <IBlockResult> calc = digestFactory.CreateCalculator(); if (content != null) { Stream digOut = calc.Stream; if (signedAttributeSet == null) { if (isRawVerifier) { content.Write(digOut); } else { Stream cOut = new TeeOutputStream(digOut, sigOut); content.Write(cOut); cOut.Close(); } } else { content.Write(digOut); byte[] enc = this.GetEncodedSignedAttributes(); sigOut.Write(enc, 0, enc.Length); } digOut.Close(); } else if (signedAttributeSet != null) { byte[] enc = this.GetEncodedSignedAttributes(); sigOut.Write(enc, 0, enc.Length); } else { // TODO Get rid of this exception and just treat content==null as empty not missing? throw new CmsException("data not encapsulated in signature - use detached constructor."); } resultDigest = calc.GetResult().Collect(); } else { if (signedAttributeSet == null) { if (content != null) { content.Write(sigOut); } } else { byte[] enc = this.GetEncodedSignedAttributes(); sigOut.Write(enc, 0, enc.Length); } } sigOut.Close(); } catch (Exception e) { throw new CmsException("can't process object to create signature.", e); } // RFC 3852 11.1 Check the content-type attribute is correct { Asn1Object validContentType = GetSingleValuedSignedAttribute( CmsAttributes.ContentType, "content-type"); if (validContentType == null) { if (!isCounterSignature && signedAttributeSet != null) { throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data"); } } else { if (isCounterSignature) { throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute"); } if (!(validContentType is DerObjectIdentifier)) { throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'"); } DerObjectIdentifier signedContentType = (DerObjectIdentifier)validContentType; if (!signedContentType.Equals(contentType)) { throw new CmsException("content-type attribute value does not match eContentType"); } } } Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes; // RFC 6211 Validate Algorithm Identifier protection attribute if present { Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes; if (unsignedAttrTable != null && unsignedAttrTable.GetAll(CmsAttributes.CmsAlgorithmProtect).Count > 0) { throw new CmsException("A cmsAlgorithmProtect attribute MUST be a signed attribute"); } if (signedAttrTable != null) { Asn1EncodableVector protectionAttributes = signedAttrTable.GetAll(CmsAttributes.CmsAlgorithmProtect); if (protectionAttributes.Count > 1) { throw new CmsException("Only one instance of a cmsAlgorithmProtect attribute can be present"); } if (protectionAttributes.Count > 0) { Asn1.Cms.Attribute attr = Asn1.Cms.Attribute.GetInstance(protectionAttributes[0]); if (attr.AttrValues.Count != 1) { throw new CmsException("A cmsAlgorithmProtect attribute MUST contain exactly one value"); } CmsAlgorithmProtection algorithmProtection = CmsAlgorithmProtection.GetInstance(attr.AttrValues[0]); if (!CmsUtilities.IsEquivalent(algorithmProtection.DigestAlgorithm, info.DigestAlgorithm)) { throw new CmsException("CMS Algorithm Identifier Protection check failed for digestAlgorithm"); } if (!CmsUtilities.IsEquivalent(algorithmProtection.SignatureAlgorithm, info.DigestEncryptionAlgorithm)) { throw new CmsException("CMS Algorithm Identifier Protection check failed for signatureAlgorithm"); } } } } // RFC 3852 11.2 Check the message-digest attribute is correct { Asn1Encodable validMessageDigest = GetSingleValuedSignedAttribute( CmsAttributes.MessageDigest, "message-digest"); if (validMessageDigest == null) { if (signedAttributeSet != null) { throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present"); } } else { if (!(validMessageDigest is Asn1OctetString)) { throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'"); } Asn1OctetString signedMessageDigest = (Asn1OctetString)validMessageDigest; if (!Arrays.ConstantTimeAreEqual(resultDigest, signedMessageDigest.GetOctets())) { throw new CmsSignerDigestMismatchException("message-digest attribute value does not match calculated value"); } } } // RFC 3852 11.4 Validate countersignature attribute(s) { if (signedAttrTable != null && signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0) { throw new CmsException("A countersignature attribute MUST NOT be a signed attribute"); } Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes; if (unsignedAttrTable != null) { Asn1EncodableVector csAttrs = unsignedAttrTable.GetAll(CmsAttributes.CounterSignature); for (int i = 0; i < csAttrs.Count; ++i) { Asn1.Cms.Attribute csAttr = Asn1.Cms.Attribute.GetInstance(csAttrs[i]); if (csAttr.AttrValues.Count < 1) { throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue"); } // Note: We don't recursively validate the countersignature value } } } try { if (signedAttributeSet == null && resultDigest != null) { if (isRawVerifier) { if (SignatureAlgorithmID.Algorithm.Equals(PkcsObjectIdentifiers.RsaEncryption)) { DigestInfo digInfo = new DigestInfo(new AlgorithmIdentifier(digestAlgorithm.Algorithm, DerNull.Instance), resultDigest); byte[] data = digInfo.GetEncoded(Asn1Encodable.Der); sigOut.Write(data, 0, data.Length); sigOut.Close(); return(contentVerifier.GetResult().IsVerified(this.GetSignature())); } sigOut.Write(resultDigest, 0, resultDigest.Length); sigOut.Close(); return(contentVerifier.GetResult().IsVerified(this.GetSignature())); } } sigOut.Close(); return(contentVerifier.GetResult().IsVerified(this.GetSignature())); } catch (IOException e) { throw new CmsException("can't process mime object to create signature.", e); } }
/// <summary> /// Base constructor. /// </summary> /// <param name="digestFactory">The digest factory to base key info/identifier calculations on.</param> public X509ExtensionUtilities(IDigestFactory <FipsShs.Parameters> digestFactory) { this.digestFactory = digestFactory; }
internal static byte[] MakeKeyFromPassPhrase( IDigestFactory <PgpDigestTypeIdentifier> digestFactory, SymmetricKeyAlgorithmTag algorithm, S2k s2k, char[] passPhrase) { int keySize = 0; switch (algorithm) { case SymmetricKeyAlgorithmTag.TripleDes: keySize = 192; break; case SymmetricKeyAlgorithmTag.Idea: keySize = 128; break; case SymmetricKeyAlgorithmTag.Cast5: keySize = 128; break; case SymmetricKeyAlgorithmTag.Blowfish: keySize = 128; break; case SymmetricKeyAlgorithmTag.Safer: keySize = 128; break; case SymmetricKeyAlgorithmTag.Des: keySize = 64; break; case SymmetricKeyAlgorithmTag.Aes128: keySize = 128; break; case SymmetricKeyAlgorithmTag.Aes192: keySize = 192; break; case SymmetricKeyAlgorithmTag.Aes256: keySize = 256; break; case SymmetricKeyAlgorithmTag.Twofish: keySize = 256; break; case SymmetricKeyAlgorithmTag.Camellia128: keySize = 128; break; case SymmetricKeyAlgorithmTag.Camellia192: keySize = 192; break; case SymmetricKeyAlgorithmTag.Camellia256: keySize = 256; break; default: throw new PgpException("unknown symmetric algorithm: " + algorithm); } byte[] pBytes = Strings.ToUtf8ByteArray(passPhrase); byte[] keyBytes = new byte[(keySize + 7) / 8]; int generatedBytes = 0; int loopCount = 0; if (s2k != null) { if (s2k.HashAlgorithm != digestFactory.AlgorithmDetails.Algorithm) { throw new PgpException("s2k/digestFactory mismatch"); } } else { if (digestFactory.AlgorithmDetails.Algorithm != HashAlgorithmTag.MD5) { throw new PgpException("digestFactory not for MD5"); } } IStreamCalculator <IBlockResult> digestCalculator = digestFactory.CreateCalculator(); Stream dOut = digestCalculator.Stream; try { while (generatedBytes < keyBytes.Length) { if (s2k != null) { for (int i = 0; i != loopCount; i++) { dOut.WriteByte(0); } byte[] iv = s2k.GetIV(); switch (s2k.Type) { case S2k.Simple: dOut.Write(pBytes, 0, pBytes.Length); break; case S2k.Salted: dOut.Write(iv, 0, iv.Length); dOut.Write(pBytes, 0, pBytes.Length); break; case S2k.SaltedAndIterated: long count = s2k.IterationCount; dOut.Write(iv, 0, iv.Length); dOut.Write(pBytes, 0, pBytes.Length); count -= iv.Length + pBytes.Length; while (count > 0) { if (count < iv.Length) { dOut.Write(iv, 0, (int)count); break; } else { dOut.Write(iv, 0, iv.Length); count -= iv.Length; } if (count < pBytes.Length) { dOut.Write(pBytes, 0, (int)count); count = 0; } else { dOut.Write(pBytes, 0, pBytes.Length); count -= pBytes.Length; } } break; default: throw new PgpException("unknown S2K type: " + s2k.Type); } } else { for (int i = 0; i != loopCount; i++) { dOut.WriteByte((byte)0); } dOut.Write(pBytes, 0, pBytes.Length); } dOut.Close(); byte[] dig = digestCalculator.GetResult().Collect(); 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++; } } catch (IOException e) { throw new PgpException("exception calculating digest: " + e.Message, e); } for (int i = 0; i != pBytes.Length; i++) { pBytes[i] = 0; } return(keyBytes); }
internal SecretKeyDecryptor(SymmetricKeyAlgorithmTag symAlg, byte[] key, byte[] iv, S2k s2k, IDigestFactory <PgpDigestTypeIdentifier> checksumCalculatorFactory) { FipsTripleDes.ParametersWithIV parameters; parameters = FipsTripleDes.Cfb64.WithIV(iv); this.s2k = s2k; cipherBuilder = CryptoServicesRegistrar.CreateService(new FipsTripleDes.Key(key)).CreateDecryptorBuilder(FipsTripleDes.Cfb64.WithIV(iv)); }
internal SecretKeyEncryptor(SymmetricKeyAlgorithmTag symAlg, byte[] key, byte[] iv, S2k s2k, IDigestFactory <PgpDigestTypeIdentifier> checksumCalculatorFactory) { FipsTripleDes.ParametersWithIV parameters; if (iv != null) { parameters = FipsTripleDes.Cfb64.WithIV(iv); this.iv = iv; } else { if (this.random == null) { this.random = new SecureRandom(); } parameters = FipsTripleDes.Cfb64.WithIV(random); this.iv = parameters.GetIV(); } this.s2k = s2k; cipherBuilder = CryptoServicesRegistrar.CreateService(new FipsTripleDes.Key(key)).CreateEncryptorBuilder(FipsTripleDes.Cfb64.WithIV(iv)); }
public PgpPbeSecretKeyEncryptorBuilder WithS2kDigestFactory(IDigestFactory <PgpDigestTypeIdentifier> s2kDigestFactory) { this.s2kDigestFactory = s2kDigestFactory; return(this); }
internal SigWithDigest(ISignatureFactory <IParameters <Algorithm> > sigFact, IDigestFactory <IParameters <Algorithm> > digFact) { this.sigCalc = sigFact.CreateCalculator(); this.digCalc = digFact.CreateCalculator(); this.jointStream = new TeeOutputStream(sigCalc.Stream, digCalc.Stream); }
public PkixDigestFactory(AlgorithmIdentifier algorithmID) { this.algorithmID = algorithmID; this.digestFact = CryptoServicesRegistrar.CreateService((FipsShs.Parameters)Utils.digestTable[algorithmID.Algorithm]); }