Inheritance: Asn1Sequence
		public override void PerformTest()
        {
            CommitmentTypeIndication cti = new CommitmentTypeIndication(CommitmentTypeIdentifier.ProofOfOrigin);

            CheckConstruction(cti, CommitmentTypeIdentifier.ProofOfOrigin, null);

            Asn1Sequence qualifier = new DerSequence(new DerObjectIdentifier("1.2"));

            cti = new CommitmentTypeIndication(CommitmentTypeIdentifier.ProofOfOrigin, qualifier);

            CheckConstruction(cti, CommitmentTypeIdentifier.ProofOfOrigin, qualifier);

            cti = CommitmentTypeIndication.GetInstance(null);

            if (cti != null)
            {
                Fail("null GetInstance() failed.");
            }

            try
            {
                CommitmentTypeIndication.GetInstance(new object());

                Fail("GetInstance() failed to detect bad object.");
            }
            catch (ArgumentException)
            {
                // expected
            }
        }
		public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
		{
			byte[] keyBytes = contentEncryptionKey.GetKey();

			string rfc3211WrapperName = Helper.GetRfc3211WrapperName(keyEncryptionKeyOID);
			IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName);

			// Note: In Java build, the IV is automatically generated in JCE layer
			int ivLength = Platform.StartsWith(rfc3211WrapperName, "DESEDE") ? 8 : 16;
			byte[] iv = new byte[ivLength];
			random.NextBytes(iv);

			ICipherParameters parameters = new ParametersWithIV(keyEncryptionKey, iv);
			keyWrapper.Init(true, new ParametersWithRandom(parameters, random));
        	Asn1OctetString encryptedKey = new DerOctetString(
				keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

			DerSequence seq = new DerSequence(
				new DerObjectIdentifier(keyEncryptionKeyOID),
				new DerOctetString(iv));

			AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(
				PkcsObjectIdentifiers.IdAlgPwriKek, seq);

			return new RecipientInfo(new PasswordRecipientInfo(
				keyDerivationAlgorithm, keyEncryptionAlgorithm, encryptedKey));
		}
        public int GenerateBytes(byte[] outBytes, int outOff, int len)
        {
            // TODO Create an ASN.1 class for this (RFC3278)
            // ECC-CMS-SharedInfo
            var s = new DerSequence(
                new AlgorithmIdentifier(_algorithm, DerNull.Instance),
                new DerTaggedObject(true, 2, new DerOctetString(IntegerToBytes(_keySize))));

            _kdf.Init(new KdfParameters(_z, s.GetDerEncoded()));

            return _kdf.GenerateBytes(outBytes, outOff, len);
        }
        public virtual int GenerateBytes(byte[]	outBytes, int outOff, int len)
        {
            // TODO Create an ASN.1 class for this (RFC3278)
            // ECC-CMS-SharedInfo
            DerSequence s = new DerSequence(
                new AlgorithmIdentifier(algorithm, DerNull.Instance),
                new DerTaggedObject(true, 2, new DerOctetString(Pack.UInt32_To_BE((uint)keySize))));

            kdf.Init(new KdfParameters(z, s.GetDerEncoded()));

            return kdf.GenerateBytes(outBytes, outOff, len);
        }
        public int GenerateBytes(
			byte[]	outBytes,
			int		outOff,
			int		len)
        {
            // ECC-CMS-SharedInfo
            DerSequence s = new DerSequence(
                new AlgorithmIdentifier(algorithm, DerNull.Instance),
                new DerTaggedObject(true, 2, new DerOctetString(integerToBytes(keySize))));

            kdf.Init(new KdfParameters(z, s.GetDerEncoded()));

            return kdf.GenerateBytes(outBytes, outOff, len);
        }
Beispiel #6
0
 public void TestFormatSignature()
 {
     var random = new Random();
       var dsa_key = new SshKey(SshVersion.SSH2, new DsaPublicKeyParameters (
     new BigInteger ("1"),
     new DsaParameters(new BigInteger ("2"), new BigInteger ("3"),
                   new BigInteger ("4"))));
       // test that dsa signature works when values are not full 20 bytes.
       byte[] r_bytes = new byte[19];
       byte[] s_bytes = new byte[19];
       random.NextBytes(r_bytes);
       random.NextBytes(s_bytes);
       var r = new DerInteger(r_bytes);
       var s = new DerInteger(s_bytes);
       var sequence = new DerSequence(r, s);
       var signature = dsa_key.FormatSignature(sequence.GetEncoded());
       Assert.That(signature.Count(), Is.EqualTo(40));
 }
			internal RecipientInfo ToRecipientInfo(
				KeyParameter	key,
				SecureRandom	random)
			{
				byte[] keyBytes = key.GetKey();

				if (pubKey != null)
				{
					IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id);

					keyWrapper.Init(true, new ParametersWithRandom(pubKey, random));

					Asn1OctetString encKey = new DerOctetString(
						keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

					RecipientIdentifier recipId;
					if (cert != null)
					{
						TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
							Asn1Object.FromByteArray(cert.GetTbsCertificate()));

						Asn1.Cms.IssuerAndSerialNumber encSid = new Asn1.Cms.IssuerAndSerialNumber(
							tbs.Issuer, tbs.SerialNumber.Value);

						recipId = new RecipientIdentifier(encSid);
					}
					else
					{
						recipId = new RecipientIdentifier(subKeyId);
					}

					return new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncAlg, encKey));
				}
				else if (originator != null)
				{
					IWrapper keyWrapper = Helper.CreateWrapper(
						DerObjectIdentifier.GetInstance(
							Asn1Sequence.GetInstance(keyEncAlg.Parameters)[0]).Id);

					keyWrapper.Init(true, new ParametersWithRandom(secKey, random));

					Asn1OctetString encKey = new DerOctetString(
						keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

					RecipientEncryptedKey rKey = new RecipientEncryptedKey(
						new KeyAgreeRecipientIdentifier(
							new Asn1.Cms.IssuerAndSerialNumber(
								PrincipalUtilities.GetIssuerX509Principal(cert),
								cert.SerialNumber)),
						encKey);

					return new RecipientInfo(
						new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg, new DerSequence(rKey)));
				}
				else if (derivationAlg != null)
				{
					string rfc3211WrapperName = Helper.GetRfc3211WrapperName(secKeyAlgorithm);
					IWrapper keyWrapper = Helper.CreateWrapper(rfc3211WrapperName);


					// Note: In Java build, the IV is automatically generated in JCE layer
					int ivLength = rfc3211WrapperName.StartsWith("DESEDE") ? 8 : 16;
					byte[] iv = new byte[ivLength];
					random.NextBytes(iv);


					ICipherParameters parameters = new ParametersWithIV(secKey, iv);
					keyWrapper.Init(true, new ParametersWithRandom(parameters, random));

					Asn1OctetString encKey = new DerOctetString(
						keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

//					byte[] iv = keyWrapper.GetIV();

					DerSequence seq = new DerSequence(
						new DerObjectIdentifier(secKeyAlgorithm),
						new DerOctetString(iv));

					keyEncAlg = new AlgorithmIdentifier(PkcsObjectIdentifiers.IdAlgPwriKek, seq);

					return new RecipientInfo(new PasswordRecipientInfo(derivationAlg, keyEncAlg, encKey));
				}
				else
				{
					IWrapper keyWrapper = Helper.CreateWrapper(keyEncAlg.ObjectID.Id);

					keyWrapper.Init(true, new ParametersWithRandom(secKey, random));

					Asn1OctetString encKey = new DerOctetString(
						keyWrapper.Wrap(keyBytes, 0, keyBytes.Length));

					return new RecipientInfo(new KekRecipientInfo(secKeyId, keyEncAlg, encKey));
				}
			}
			public RecipientInf(
				string						secKeyAlgorithm, // TODO Can get this from secKey?
				KeyParameter				secKey,
				string						algorithm,
				string						wrapOid,
				OriginatorIdentifierOrKey	originator,
				X509Certificate				cert)
			{
				DerSequence paramSeq = new DerSequence(
					new DerObjectIdentifier(wrapOid),
					DerNull.Instance);

				this.secKeyAlgorithm = secKeyAlgorithm;
				this.secKey = secKey;
				this.keyEncAlg = new AlgorithmIdentifier(new DerObjectIdentifier(algorithm), paramSeq);
				this.originator = originator;
				this.cert = cert;
			}
        private BasicOcspResp GenerateResponse(
			string					signatureName,
			IAsymmetricKeyParameter	privateKey,
			X509Certificate[]		chain,
			DateTime				producedAt,
			SecureRandom			random)
        {
            DerObjectIdentifier signingAlgorithm;
            try
            {
                signingAlgorithm = OcspUtilities.GetAlgorithmOid(signatureName);
            }
            catch (Exception e)
            {
                throw new ArgumentException("unknown signing algorithm specified", e);
            }

            Asn1EncodableVector responses = new Asn1EncodableVector();

            foreach (ResponseObject respObj in list)
            {
                try
                {
                    responses.Add(respObj.ToResponse());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating Request", e);
                }
            }

            ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions);

            ISigner sig = null;

            try
            {
                sig = SignerUtilities.GetSigner(signatureName);

                if (random != null)
                {
                    sig.Init(true, new ParametersWithRandom(privateKey, random));
                }
                else
                {
                    sig.Init(true, privateKey);
                }
            }
            catch (Exception e)
            {
                throw new OcspException("exception creating signature: " + e, e);
            }

            DerBitString bitSig = null;

            try
            {
                byte[] encoded = tbsResp.GetDerEncoded();
                sig.BlockUpdate(encoded, 0, encoded.Length);

                bitSig = new DerBitString(sig.GenerateSignature());
            }
            catch (Exception e)
            {
                throw new OcspException("exception processing TBSRequest: " + e, e);
            }

            AlgorithmIdentifier sigAlgId = OcspUtilities.GetSigAlgID(signingAlgorithm);

            DerSequence chainSeq = null;
            if (chain != null && chain.Length > 0)
            {
                Asn1EncodableVector v = new Asn1EncodableVector();
                try
                {
                    for (int i = 0; i != chain.Length; i++)
                    {
                        v.Add(
                            X509CertificateStructure.GetInstance(
                                Asn1Object.FromByteArray(chain[i].GetEncoded())));
                    }
                }
                catch (IOException e)
                {
                    throw new OcspException("error processing certs", e);
                }
                catch (CertificateEncodingException e)
                {
                    throw new OcspException("error encoding certs", e);
                }

                chainSeq = new DerSequence(v);
            }

            return new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, chainSeq));
        }
        internal Asn1Object ReadTaggedObject(bool constructed, int tag)
        {
            if (!constructed)
            {
                DefiniteLengthInputStream definiteLengthInputStream = (DefiniteLengthInputStream)_in;
                return(new DerTaggedObject(explicitly: false, tag, new DerOctetString(definiteLengthInputStream.ToArray())));
            }
            Asn1EncodableVector asn1EncodableVector = ReadVector();

            if (_in is IndefiniteLengthInputStream)
            {
                return((asn1EncodableVector.Count != 1) ? new BerTaggedObject(explicitly: false, tag, BerSequence.FromVector(asn1EncodableVector)) : new BerTaggedObject(explicitly: true, tag, asn1EncodableVector[0]));
            }
            return((asn1EncodableVector.Count != 1) ? new DerTaggedObject(explicitly: false, tag, DerSequence.FromVector(asn1EncodableVector)) : new DerTaggedObject(explicitly: true, tag, asn1EncodableVector[0]));
        }
Beispiel #11
0
 private static byte[] BuildOCSPResponse(byte[] BasicOCSPResponse) {
     DerOctetString doctet = new DerOctetString(BasicOCSPResponse);
     Asn1EncodableVector v2 = new Asn1EncodableVector();
     v2.Add(OcspObjectIdentifiers.PkixOcspBasic);
     v2.Add(doctet);
     DerEnumerated den = new DerEnumerated(0);
     Asn1EncodableVector v3 = new Asn1EncodableVector();
     v3.Add(den);
     v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2)));            
     DerSequence seq = new DerSequence(v3);
     return seq.GetEncoded();
 }
Beispiel #12
0
		public byte[] GetSignature()
        {
            MPInteger[] sigValues = sigPck.GetSignature();
            byte[] signature;

			if (sigValues != null)
			{
				if (sigValues.Length == 1)    // an RSA signature
				{
					signature = sigValues[0].Value.ToByteArrayUnsigned();
				}
				else
				{
					try
					{
						signature = new DerSequence(
							new DerInteger(sigValues[0].Value),
							new DerInteger(sigValues[1].Value)).GetEncoded();
					}
					catch (IOException e)
					{
						throw new PgpException("exception encoding DSA sig.", e);
					}
				}
			}
			else
			{
				signature = sigPck.GetSignatureBytes();
			}

			return signature;
        }
        private Asn1Object CreateDERForRecipient(byte[] inp, X509Certificate cert) {
            
            String s = "1.2.840.113549.3.2";
            
            byte[] outp = new byte[100];
            DerObjectIdentifier derob = new DerObjectIdentifier(s);
            byte[] keyp = IVGenerator.GetIV(16);
            IBufferedCipher cf = CipherUtilities.GetCipher(derob);
            KeyParameter kp = new KeyParameter(keyp);
            byte[] iv = IVGenerator.GetIV(cf.GetBlockSize());
            ParametersWithIV piv = new ParametersWithIV(kp, iv);
            cf.Init(true, piv);
            int len = cf.DoFinal(inp, outp, 0);

            byte[] abyte1 = new byte[len];
            System.Array.Copy(outp, 0, abyte1, 0, len);
            DerOctetString deroctetstring = new DerOctetString(abyte1);
            KeyTransRecipientInfo keytransrecipientinfo = ComputeRecipientInfo(cert, keyp);
            DerSet derset = new DerSet(new RecipientInfo(keytransrecipientinfo));
            Asn1EncodableVector ev = new Asn1EncodableVector();
            ev.Add(new DerInteger(58));
            ev.Add(new DerOctetString(iv));
            DerSequence seq = new DerSequence(ev);
            AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(derob, seq);
            EncryptedContentInfo encryptedcontentinfo = 
                new EncryptedContentInfo(PkcsObjectIdentifiers.Data, algorithmidentifier, deroctetstring);
            Asn1Set set = null;
            EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set);
            Org.BouncyCastle.Asn1.Cms.ContentInfo contentinfo = 
                new Org.BouncyCastle.Asn1.Cms.ContentInfo(PkcsObjectIdentifiers.EnvelopedData, env);
            return contentinfo.ToAsn1Object();        
        }
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            byte[] keyBytes = contentEncryptionKey.GetKey();

            IAsymmetricKeyParameter senderPublicKey = senderKeyPair.Public;
            ICipherParameters senderPrivateParams = senderKeyPair.Private;

            OriginatorIdentifierOrKey originator;
            try
            {
                originator = new OriginatorIdentifierOrKey(
                    CreateOriginatorPublicKey(senderPublicKey));
            }
            catch (IOException e)
            {
                throw new InvalidKeyException("cannot extract originator public key: " + e);
            }

            Asn1OctetString ukm = null;
            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                try
                {
                    IAsymmetricCipherKeyPairGenerator ephemKPG =
                        GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                    ephemKPG.Init(
                        ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random));

                    IAsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair();

                    ukm = new DerOctetString(
                        new MQVuserKeyingMaterial(
                            CreateOriginatorPublicKey(ephemKP.Public), null));

                    senderPrivateParams = new MqvPrivateParameters(
                        (ECPrivateKeyParameters)senderPrivateParams,
                        (ECPrivateKeyParameters)ephemKP.Private,
                        (ECPublicKeyParameters)ephemKP.Public);
                }
                catch (IOException e)
                {
                    throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e);
                }
                catch (SecurityUtilityException e)
                {
                    throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e);
                }
            }

            DerSequence paramSeq = new DerSequence(
                keyEncryptionOID,
                DerNull.Instance);
            AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq);

            Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector();
            foreach (X509Certificate recipientCert in recipientCerts)
            {
                TbsCertificateStructure tbsCert;
                try
                {
                    tbsCert = TbsCertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(recipientCert.GetTbsCertificate()));
                }
                catch (Exception)
                {
                    throw new ArgumentException("can't extract TBS structure from certificate");
                }

                // TODO Should there be a SubjectKeyIdentifier-based alternative?
                IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(
                    tbsCert.Issuer, tbsCert.SerialNumber.Value);
                KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial);

                ICipherParameters recipientPublicParams = recipientCert.GetPublicKey();
                if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
                {
                    recipientPublicParams = new MqvPublicParameters(
                        (ECPublicKeyParameters)recipientPublicParams,
                        (ECPublicKeyParameters)recipientPublicParams);
                }

                // Use key agreement to choose a wrap key for this recipient
                IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    keyAgreementOID, keyEncryptionOID.Id);
                keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random));
                IBigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams);

                int keyEncryptionKeySize = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
                byte[] keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize);
                KeyParameter keyEncryptionKey = ParameterUtilities.CreateKeyParameter(
                    keyEncryptionOID, keyEncryptionKeyBytes);

                // Wrap the content encryption key with the agreement key
                IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id);
                keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random));
                byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);

                Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes);

                recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey));
            }

            return new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg,
                new DerSequence(recipientEncryptedKeys)));
        }
        /// <summary>
        /// Add the "Subject Alternative Names" extension. Note that you have to repeat
        /// the value from the "Subject Name" property.
        /// </summary>
        /// <param name="certificateGenerator"></param>
        /// <param name="subjectAlternativeNames"></param>
        private static void AddSubjectAlternativeNames(X509V3CertificateGenerator certificateGenerator,
                                                       IEnumerable<string> subjectAlternativeNames)
        {
            var subjectAlternativeNamesExtension =
                new DerSequence(
                    subjectAlternativeNames.Select(name => new GeneralName(GeneralName.DnsName, name))
                                           .ToArray<Asn1Encodable>());

            certificateGenerator.AddExtension(
                X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
        }
Beispiel #16
0
        public static Asn1EncodableVector GenerateSignerInfo(X509Certificate2 cert,
            String digestAlgorithmName,
            byte[] datos,
            AdESPolicy policy,
            bool signingCertificateV2,
            byte[] messageDigest,
            DateTime signDate,
            bool padesMode,
            String contentType,
            String contentDescription)
        {
            // ALGORITMO DE HUELLA DIGITAL
            AlgorithmIdentifier digestAlgorithmOID = SigUtils.MakeAlgId(AOAlgorithmID.GetOID(digestAlgorithmName));

            // // ATRIBUTOS

            // authenticatedAttributes
            Asn1EncodableVector contexExpecific = InitContexExpecific(
                   digestAlgorithmName,
                   datos,
                   Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Data.Id,
                   messageDigest,
                   signDate,
                   padesMode
               );

            // Serial Number
            // comentar lo de abajo para version del rfc 3852

            if (signingCertificateV2)
            {
                // INICIO SINGING CERTIFICATE-V2

                /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
                 * CertificateSerialNumber */

                TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
                    Asn1Object.FromByteArray(
                    new Org.BouncyCastle.X509.X509Certificate(
                        X509CertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(
                        cert.GetRawCertData()))).GetTbsCertificate()));

                GeneralNames gns = new GeneralNames(new GeneralName(tbs.Issuer));

                IssuerSerial isuerSerial = new IssuerSerial(gns, tbs.SerialNumber);

                /** ESSCertIDv2 ::= SEQUENCE { hashAlgorithm AlgorithmIdentifier
                 * DEFAULT {algorithm id-sha256}, certHash Hash, issuerSerial
                 * IssuerSerial OPTIONAL }
                 * Hash ::= OCTET STRING */

                byte[] certHash = Digester.Digest(cert.GetRawCertData(), digestAlgorithmName);
                EssCertIDv2[] essCertIDv2 = { new EssCertIDv2(digestAlgorithmOID, certHash, isuerSerial) };

                /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
                 * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
                 * OPTIONAL }
                 * CertPolicyId ::= OBJECT IDENTIFIER
                 * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
                 * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

                SigningCertificateV2 scv2;
                if (policy.GetPolicyIdentifier() != null)
                {

                    /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF
                     * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL
                     * } */
                    scv2 = new SigningCertificateV2(essCertIDv2, GetPolicyInformation(policy)); // con politica
                }
                else
                {
                    scv2 = new SigningCertificateV2(essCertIDv2); // Sin politica
                }

                // Secuencia con singningCertificate
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2)));

                // FIN SINGING CERTIFICATE-V2

            }
            else
            {
                // INICIO SINGNING CERTIFICATE

                /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
                 * CertificateSerialNumber } */

                TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
                    Asn1Object.FromByteArray(
                    new Org.BouncyCastle.X509.X509Certificate(
                        X509CertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(
                        cert.GetRawCertData()))).GetTbsCertificate()));

                GeneralName gn = new GeneralName(tbs.Issuer);
                GeneralNames gns = new GeneralNames(gn);

                IssuerSerial isuerSerial = new IssuerSerial(gns, tbs.SerialNumber);

                /** ESSCertID ::= SEQUENCE { certHash Hash, issuerSerial IssuerSerial
                 * OPTIONAL }
                 * Hash ::= OCTET STRING -- SHA1 hash of entire certificate */
                byte[] certHash = Digester.Digest(cert.GetRawCertData(), digestAlgorithmName);

                EssCertID essCertID = new EssCertID(certHash, isuerSerial);

                /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
                 * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
                 * OPTIONAL }
                 * CertPolicyId ::= OBJECT IDENTIFIER
                 * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
                 * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

                SigningCertificate scv;
                if (policy.GetPolicyIdentifier() != null)
                {

                    /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF
                     * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL
                     * } */
                    /*
                     * HAY QUE HACER UN SEQUENCE, YA QUE EL CONSTRUCTOR DE BOUNCY
                     * CASTLE NO TIENE DICHO CONSTRUCTOR.
                     */
                    Asn1EncodableVector v = new Asn1EncodableVector();
                    v.Add(new DerSequence(essCertID));
                    v.Add(new DerSequence(GetPolicyInformation(policy)));
                    scv = SigningCertificate.GetInstance(new DerSequence(v)); // con politica
                }
                else
                {
                    scv = new SigningCertificate(essCertID); // Sin politica
                }

                /** id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1)
                 * member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) smime(16)
                 * id-aa(2) 12 } */
                // Secuencia con singningCertificate
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(scv)));
            }

            // INICIO SIGPOLICYID ATTRIBUTE

            if (policy.GetPolicyIdentifier() != null)
            {
                /**
                 * SigPolicyId ::= OBJECT IDENTIFIER Politica de firma.
                 */
                DerObjectIdentifier doiSigPolicyId = new DerObjectIdentifier(policy.GetPolicyIdentifier().ToLower().Replace("urn:oid:", ""));

                /**
                 *   OtherHashAlgAndValue ::= SEQUENCE {
                 *     hashAlgorithm    AlgorithmIdentifier,
                 *     hashValue        OCTET STRING }
                 *
                 */

                // Algoritmo para el hash
                AlgorithmIdentifier hashid;
                // si tenemos algoritmo de calculo de hash, lo ponemos
                if (policy.GetPolicyIdentifierHashAlgorithm() != null)
                {
                    hashid = SigUtils.MakeAlgId(
                                        AOAlgorithmID.GetOID(
                                        AOSignConstants.GetDigestAlgorithmName(
                                           policy.GetPolicyIdentifierHashAlgorithm())));
                }
                // si no tenemos, ponemos el algoritmo de firma.
                else
                {
                    hashid = digestAlgorithmOID;
                }
                // hash del documento, descifrado en b64
                byte[] hashed;
                if (policy.GetPolicyIdentifierHash() != null)
                {
                    hashed = System.Convert.FromBase64String(policy.GetPolicyIdentifierHash());
                }
                else
                {
                    hashed = new byte[] { 0 };
                }

                DigestInfo otherHashAlgAndValue = new DigestInfo(hashid, hashed);

                /**
                 *   SigPolicyQualifierInfo ::= SEQUENCE {
                 *       SigPolicyQualifierId  SigPolicyQualifierId,
                 *       SigQualifier          ANY DEFINED BY policyQualifierId }
                 */

                AOSigPolicyQualifierInfo spqInfo = null;
                if (policy.GetPolicyQualifier() != null)
                {
                    spqInfo = new AOSigPolicyQualifierInfo(policy.GetPolicyQualifier().ToString());
                }

                /**
                 * SignaturePolicyId ::= SEQUENCE {
                 *  sigPolicyId           SigPolicyId,
                 *  sigPolicyHash         SigPolicyHash,
                 *  sigPolicyQualifiers   SEQUENCE SIZE (1..MAX) OF
                 *                          AOSigPolicyQualifierInfo OPTIONAL}
                 *
                 */
                Asn1EncodableVector v = new Asn1EncodableVector();
                // sigPolicyId
                v.Add(doiSigPolicyId);
                // sigPolicyHash
                v.Add(otherHashAlgAndValue.ToAsn1Object()); // como sequence
                // sigPolicyQualifiers
                if (spqInfo != null)
                {
                    v.Add(spqInfo.toASN1Primitive());
                }

                DerSequence ds = new DerSequence(v);

                // Secuencia con singningCertificate
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAAEtsSigPolicyID, new DerSet(ds.ToAsn1Object())));
                // FIN SIGPOLICYID ATTRIBUTE
            }

            /**
             * Secuencia con el tipo de contenido firmado. No se agrega en firmas PAdES.
             *
             * ContentHints ::= SEQUENCE {
             *	  contentDescription UTF8String (SIZE (1..MAX)) OPTIONAL,
             *	  contentType ContentType }
             */
            if (contentType != null && !padesMode)
            {
                ContentHints contentHints;
                if (contentDescription != null)
                {
                    contentHints = new ContentHints(new DerObjectIdentifier(contentType),
                                                    new DerUtf8String(contentDescription));
                }
                else
                {
                    contentHints = new ContentHints(new DerObjectIdentifier(contentType));
                }
                contexExpecific.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(
                        Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAAContentHint,
                        new DerSet(contentHints.ToAsn1Object())));
            }

            return contexExpecific;
        }
Beispiel #17
0
    public void TestAnswerSSH2_AGENTC_SIGN_REQUEST()
    {
      const string signatureData = "this is the data that gets signed";
      byte[] signatureDataBytes = Encoding.UTF8.GetBytes(signatureData);
      BlobBuilder builder = new BlobBuilder();

      Agent agent = new TestAgent(allKeys);
      Agent.BlobHeader header;
      byte[] signatureBlob;
      BlobParser signatureParser;
      string algorithm;
      byte[] signature;
      ISigner signer;
      bool signatureOk;
      BigInteger r, s;
      DerSequence seq;

      /* test signatures */

      foreach (ISshKey key in allKeys.Where(key => key.Version == SshVersion.SSH2)) {
        builder.Clear();
        builder.AddBlob(key.GetPublicKeyBlob());
        builder.AddStringBlob(signatureData);
        builder.InsertHeader(Agent.Message.SSH2_AGENTC_SIGN_REQUEST);
        PrepareMessage(builder);
        agent.AnswerMessage(stream);
        RewindStream();

        /* check that proper response type was received */
        header = parser.ReadHeader();
        Assert.That(header.Message,
                    Is.EqualTo(Agent.Message.SSH2_AGENT_SIGN_RESPONSE));
        signatureBlob = parser.ReadBlob();
        signatureParser = new BlobParser(signatureBlob);
        algorithm = signatureParser.ReadString();
        Assert.That(algorithm, Is.EqualTo(key.Algorithm.GetIdentifierString()));
        signature = signatureParser.ReadBlob();
        if (key.Algorithm == PublicKeyAlgorithm.SSH_RSA) {
          Assert.That(signature.Length == key.Size / 8);
        } else if (key.Algorithm == PublicKeyAlgorithm.SSH_DSS) {
          Assert.That(signature.Length, Is.EqualTo(40));
          r = new BigInteger(1, signature, 0, 20);
          s = new BigInteger(1, signature, 20, 20);
          seq = new DerSequence(new DerInteger(r), new DerInteger(s));
          signature = seq.GetDerEncoded();
        } else if (key.Algorithm == PublicKeyAlgorithm.ECDSA_SHA2_NISTP256 ||
          key.Algorithm == PublicKeyAlgorithm.ECDSA_SHA2_NISTP384 ||
          key.Algorithm == PublicKeyAlgorithm.ECDSA_SHA2_NISTP521) {
          Assert.That(signature.Length, Is.AtLeast(key.Size / 4 + 8));
          Assert.That(signature.Length, Is.AtMost(key.Size / 4 + 10));
          BlobParser sigParser = new BlobParser(signature);
          r = new BigInteger(sigParser.ReadBlob());
          s = new BigInteger(sigParser.ReadBlob());
          seq = new DerSequence(new DerInteger(r), new DerInteger(s));
          signature = seq.GetDerEncoded();
        } else if (key.Algorithm == PublicKeyAlgorithm.ED25519) {
            Assert.That(signature.Length, Is.EqualTo(64));
        }
        signer = key.GetSigner();
        signer.Init(false, key.GetPublicKeyParameters());
        signer.BlockUpdate(signatureDataBytes, 0, signatureDataBytes.Length);
        signatureOk = signer.VerifySignature(signature);
        Assert.That(signatureOk, Is.True, "invalid signature");
        Assert.That(header.BlobLength, Is.EqualTo(stream.Position - 4));
      }

      /* test DSA key old signature format */

      builder.Clear();
      builder.AddBlob(dsaKey.GetPublicKeyBlob());
      builder.AddStringBlob(signatureData);
      builder.AddInt((uint)Agent.SignRequestFlags.SSH_AGENT_OLD_SIGNATURE);
      builder.InsertHeader(Agent.Message.SSH2_AGENTC_SIGN_REQUEST);
      PrepareMessage(builder);
      agent.AnswerMessage(stream);
      RewindStream();
      header = parser.ReadHeader();
      Assert.That(header.Message,
                  Is.EqualTo(Agent.Message.SSH2_AGENT_SIGN_RESPONSE));
      signatureBlob = parser.ReadBlob();
      signatureParser = new BlobParser(signatureBlob);
      signature = signatureParser.ReadBlob();
      Assert.That(signature.Length == 40);
      r = new BigInteger(1, signature, 0, 20);
      s = new BigInteger(1, signature, 20, 20);
      seq = new DerSequence(new DerInteger(r), new DerInteger(s));
      signature = seq.GetDerEncoded();
      signer = dsaKey.GetSigner();
      signer.Init(false, dsaKey.GetPublicKeyParameters());
      signer.BlockUpdate(signatureDataBytes, 0, signatureDataBytes.Length);
      signatureOk = signer.VerifySignature(signature);
      Assert.That(signatureOk, Is.True, "invalid signature");
      Assert.That(header.BlobLength, Is.EqualTo(stream.Position - 4));

      /* test key not found */

      agent = new TestAgent();
      builder.Clear();
      builder.AddBlob(dsaKey.GetPublicKeyBlob());
      builder.AddStringBlob(signatureData);
      builder.InsertHeader(Agent.Message.SSH2_AGENTC_SIGN_REQUEST);
      PrepareMessage(builder);
      agent.AnswerMessage(stream);
      RewindStream();
      Agent.BlobHeader header2 = parser.ReadHeader();
      Assert.That(header2.BlobLength, Is.EqualTo(1));
      Assert.That(header2.Message, Is.EqualTo(Agent.Message.SSH_AGENT_FAILURE));

      /* test confirm constraint */

      agent = new TestAgent();
      Agent.KeyConstraint testConstraint = new Agent.KeyConstraint();
      testConstraint.Type = Agent.KeyConstraintType.SSH_AGENT_CONSTRAIN_CONFIRM;
      SshKey testKey = dsaKey.Clone();
      bool confirmCallbackReturnValue = false;
      agent.ConfirmUserPermissionCallback = delegate(ISshKey k, Process p)
      {
        return confirmCallbackReturnValue;
      };
      testKey.AddConstraint(testConstraint);
      agent.AddKey(testKey);
      builder.Clear();
      builder.AddBlob(dsaKey.GetPublicKeyBlob());
      builder.AddStringBlob(signatureData);
      builder.InsertHeader(Agent.Message.SSH2_AGENTC_SIGN_REQUEST);
      PrepareMessage(builder);
      agent.AnswerMessage(stream);
      RewindStream();
      header2 = parser.ReadHeader();
      Assert.That(header2.BlobLength, Is.EqualTo(1));
      Assert.That(header2.Message, Is.EqualTo(Agent.Message.SSH_AGENT_FAILURE));
      confirmCallbackReturnValue = true;
      PrepareMessage(builder);
      agent.AnswerMessage(stream);
      RewindStream();
      header2 = parser.ReadHeader();
      Assert.That(header2.BlobLength, Is.Not.EqualTo(1));
      Assert.That(header2.Message, Is.EqualTo(Agent.Message.SSH2_AGENT_SIGN_RESPONSE));
    }
Beispiel #18
0
        public void Save(
        	Stream			stream,
        	char[]			password,
        	SecureRandom	random)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (password == null)
                throw new ArgumentNullException("password");
            if (random == null)
                throw new ArgumentNullException("random");

            ContentInfo[] c = new ContentInfo[2];

            //
            // handle the key
            //
            Asn1EncodableVector keyS = new Asn1EncodableVector();
            foreach (string name in keys.Keys)
            {
                byte[] kSalt = new byte[saltSize];
                random.NextBytes(kSalt);

                AsymmetricKeyEntry privKey = (AsymmetricKeyEntry) keys[name];
                EncryptedPrivateKeyInfo kInfo =
                    EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                        keyAlgorithm, password, kSalt, minIterations, privKey.Key);

                Asn1EncodableVector kName = new Asn1EncodableVector();

                foreach (string oid in privKey.BagAttributeKeys)
                {
                    kName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(privKey[oid])));
                }

                //
                // make sure we have a local key-id
                //
                if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    X509CertificateEntry ct = GetCertificate(name);

                    SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
                        ct.Certificate.GetPublicKey());

                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(new SubjectKeyIdentifier(info))));
                }

                //
                // make sure we are using the local alias on store
                //
                DerBmpString nm = (DerBmpString) privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];
                if (nm == null || !nm.GetString().Equals(name))
                {
                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                SafeBag kBag = new SafeBag(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag, kInfo.ToAsn1Object(), new DerSet(kName));
                keyS.Add(kBag);
            }

            byte[] derEncodedBytes = new DerSequence(keyS).GetDerEncoded();

            BerOctetString keyString = new BerOctetString(derEncodedBytes);

            //
            // certificate processing
            //
            byte[] cSalt = new byte[saltSize];

            random.NextBytes(cSalt);

            Asn1EncodableVector	certSeq = new Asn1EncodableVector();
            Pkcs12PbeParams		cParams = new Pkcs12PbeParams(cSalt, minIterations);
            AlgorithmIdentifier	cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object());
            Hashtable			doneCerts = new Hashtable();

            foreach (string name in keys.Keys)
            {
                X509CertificateEntry certEntry = GetCertificate(name);
                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509CertType,
                    new DerOctetString(certEntry.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in certEntry.BagAttributeKeys)
                {
                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(certEntry[oid])));
                }

                //
                // make sure we are using the local alias on store
                //
                DerBmpString nm = (DerBmpString)certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];
                if (nm == null || !nm.GetString().Equals(name))
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
                        certEntry.Certificate.GetPublicKey());

                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(new SubjectKeyIdentifier(info))));
                }

                SafeBag sBag = new SafeBag(
                    PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);

                doneCerts.Add(certEntry.Certificate, certEntry.Certificate);
            }

            foreach (string certId in certs.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)certs[certId];

                if (keys[certId] != null)
                {
                    continue;
                }

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509CertType,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(cert[oid])));
                }

                //
                // make sure we are using the local alias on store
                //
                DerBmpString nm = (DerBmpString) cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName];
                if (nm == null || !nm.GetString().Equals(certId))
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(certId))));
                }

                SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag,
                    cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);

                doneCerts.Add(cert, cert);
            }

            foreach (CertId certId in chainCerts.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId];

                if (doneCerts[cert] != null)
                {
                    continue;
                }

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509CertType,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    fName.Add(new DerSequence(new DerObjectIdentifier(oid), new DerSet(cert[oid])));
                }

                SafeBag sBag = new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName));

                certSeq.Add(sBag);
            }

            derEncodedBytes = new DerSequence(certSeq).GetDerEncoded();

            byte[] certBytes = EncryptData(new AlgorithmIdentifier(certAlgorithm, cParams), derEncodedBytes, password);
            EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes));

            c[0] = new ContentInfo(PkcsObjectIdentifiers.Data, keyString);
            c[1] = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object());

            AuthenticatedSafe auth = new AuthenticatedSafe(c);

            byte[] pkg = auth.GetEncoded();

            ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(pkg));

            //
            // create the mac
            //
            byte[] mSalt = new byte[20];
            int itCount = minIterations;

            random.NextBytes(mSalt);

            byte[] data = ((Asn1OctetString)mainInfo.Content).GetOctets();

            Asn1Encodable parameters = PbeUtilities.GenerateAlgorithmParameters(OiwObjectIdentifiers.IdSha1, mSalt, itCount);
            ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters(
                OiwObjectIdentifiers.IdSha1, password, parameters);
            IMac mac = (IMac)PbeUtilities.CreateEngine(OiwObjectIdentifiers.IdSha1);

            mac.Init(keyParameters);

            mac.BlockUpdate(data, 0, data.Length);

            byte[] res = new byte[mac.GetMacSize()];

            mac.DoFinal(res, 0);

            AlgorithmIdentifier algId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance);
            DigestInfo dInfo = new DigestInfo(algId, res);

            MacData mData = new MacData(dInfo, mSalt, itCount);

            //
            // output the Pfx
            //
            Pfx pfx = new Pfx(mainInfo, mData);

            BerOutputStream berOut = new BerOutputStream(stream);

            berOut.WriteObject(pfx);
        }
        public Asn1Object ToAsn1Object()
        {
            if (_indefiniteLength)
            {
                Asn1EncodableVector v = rLoadVector(_contentStream);

                return(v.Count == 1
                                        ?       new BerTaggedObject(true, _tagNumber, v[0])
                                        :       new BerTaggedObject(false, _tagNumber, BerSequence.FromVector(v)));
            }

            if (IsConstructed)
            {
                Asn1EncodableVector v = rLoadVector(_contentStream);

                return(v.Count == 1
                                        ?       new DerTaggedObject(true, _tagNumber, v[0])
                                        :       new DerTaggedObject(false, _tagNumber, DerSequence.FromVector(v)));
            }

            try
            {
                DefiniteLengthInputStream defIn = (DefiniteLengthInputStream)_contentStream;
                return(new DerTaggedObject(false, _tagNumber, new DerOctetString(defIn.ToArray())));
            }
            catch (IOException e)
            {
                throw new InvalidOperationException(e.Message, e);
            }
        }
Beispiel #20
0
        public byte[] GetSignature()
        {
            MPInteger[] sigValues = sigPck.GetSignature();
            byte[] signature;
            if (sigValues.Length == 1)    // an RSA signature
            {
                byte[] sBytes = sigValues[0].Value.ToByteArray();

                if (sBytes[0] == 0)
                {
                    signature = new byte[sBytes.Length - 1];
                    Array.Copy(sBytes, 1, signature, 0, signature.Length);
                }
                else
                {
                    signature = sBytes;
                }
            }
            else
            {
                try
                {
                    signature = new DerSequence(
                        new DerInteger(sigValues[0].Value),
                        new DerInteger(sigValues[1].Value)).GetEncoded();
                }
                catch (IOException e)
                {
                    throw new PgpException("exception encoding DSA sig.", e);
                }
            }

            return signature;
        }
Beispiel #21
0
        /**
        * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
        * in the signerInfo can also be set. If either of the parameters is <CODE>null</CODE>, none will be used.
        * @param secondDigest the digest in the authenticatedAttributes
        * @param signingTime the signing time in the authenticatedAttributes
        * @return the bytes for the PKCS7SignedData object
        */
        public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime)
        {
            if (externalDigest != null) {
                digest = externalDigest;
                if (RSAdata != null)
                    RSAdata = externalRSAdata;
            }
            else if (externalRSAdata != null && RSAdata != null) {
                RSAdata = externalRSAdata;
                sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                digest = sig.GenerateSignature();
            }
            else {
                if (RSAdata != null) {
                    RSAdata = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(RSAdata, 0);
                    sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                }
                digest = sig.GenerateSignature();
            }

            // Create the set of Hash algorithms
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();
            foreach (string dal in digestalgos.Keys) {
                Asn1EncodableVector algos = new Asn1EncodableVector();
                algos.Add(new DerObjectIdentifier(dal));
                algos.Add(DerNull.Instance);
                digestAlgorithms.Add(new DerSequence(algos));
            }

            // Create the contentInfo.
            Asn1EncodableVector v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(ID_PKCS7_DATA));
            if (RSAdata != null)
                v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata)));
            DerSequence contentinfo = new DerSequence(v);

            // Get all the certificates
            //
            v = new Asn1EncodableVector();
            foreach (X509Certificate xcert in certs) {
                Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded()));
                v.Add(tempstream.ReadObject());
            }

            DerSet dercertificates = new DerSet(v);

            // Create signerinfo structure.
            //
            Asn1EncodableVector signerinfo = new Asn1EncodableVector();

            // Add the signerInfo version
            //
            signerinfo.Add(new DerInteger(signerversion));

            v = new Asn1EncodableVector();
            v.Add(GetIssuer(signCert.GetTbsCertificate()));
            v.Add(new DerInteger(signCert.SerialNumber));
            signerinfo.Add(new DerSequence(v));

            // Add the digestAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestAlgorithm));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // add the authenticated attribute if present
            if (secondDigest != null /*&& signingTime != null*/) {
                Asn1EncodableVector attribute = new Asn1EncodableVector();
                v = new Asn1EncodableVector();
                v.Add(new DerObjectIdentifier(ID_CONTENT_TYPE));
                v.Add(new DerSet(new DerObjectIdentifier(ID_PKCS7_DATA)));
                attribute.Add(new DerSequence(v));
                v = new Asn1EncodableVector();
                v.Add(new DerObjectIdentifier(ID_SIGNING_TIME));
                v.Add(new DerSet(new DerUtcTime(signingTime)));
                attribute.Add(new DerSequence(v));
                v = new Asn1EncodableVector();
                v.Add(new DerObjectIdentifier(ID_MESSAGE_DIGEST));
                v.Add(new DerSet(new DerOctetString(secondDigest)));
                attribute.Add(new DerSequence(v));
                signerinfo.Add(new DerTaggedObject(false, 0, new DerSet(attribute)));
            }
            // Add the digestEncryptionAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestEncryptionAlgorithm));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // Add the digest
            signerinfo.Add(new DerOctetString(digest));

            // Finally build the body out of all the components above
            Asn1EncodableVector body = new Asn1EncodableVector();
            body.Add(new DerInteger(version));
            body.Add(new DerSet(digestAlgorithms));
            body.Add(contentinfo);
            body.Add(new DerTaggedObject(false, 0, dercertificates));

            //                if (crls.Count > 0) {
            //                    v = new Asn1EncodableVector();
            //                    for (Iterator i = crls.Iterator();i.HasNext();) {
            //                        Asn1InputStream t = new Asn1InputStream(new ByteArrayInputStream((((X509CRL)i.Next()).GetEncoded())));
            //                        v.Add(t.ReadObject());
            //                    }
            //                    DERSet dercrls = new DERSet(v);
            //                    body.Add(new DERTaggedObject(false, 1, dercrls));
            //                }

            // Only allow one signerInfo
            body.Add(new DerSet(new DerSequence(signerinfo)));

            // Now we have the body, wrap it in it's PKCS7Signed shell
            // and return it
            //
            Asn1EncodableVector whole = new Asn1EncodableVector();
            whole.Add(new DerObjectIdentifier(ID_PKCS7_SIGNED_DATA));
            whole.Add(new DerTaggedObject(0, new DerSequence(body)));

            MemoryStream bOut = new MemoryStream();

            Asn1OutputStream dout = new Asn1OutputStream(bOut);
            dout.WriteObject(new DerSequence(whole));
            dout.Close();

            return bOut.ToArray();
        }
Beispiel #22
0
        public void TestSignRequest()
        {
            var agentClient = new TestAgentClient();
              var data = Encoding.UTF8.GetBytes("Data to be signed");

              foreach (var key in allKeys) {
            agentClient.Agent.AddKey(key);
            var signature = agentClient.SignRequest(key, data);
            switch (key.Version) {
              case SshVersion.SSH1:
            using (MD5 md5 = MD5.Create()) {
              var md5Buffer = new byte[48];
              data.CopyTo(md5Buffer, 0);
              agentClient.SessionId.CopyTo(md5Buffer, 32);
              var expctedSignature = md5.ComputeHash(md5Buffer);
              Assert.That(signature, Is.EqualTo(expctedSignature));
            }
            break;
              case SshVersion.SSH2:
            BlobParser signatureParser = new BlobParser(signature);
            var algorithm = signatureParser.ReadString();
            Assert.That(algorithm, Is.EqualTo(key.Algorithm.GetIdentifierString()));
            signature = signatureParser.ReadBlob();
            if (key.Algorithm == PublicKeyAlgorithm.SSH_RSA) {
              Assert.That(signature.Length == key.Size / 8);
            } else if (key.Algorithm == PublicKeyAlgorithm.SSH_DSS) {
              Assert.That(signature.Length, Is.EqualTo(40));
              var r = new BigInteger(1, signature, 0, 20);
              var s = new BigInteger(1, signature, 20, 20);
              var seq = new DerSequence(new DerInteger(r), new DerInteger(s));
              signature = seq.GetDerEncoded();
            } else if (key.Algorithm == PublicKeyAlgorithm.ECDSA_SHA2_NISTP256 ||
              key.Algorithm == PublicKeyAlgorithm.ECDSA_SHA2_NISTP384 ||
              key.Algorithm == PublicKeyAlgorithm.ECDSA_SHA2_NISTP521) {
              Assert.That(signature.Length, Is.AtLeast(key.Size / 4 + 8));
              Assert.That(signature.Length, Is.AtMost(key.Size / 4 + 10));
              BlobParser parser = new BlobParser(signature);
              var r = new BigInteger(parser.ReadBlob());
              var s = new BigInteger(parser.ReadBlob());
              var seq = new DerSequence(new DerInteger(r), new DerInteger(s));
              signature = seq.GetDerEncoded();
            }
            var signer = key.GetSigner();
            signer.Init(false, key.GetPublicKeyParameters());
            signer.BlockUpdate(data, 0, data.Length);
            var valid = signer.VerifySignature(signature);
            Assert.That(valid, Is.True);
            break;
              default:
            Assert.Fail("Unexpected Ssh Version");
            break;
            }
              }
        }
        /// <summary>
        /// Write myself to the given stream
        /// </summary>
        public void WriteTo(Stream stream, out string md5FingerPrint, out string sha1FingerPrint)
        {
            X509Certificate[] cert;
            AsymmetricKeyEntry privateKey;
            LoadPfx(out cert, out privateKey);

            var certsVector = new Asn1EncodableVector();
            md5FingerPrint = null;
            sha1FingerPrint = null;
            foreach (var c in cert)
            {
                var certStream = new MemoryStream(c.GetEncoded());
                var certStruct = X509CertificateStructure.GetInstance(new Asn1InputStream(certStream).ReadObject());
                certsVector.Add(certStruct);

                if (md5FingerPrint == null)
                {
                    var certData = certStream.ToArray();
                    md5FingerPrint = CreateFingerprint(new MD5Digest(), certData);
                }

                if (sha1FingerPrint == null)
                {
                    var certData = certStream.ToArray();
                    sha1FingerPrint = CreateFingerprint(new Sha1Digest(), certData);
                }
            }

            var encryptedSignature = GetSignature(signature, privateKey.Key);
            var signerInfo = new SignerInfo(
                new DerInteger(1),
                new IssuerAndSerialNumber(cert[0].IssuerDN, cert[0].SerialNumber),
                new AlgorithmIdentifier(Oids.SHA1, DerNull.Instance),
                null,
                new AlgorithmIdentifier(Oids.RSA, DerNull.Instance),
                new DerOctetString(encryptedSignature),
                null);

            var pkcs7 = new SignedData(
                new DerInteger(1),
                new DerSet(new AlgorithmIdentifier(Oids.SHA1, DerNull.Instance)),
                new ContentInfo(new DerObjectIdentifier(Oids.data), null),
                new DerSet(certsVector),
                null,
                new DerSet(signerInfo));

            //var signedData = new ContentInfo(new DERObjectIdentifier(Oids.signedData), pkcs7);

            var v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(Oids.signedData));
            v.Add(new DerTaggedObject(0, pkcs7));            
            var signedData = new DerSequence(v);

            // Save
            var data = signedData.GetEncoded();
            stream.Write(data, 0, data.Length);
        }
        public void Save(
            Stream			stream,
            char[]			password,
            SecureRandom	random)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (random == null)
                throw new ArgumentNullException("random");

            //
            // handle the keys
            //
            Asn1EncodableVector keyBags = new Asn1EncodableVector();
            foreach (string name in keys.Keys)
            {
                byte[] kSalt = new byte[SaltSize];
                random.NextBytes(kSalt);

                AsymmetricKeyEntry privKey = (AsymmetricKeyEntry)keys[name];

                DerObjectIdentifier bagOid;
                Asn1Encodable bagData;

                if (password == null)
                {
                    bagOid = PkcsObjectIdentifiers.KeyBag;
                    bagData = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey.Key);
                }
                else
                {
                    bagOid = PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag;
                    bagData = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                        keyAlgorithm, password, kSalt, MinIterations, privKey.Key);
                }

                Asn1EncodableVector kName = new Asn1EncodableVector();

                foreach (string oid in privKey.BagAttributeKeys)
                {
                    Asn1Encodable entry = privKey[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                        continue;

                    kName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'name'
                //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    X509CertificateEntry ct = GetCertificate(name);
                    AsymmetricKeyParameter pubKey = ct.Certificate.GetPublicKey();
                    SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey);

                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(subjectKeyID)));
                }

                keyBags.Add(new SafeBag(bagOid, bagData.ToAsn1Object(), new DerSet(kName)));
            }

            byte[] keyBagsEncoding = new DerSequence(keyBags).GetDerEncoded();
            ContentInfo keysInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(keyBagsEncoding));

            //
            // certificate processing
            //
            byte[] cSalt = new byte[SaltSize];

            random.NextBytes(cSalt);

            Asn1EncodableVector	certBags = new Asn1EncodableVector();
            Pkcs12PbeParams		cParams = new Pkcs12PbeParams(cSalt, MinIterations);
            AlgorithmIdentifier	cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object());
            ISet				doneCerts = new HashSet();

            foreach (string name in keys.Keys)
            {
                X509CertificateEntry certEntry = GetCertificate(name);
                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(certEntry.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in certEntry.BagAttributeKeys)
                {
                    Asn1Encodable entry = certEntry[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                        continue;

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'name'
                //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    AsymmetricKeyParameter pubKey = certEntry.Certificate.GetPublicKey();
                    SubjectKeyIdentifier subjectKeyID = CreateSubjectKeyID(pubKey);

                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(subjectKeyID)));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));

                doneCerts.Add(certEntry.Certificate);
            }

            foreach (string certId in certs.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)certs[certId];

                if (keys[certId] != null)
                    continue;

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    // a certificate not immediately linked to a key doesn't require
                    // a localKeyID and will confuse some PKCS12 implementations.
                    //
                    // If we find one, we'll prune it out.
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                        continue;

                    Asn1Encodable entry = cert[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                        continue;

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'certId'
                //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(certId))));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));

                doneCerts.Add(cert.Certificate);
            }

            foreach (CertId certId in chainCerts.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId];

                if (doneCerts.Contains(cert.Certificate))
                    continue;

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    // a certificate not immediately linked to a key doesn't require
                    // a localKeyID and will confuse some PKCS12 implementations.
                    //
                    // If we find one, we'll prune it out.
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                        continue;

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(cert[oid])));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));
            }

            byte[] certBagsEncoding = new DerSequence(certBags).GetDerEncoded();

            ContentInfo certsInfo;
            if (password == null)
            {
                certsInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(certBagsEncoding));
            }
            else
            {
                byte[] certBytes = CryptPbeData(true, cAlgId, password, false, certBagsEncoding);
                EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes));
                certsInfo = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object());
            }

            ContentInfo[] info = new ContentInfo[]{ keysInfo, certsInfo };

            byte[] data = new AuthenticatedSafe(info).GetEncoded(
                useDerEncoding ? Asn1Encodable.Der : Asn1Encodable.Ber);

            ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data));

            //
            // create the mac
            //
            MacData macData = null;
            if (password != null)
            {
                byte[] mSalt = new byte[20];
                random.NextBytes(mSalt);

                byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1,
                    mSalt, MinIterations, password, false, data);

                AlgorithmIdentifier algId = new AlgorithmIdentifier(
                    OiwObjectIdentifiers.IdSha1, DerNull.Instance);
                DigestInfo dInfo = new DigestInfo(algId, mac);

                macData = new MacData(dInfo, mSalt, MinIterations);
            }

            //
            // output the Pfx
            //
            Pfx pfx = new Pfx(mainInfo, macData);

            DerOutputStream derOut;
            if (useDerEncoding)
            {
                derOut = new DerOutputStream(stream);
            }
            else
            {
                derOut = new BerOutputStream(stream);
            }

            derOut.WriteObject(pfx);
        }
		private BasicOcspResp GenerateResponse(
			ISignatureCalculator    signatureCalculator,
			X509Certificate[]		chain,
			DateTime				producedAt)
		{
            AlgorithmIdentifier signingAlgID = (AlgorithmIdentifier)signatureCalculator.AlgorithmDetails;
            DerObjectIdentifier signingAlgorithm = signingAlgID.Algorithm;

			Asn1EncodableVector responses = new Asn1EncodableVector();

			foreach (ResponseObject respObj in list)
			{
				try
				{
					responses.Add(respObj.ToResponse());
				}
				catch (Exception e)
				{
					throw new OcspException("exception creating Request", e);
				}
			}

			ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions);
			DerBitString bitSig = null;

			try
			{
                IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator();

				byte[] encoded = tbsResp.GetDerEncoded();

                streamCalculator.Stream.Write(encoded, 0, encoded.Length);

                streamCalculator.Stream.Close();

                bitSig = new DerBitString(((IBlockResult)streamCalculator.GetResult()).DoFinal());
			}
			catch (Exception e)
			{
				throw new OcspException("exception processing TBSRequest: " + e, e);
			}

			AlgorithmIdentifier sigAlgId = OcspUtilities.GetSigAlgID(signingAlgorithm);

			DerSequence chainSeq = null;
			if (chain != null && chain.Length > 0)
			{
				Asn1EncodableVector v = new Asn1EncodableVector();
				try
				{
					for (int i = 0; i != chain.Length; i++)
					{
						v.Add(
							X509CertificateStructure.GetInstance(
								Asn1Object.FromByteArray(chain[i].GetEncoded())));
					}
				}
				catch (IOException e)
				{
					throw new OcspException("error processing certs", e);
				}
				catch (CertificateEncodingException e)
				{
					throw new OcspException("error encoding certs", e);
				}

				chainSeq = new DerSequence(v);
			}

			return new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, chainSeq));
		}
Beispiel #26
0
 internal virtual DerSequence CreateDerSequence(DefiniteLengthInputStream dIn) =>
 DerSequence.FromVector(this.BuildDerEncodableVector(dIn));
 internal virtual DerSequence CreateDerSequence(
     DefiniteLengthInputStream dIn)
 {
     return(DerSequence.FromVector(BuildDerEncodableVector(dIn)));
 }
Beispiel #28
0
		public static bool verifySign(string signature, byte[] origdata, ICipherParameters pubkey) {
			var dsa = SignerUtilities.GetSigner(ECDSA);
			dsa.Init (false, pubkey);
			dsa.BlockUpdate(origdata, 0, origdata.Length);

			BigInteger r = new BigInteger (signature.Substring (0, 64), 16);
			BigInteger s = new BigInteger (signature.Substring (64, 64), 16);
			Asn1EncodableVector vec = new Asn1EncodableVector ();
			vec.Add (new DerInteger (r));
			vec.Add (new DerInteger (s));
			Asn1Sequence seq = new DerSequence(vec);

			byte[] sign = seq.GetEncoded ();
			bool result = dsa.VerifySignature (sign);
			return result;
		}
Beispiel #29
0
 internal virtual DerSequence CreateDerSequence(
     DefiniteLengthInputStream dIn)
 {
     return(DerSequence.FromVector(ReadVector(dIn)));
 }
        public virtual int GenerateBytes(byte[]	outBytes, int outOff, int len)
        {
            if ((outBytes.Length - len) < outOff)
            {
                throw new DataLengthException("output buffer too small");
            }

            long oBytes = len;
            int outLen = digest.GetDigestSize();

            //
            // this is at odds with the standard implementation, the
            // maximum value should be hBits * (2^32 - 1) where hBits
            // is the digest output size in bits. We can't have an
            // array with a long index at the moment...
            //
            if (oBytes > ((2L << 32) - 1))
            {
                throw new ArgumentException("Output length too large");
            }

            int cThreshold = (int)((oBytes + outLen - 1) / outLen);

            byte[] dig = new byte[digest.GetDigestSize()];

            uint counter = 1;

            for (int i = 0; i < cThreshold; i++)
            {
                digest.BlockUpdate(z, 0, z.Length);

                // KeySpecificInfo
                DerSequence keyInfo = new DerSequence(
                    algorithm,
                    new DerOctetString(Pack.UInt32_To_BE(counter)));

                // OtherInfo
                Asn1EncodableVector v1 = new Asn1EncodableVector(keyInfo);

                if (partyAInfo != null)
                {
                    v1.Add(new DerTaggedObject(true, 0, new DerOctetString(partyAInfo)));
                }

                v1.Add(new DerTaggedObject(true, 2, new DerOctetString(Pack.UInt32_To_BE((uint)keySize))));

                byte[] other = new DerSequence(v1).GetDerEncoded();

                digest.BlockUpdate(other, 0, other.Length);

                digest.DoFinal(dig, 0);

                if (len > outLen)
                {
                    Array.Copy(dig, 0, outBytes, outOff, outLen);
                    outOff += outLen;
                    len -= outLen;
                }
                else
                {
                    Array.Copy(dig, 0, outBytes, outOff, len);
                }

                counter++;
            }

            digest.Reset();

            return (int)oBytes;
        }
		public override void PerformTest()
        {
            DerUtf8String countryName = new DerUtf8String("Australia");

            SignerLocation sl = new SignerLocation(countryName, null, null);

            CheckConstruction(sl, countryName, null, null);

            DerUtf8String localityName = new DerUtf8String("Melbourne");

            sl = new SignerLocation(null, localityName, null);

			CheckConstruction(sl, null, localityName, null);

			sl = new SignerLocation(countryName, localityName, null);

			CheckConstruction(sl, countryName, localityName, null);

			Asn1Sequence postalAddress = new DerSequence(
				new DerUtf8String("line 1"),
				new DerUtf8String("line 2"));

            sl = new SignerLocation(null, null, postalAddress);

            CheckConstruction(sl, null, null, postalAddress);

            sl = new SignerLocation(countryName, null, postalAddress);

            CheckConstruction(sl, countryName, null, postalAddress);

            sl = new SignerLocation(countryName, localityName, postalAddress);

            CheckConstruction(sl, countryName, localityName, postalAddress);

            sl = SignerLocation.GetInstance(null);

            if (sl != null)
            {
                Fail("null GetInstance() failed.");
            }

            try
            {
                SignerLocation.GetInstance(new object());

                Fail("GetInstance() failed to detect bad object.");
            }
            catch (ArgumentException)
            {
                // expected
            }

            //
            // out of range postal address
            //
			postalAddress = new DerSequence(
				new DerUtf8String("line 1"),
				new DerUtf8String("line 2"),
				new DerUtf8String("line 3"),
				new DerUtf8String("line 4"),
				new DerUtf8String("line 5"),
				new DerUtf8String("line 6"),
				new DerUtf8String("line 7"));

			try
            {
                new SignerLocation(null, null, postalAddress);

                Fail("constructor failed to detect bad postalAddress.");
            }
            catch (ArgumentException)
            {
                // expected
            }

            try
            {
                new SignerLocation(new DerSequence(new DerTaggedObject(2, postalAddress)));

                Fail("sequence constructor failed to detect bad postalAddress.");
            }
            catch (ArgumentException)
            {
                // expected
            }

            try
            {
                new SignerLocation(new DerSequence(new DerTaggedObject(5, postalAddress)));

                Fail("sequence constructor failed to detect bad tag.");
            }
            catch (ArgumentException)
            {
                // expected
            }
        }
Beispiel #32
0
        /**
        * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
        * in the signerInfo can also be set, OR a time-stamp-authority client
        * may be provided.
        * @param secondDigest the digest in the authenticatedAttributes
        * @param signingTime the signing time in the authenticatedAttributes
        * @param tsaClient TSAClient - null or an optional time stamp authority client
        * @return byte[] the bytes for the PKCS7SignedData object
        * @since   2.1.6
        */
        public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime, ITSAClient tsaClient, byte[] ocsp) {
            if (externalDigest != null) {
                digest = externalDigest;
                if (RSAdata != null)
                    RSAdata = externalRSAdata;
            }
            else if (externalRSAdata != null && RSAdata != null) {
                RSAdata = externalRSAdata;
                sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                digest = sig.GenerateSignature();
            }
            else {
                if (RSAdata != null) {
                    RSAdata = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(RSAdata, 0);
                    sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                }
                digest = sig.GenerateSignature();
            }
            
            // Create the set of Hash algorithms
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();
            foreach (string dal in digestalgos.Keys) {
                Asn1EncodableVector algos = new Asn1EncodableVector();
                algos.Add(new DerObjectIdentifier(dal));
                algos.Add(DerNull.Instance);
                digestAlgorithms.Add(new DerSequence(algos));
            }
            
            // Create the contentInfo.
            Asn1EncodableVector v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(ID_PKCS7_DATA));
            if (RSAdata != null)
                v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata)));
            DerSequence contentinfo = new DerSequence(v);
            
            // Get all the certificates
            //
            v = new Asn1EncodableVector();
            foreach (X509Certificate xcert in certs) {
                Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded()));
                v.Add(tempstream.ReadObject());
            }
            
            DerSet dercertificates = new DerSet(v);
            
            // Create signerinfo structure.
            //
            Asn1EncodableVector signerinfo = new Asn1EncodableVector();
            
            // Add the signerInfo version
            //
            signerinfo.Add(new DerInteger(signerversion));
            
            v = new Asn1EncodableVector();
            v.Add(GetIssuer(signCert.GetTbsCertificate()));
            v.Add(new DerInteger(signCert.SerialNumber));
            signerinfo.Add(new DerSequence(v));
            
            // Add the digestAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestAlgorithm));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));
            
            // add the authenticated attribute if present
            if (secondDigest != null /*&& signingTime != null*/) {
                signerinfo.Add(new DerTaggedObject(false, 0, GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp)));
            }
            // Add the digestEncryptionAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestEncryptionAlgorithm));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));
            
            // Add the digest
            signerinfo.Add(new DerOctetString(digest));
            
            // When requested, go get and add the timestamp. May throw an exception.
            // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
            // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
            if (tsaClient != null) {
                byte[] tsImprint = new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(digest);
                byte[] tsToken = tsaClient.GetTimeStampToken(this, tsImprint);
                if (tsToken != null) {
                    Asn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken);
                    if (unauthAttributes != null) {
                        signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes)));
                    }
                }
            }
            
            // Finally build the body out of all the components above
            Asn1EncodableVector body = new Asn1EncodableVector();
            body.Add(new DerInteger(version));
            body.Add(new DerSet(digestAlgorithms));
            body.Add(contentinfo);
            body.Add(new DerTaggedObject(false, 0, dercertificates));
            
//                if (crls.Count > 0) {
//                    v = new Asn1EncodableVector();
//                    for (Iterator i = crls.Iterator();i.HasNext();) {
//                        Asn1InputStream t = new Asn1InputStream(new ByteArrayInputStream((((X509CRL)i.Next()).GetEncoded())));
//                        v.Add(t.ReadObject());
//                    }
//                    DERSet dercrls = new DERSet(v);
//                    body.Add(new DERTaggedObject(false, 1, dercrls));
//                }
            
            // Only allow one signerInfo
            body.Add(new DerSet(new DerSequence(signerinfo)));
            
            // Now we have the body, wrap it in it's PKCS7Signed shell
            // and return it
            //
            Asn1EncodableVector whole = new Asn1EncodableVector();
            whole.Add(new DerObjectIdentifier(ID_PKCS7_SIGNED_DATA));
            whole.Add(new DerTaggedObject(0, new DerSequence(body)));
            
            MemoryStream bOut = new MemoryStream();
            
            Asn1OutputStream dout = new Asn1OutputStream(bOut);
            dout.WriteObject(new DerSequence(whole));
            dout.Close();
            
            return bOut.ToArray();
        }
		public override Asn1Object ToAsn1Object()
		{
			DerSequence hashSeq = new DerSequence(datagroupHash);

			Asn1EncodableVector v = new Asn1EncodableVector(version, digestAlgorithmIdentifier, hashSeq);

			if (versionInfo != null)
			{
				v.Add(versionInfo);
			}

			return new DerSequence(v);
		}
Beispiel #34
0
        private void doTestNullDerNullCert()
        {
            AsymmetricCipherKeyPair keyPair = GenerateLongFixedKeys();

            AsymmetricKeyParameter pubKey = keyPair.Public;
            AsymmetricKeyParameter privKey = keyPair.Private;

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name("CN=Test"));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name("CN=Test"));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("MD5WithRSAEncryption");
            X509Certificate cert = certGen.Generate(privKey);

            X509CertificateStructure certStruct = X509CertificateStructure.GetInstance(
                Asn1Object.FromByteArray(cert.GetEncoded()));

            Asn1Encodable tbsCertificate = certStruct.TbsCertificate;
            AlgorithmIdentifier sig = certStruct.SignatureAlgorithm;

            DerSequence seq = new DerSequence(
                tbsCertificate,
                new AlgorithmIdentifier(sig.Algorithm),
                certStruct.Signature);

            try
            {
                // verify
                byte[] encoded = seq.GetEncoded();
                X509CertificateParser fact = new X509CertificateParser();
                cert = fact.ReadCertificate(encoded);
                cert.Verify(cert.GetPublicKey());
            }
            catch (Exception e)
            {
                Fail("doTestNullDerNull failed - exception " + e.ToString(), e);
            }
        }
        private string GenerateX509Cert(string publicKey, string x509Subject)
        {
            Asn1Sequence asn1Sequence = null;

            using (var reader = new StringReader(publicKey))
            {
                // Read the RSA public key from the input string.
                var pemReader = new PemReader(reader);
                var pemObject = pemReader.ReadPemObject();
                asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(pemObject.Content);
            }

            // Generate a TBS certificate. We use placeholder-like values since
            // the consumer of this certificate should only use the subject
            // public key info.
            var tbsCertGen = new V3TbsCertificateGenerator();
            tbsCertGen.SetSerialNumber(new DerInteger(1));
            var signatureAlgId = new AlgorithmIdentifier(PkcsObjectIdentifiers.Sha1WithRsaEncryption, DerNull.Instance);
            tbsCertGen.SetSignature(signatureAlgId);
            tbsCertGen.SetIssuer(new X509Name("CN=Root Agency"));
            var dateTimeNow = DateTime.Now;
            tbsCertGen.SetStartDate(new Time(dateTimeNow.AddMinutes(-10)));
            tbsCertGen.SetEndDate(new Time(dateTimeNow.AddYears(1)));   // Openssh key doesn`t have any start/end date, this is to satisfy RDFE
            tbsCertGen.SetSubject(new X509Name(x509Subject));
            tbsCertGen.SetSubjectPublicKeyInfo(new SubjectPublicKeyInfo(new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance), asn1Sequence));
            var tbsCert = tbsCertGen.GenerateTbsCertificate();

            // Per RFC 3280, the layout of an X.509 v3 certificate looks like:
            // Certificate  ::=  SEQUENCE  {
            //     tbsCertificate       TBSCertificate,
            //     signatureAlgorithm   AlgorithmIdentifier,
            //     signatureValue       BIT STRING
            // }
            // Since we don't have access to the private key, we cannot create
            // a signature for the TBS. However, a valid certificate requires
            // a bit string for the signature value, so we use a 0-byte array
            // in its place.
            Asn1EncodableVector v = new Asn1EncodableVector();
            v.Add(tbsCert);
            v.Add(signatureAlgId);
            v.Add(new DerBitString(new byte[0]));
            var derSequence = new DerSequence(v);

            // Output the DER-encoded X509 certificate.
            var sb = new StringBuilder();
            using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture))
            {
                var pemWriter = new PemWriter(writer);
                pemWriter.WriteObject(new PemObject("CERTIFICATE", derSequence.GetEncoded()));
            }

            return sb.ToString();
        }