Esempio n. 1
0
 internal PublicKeyInfo(CAPI.CERT_PUBLIC_KEY_INFO keyInfo)
 {
     this.m_algorithm = new AlgorithmIdentifier(keyInfo);
     this.m_keyValue = new byte[(IntPtr)keyInfo.PublicKey.cbData];
     if (this.m_keyValue.Length <= 0)
         return;
     Marshal.Copy(keyInfo.PublicKey.pbData, this.m_keyValue, 0, this.m_keyValue.Length);
 }
Esempio n. 2
0
 public BiometricData(
     TypeOfBiometricData	typeOfBiometricData,
     AlgorithmIdentifier	hashAlgorithm,
     Asn1OctetString		biometricDataHash)
 {
     this.typeOfBiometricData = typeOfBiometricData;
     this.hashAlgorithm = hashAlgorithm;
     this.biometricDataHash = biometricDataHash;
     this.sourceDataUri = null;
 }
Esempio n. 3
0
		private BiometricData(
			Asn1Sequence seq)
        {
			typeOfBiometricData = TypeOfBiometricData.GetInstance(seq[0]);
			hashAlgorithm = AlgorithmIdentifier.GetInstance(seq[1]);
			biometricDataHash = Asn1OctetString.GetInstance(seq[2]);

			if (seq.Count > 3)
			{
				sourceDataUri = DerIA5String.GetInstance(seq[3]);
			}
        }
Esempio n. 4
0
		public void Test_SubjectPublicKeyInfo()
		{
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo();
			AlgorithmIdentifier ai = new AlgorithmIdentifier();
			ai.Assign(OID.RSA.sha1WithRSAEncryption);

			BERWriter.DumpHEX(ai);


			spki.Assign(ai, new ASN1BitString(new byte[]{0x1, 0x2}, 9));

			BERWriter.DumpHEX(spki);
			

		}
Esempio n. 5
0
 public EnvelopedCms(SubjectIdentifierType recipientIdentifierType, ContentInfo contentInfo, AlgorithmIdentifier encryptionAlgorithm)
 {
     if (contentInfo == null)
         throw new ArgumentNullException("contentInfo");
     if (contentInfo.Content == null)
         throw new ArgumentNullException("contentInfo.Content");
     if (encryptionAlgorithm == null)
         throw new ArgumentNullException("encryptionAlgorithm");
     this.m_safeCryptMsgHandle = SafeCryptMsgHandle.InvalidHandle;
     this.m_version = recipientIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier ? 2 : 0;
     this.m_recipientIdentifierType = recipientIdentifierType;
     this.m_contentInfo = contentInfo;
     this.m_encryptionAlgorithm = encryptionAlgorithm;
     this.m_encryptionAlgorithm.Parameters = new byte[0];
     this.m_certificates = new X509Certificate2Collection();
     this.m_unprotectedAttributes = new CryptographicAttributeObjectCollection();
 }
Esempio n. 6
0
 private static unsafe void SetCmsRecipientParams(CmsRecipientCollection recipients, X509Certificate2Collection certificates, CryptographicAttributeObjectCollection unprotectedAttributes, AlgorithmIdentifier contentEncryptionAlgorithm, ref EnvelopedCms.CMSG_ENCRYPT_PARAM encryptParam)
 {
     uint[] numArray = new uint[recipients.Count];
     int length = 0;
     int num1 = recipients.Count * Marshal.SizeOf(typeof(CAPI.CMSG_RECIPIENT_ENCODE_INFO));
     int num2 = num1;
     for (int index = 0; index < recipients.Count; ++index)
     {
         numArray[index] = (uint)PkcsUtils.GetRecipientInfoType(recipients[index].Certificate);
         if ((int)numArray[index] == 1)
         {
             num2 += Marshal.SizeOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO));
         }
         else
         {
             if ((int)numArray[index] != 2)
                 throw new CryptographicException(-2146889726);
             ++length;
             num2 += Marshal.SizeOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO));
         }
     }
     encryptParam.rgpRecipients = CAPI.LocalAlloc(64U, new IntPtr(num2));
     encryptParam.rgCertEncoded = SafeLocalAllocHandle.InvalidHandle;
     encryptParam.rgUnprotectedAttr = SafeLocalAllocHandle.InvalidHandle;
     encryptParam.rgSubjectKeyIdentifier = new SafeLocalAllocHandle[recipients.Count];
     encryptParam.rgszObjId = new SafeLocalAllocHandle[recipients.Count];
     if (length > 0)
     {
         encryptParam.rgszKeyWrapObjId = new SafeLocalAllocHandle[length];
         encryptParam.rgKeyWrapAuxInfo = new SafeLocalAllocHandle[length];
         encryptParam.rgEphemeralIdentifier = new SafeLocalAllocHandle[length];
         encryptParam.rgszEphemeralObjId = new SafeLocalAllocHandle[length];
         encryptParam.rgUserKeyingMaterial = new SafeLocalAllocHandle[length];
         encryptParam.prgpEncryptedKey = new SafeLocalAllocHandle[length];
         encryptParam.rgpEncryptedKey = new SafeLocalAllocHandle[length];
     }
     if (certificates.Count > 0)
     {
         encryptParam.rgCertEncoded = CAPI.LocalAlloc(64U, new IntPtr(certificates.Count * Marshal.SizeOf(typeof(CAPI.CRYPTOAPI_BLOB))));
         for (int index = 0; index < certificates.Count; ++index)
         {
             CAPI.CERT_CONTEXT certContext = (CAPI.CERT_CONTEXT)Marshal.PtrToStructure(X509Utils.GetCertContext(certificates[index]).DangerousGetHandle(), typeof(CAPI.CERT_CONTEXT));
             CAPI.CRYPTOAPI_BLOB* cryptoapiBlobPtr = (CAPI.CRYPTOAPI_BLOB*)(void*)new IntPtr((long)encryptParam.rgCertEncoded.DangerousGetHandle() + (long)(index * Marshal.SizeOf(typeof(CAPI.CRYPTOAPI_BLOB))));
             cryptoapiBlobPtr->cbData = certContext.cbCertEncoded;
             cryptoapiBlobPtr->pbData = certContext.pbCertEncoded;
         }
     }
     if (unprotectedAttributes.Count > 0)
         encryptParam.rgUnprotectedAttr = new SafeLocalAllocHandle(PkcsUtils.CreateCryptAttributes(unprotectedAttributes));
     int index1 = 0;
     IntPtr num3 = new IntPtr((long)encryptParam.rgpRecipients.DangerousGetHandle() + (long)num1);
     for (int index2 = 0; index2 < recipients.Count; ++index2)
     {
         CmsRecipient cmsRecipient = recipients[index2];
         X509Certificate2 certificate = cmsRecipient.Certificate;
         CAPI.CERT_INFO certInfo = (CAPI.CERT_INFO)Marshal.PtrToStructure(((CAPI.CERT_CONTEXT)Marshal.PtrToStructure(X509Utils.GetCertContext(certificate).DangerousGetHandle(), typeof(CAPI.CERT_CONTEXT))).pCertInfo, typeof(CAPI.CERT_INFO));
         CAPI.CMSG_RECIPIENT_ENCODE_INFO* recipientEncodeInfoPtr = (CAPI.CMSG_RECIPIENT_ENCODE_INFO*)(void*)new IntPtr((long)encryptParam.rgpRecipients.DangerousGetHandle() + (long)(index2 * Marshal.SizeOf(typeof(CAPI.CMSG_RECIPIENT_ENCODE_INFO))));
         recipientEncodeInfoPtr->dwRecipientChoice = numArray[index2];
         recipientEncodeInfoPtr->pRecipientInfo = num3;
         if ((int)numArray[index2] == 1)
         {
             Marshal.WriteInt32(new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO), "cbSize")), Marshal.SizeOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO)));
             IntPtr num4 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO), "KeyEncryptionAlgorithm"));
             byte[] bytes = Encoding.ASCII.GetBytes(certInfo.SubjectPublicKeyInfo.Algorithm.pszObjId);
             encryptParam.rgszObjId[index2] = CAPI.LocalAlloc(64U, new IntPtr(bytes.Length + 1));
             Marshal.Copy(bytes, 0, encryptParam.rgszObjId[index2].DangerousGetHandle(), bytes.Length);
             Marshal.WriteIntPtr(new IntPtr((long)num4 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "pszObjId")), encryptParam.rgszObjId[index2].DangerousGetHandle());
             IntPtr num5 = new IntPtr((long)num4 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "Parameters"));
             IntPtr ptr1 = new IntPtr((long)num5 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData"));
             Marshal.WriteInt32(ptr1, (int)certInfo.SubjectPublicKeyInfo.Algorithm.Parameters.cbData);
             IntPtr ptr2 = new IntPtr((long)num5 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData"));
             Marshal.WriteIntPtr(ptr2, certInfo.SubjectPublicKeyInfo.Algorithm.Parameters.pbData);
             IntPtr num6 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO), "RecipientPublicKey"));
             ptr1 = new IntPtr((long)num6 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "cbData"));
             Marshal.WriteInt32(ptr1, (int)certInfo.SubjectPublicKeyInfo.PublicKey.cbData);
             ptr2 = new IntPtr((long)num6 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "pbData"));
             Marshal.WriteIntPtr(ptr2, certInfo.SubjectPublicKeyInfo.PublicKey.pbData);
             Marshal.WriteInt32(new IntPtr((long)num6 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "cUnusedBits")), (int)certInfo.SubjectPublicKeyInfo.PublicKey.cUnusedBits);
             IntPtr num7 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO), "RecipientId"));
             if (cmsRecipient.RecipientIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier)
             {
                 uint pcbData = 0U;
                 SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle;
                 if (!CAPI.CAPISafe.CertGetCertificateContextProperty(X509Utils.GetCertContext(certificate), 20U, invalidHandle, out pcbData))
                     throw new CryptographicException(Marshal.GetLastWin32Error());
                 SafeLocalAllocHandle pvData = CAPI.LocalAlloc(64U, new IntPtr((long)pcbData));
                 if (!CAPI.CAPISafe.CertGetCertificateContextProperty(X509Utils.GetCertContext(certificate), 20U, pvData, out pcbData))
                     throw new CryptographicException(Marshal.GetLastWin32Error());
                 encryptParam.rgSubjectKeyIdentifier[index2] = pvData;
                 Marshal.WriteInt32(new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "dwIdChoice")), 2);
                 IntPtr num8 = new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "Value"));
                 ptr1 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData"));
                 Marshal.WriteInt32(ptr1, (int)pcbData);
                 ptr2 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData"));
                 Marshal.WriteIntPtr(ptr2, pvData.DangerousGetHandle());
             }
             else
             {
                 Marshal.WriteInt32(new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "dwIdChoice")), 1);
                 IntPtr num8 = new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "Value"));
                 IntPtr num9 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ISSUER_SERIAL_NUMBER), "Issuer"));
                 ptr1 = new IntPtr((long)num9 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData"));
                 Marshal.WriteInt32(ptr1, (int)certInfo.Issuer.cbData);
                 ptr2 = new IntPtr((long)num9 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData"));
                 Marshal.WriteIntPtr(ptr2, certInfo.Issuer.pbData);
                 IntPtr num10 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ISSUER_SERIAL_NUMBER), "SerialNumber"));
                 ptr1 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData"));
                 Marshal.WriteInt32(ptr1, (int)certInfo.SerialNumber.cbData);
                 ptr2 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData"));
                 Marshal.WriteIntPtr(ptr2, certInfo.SerialNumber.pbData);
             }
             num3 = new IntPtr((long)num3 + (long)Marshal.SizeOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO)));
         }
         else if ((int)numArray[index2] == 2)
         {
             IntPtr ptr1 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "cbSize"));
             Marshal.WriteInt32(ptr1, Marshal.SizeOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO)));
             IntPtr num4 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "KeyEncryptionAlgorithm"));
             byte[] bytes1 = Encoding.ASCII.GetBytes("1.2.840.113549.1.9.16.3.5");
             encryptParam.rgszObjId[index2] = CAPI.LocalAlloc(64U, new IntPtr(bytes1.Length + 1));
             Marshal.Copy(bytes1, 0, encryptParam.rgszObjId[index2].DangerousGetHandle(), bytes1.Length);
             IntPtr ptr2 = new IntPtr((long)num4 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "pszObjId"));
             Marshal.WriteIntPtr(ptr2, encryptParam.rgszObjId[index2].DangerousGetHandle());
             IntPtr num5 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "KeyWrapAlgorithm"));
             uint num6 = X509Utils.OidToAlgId(contentEncryptionAlgorithm.Oid.Value);
             byte[] source = (int)num6 != 26114 ? Encoding.ASCII.GetBytes("1.2.840.113549.1.9.16.3.6") : Encoding.ASCII.GetBytes("1.2.840.113549.1.9.16.3.7");
             encryptParam.rgszKeyWrapObjId[index1] = CAPI.LocalAlloc(64U, new IntPtr(source.Length + 1));
             Marshal.Copy(source, 0, encryptParam.rgszKeyWrapObjId[index1].DangerousGetHandle(), source.Length);
             ptr2 = new IntPtr((long)num5 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "pszObjId"));
             Marshal.WriteIntPtr(ptr2, encryptParam.rgszKeyWrapObjId[index1].DangerousGetHandle());
             if ((int)num6 == 26114)
                 Marshal.WriteIntPtr(new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "pvKeyWrapAuxInfo")), encryptParam.pvEncryptionAuxInfo.DangerousGetHandle());
             Marshal.WriteInt32(new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "dwKeyChoice")), 1);
             IntPtr ptr3 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "pEphemeralAlgorithmOrSenderId"));
             encryptParam.rgEphemeralIdentifier[index1] = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER))));
             Marshal.WriteIntPtr(ptr3, encryptParam.rgEphemeralIdentifier[index1].DangerousGetHandle());
             byte[] bytes2 = Encoding.ASCII.GetBytes(certInfo.SubjectPublicKeyInfo.Algorithm.pszObjId);
             encryptParam.rgszEphemeralObjId[index1] = CAPI.LocalAlloc(64U, new IntPtr(bytes2.Length + 1));
             Marshal.Copy(bytes2, 0, encryptParam.rgszEphemeralObjId[index1].DangerousGetHandle(), bytes2.Length);
             ptr2 = new IntPtr((long)encryptParam.rgEphemeralIdentifier[index1].DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "pszObjId"));
             Marshal.WriteIntPtr(ptr2, encryptParam.rgszEphemeralObjId[index1].DangerousGetHandle());
             IntPtr num7 = new IntPtr((long)encryptParam.rgEphemeralIdentifier[index1].DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "Parameters"));
             IntPtr ptr4 = new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData"));
             Marshal.WriteInt32(ptr4, (int)certInfo.SubjectPublicKeyInfo.Algorithm.Parameters.cbData);
             IntPtr ptr5 = new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData"));
             Marshal.WriteIntPtr(ptr5, certInfo.SubjectPublicKeyInfo.Algorithm.Parameters.pbData);
             Marshal.WriteInt32(new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "cRecipientEncryptedKeys")), 1);
             encryptParam.prgpEncryptedKey[index1] = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(IntPtr))));
             Marshal.WriteIntPtr(new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "rgpRecipientEncryptedKeys")), encryptParam.prgpEncryptedKey[index1].DangerousGetHandle());
             encryptParam.rgpEncryptedKey[index1] = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO))));
             Marshal.WriteIntPtr(encryptParam.prgpEncryptedKey[index1].DangerousGetHandle(), encryptParam.rgpEncryptedKey[index1].DangerousGetHandle());
             ptr1 = new IntPtr((long)encryptParam.rgpEncryptedKey[index1].DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO), "cbSize"));
             Marshal.WriteInt32(ptr1, Marshal.SizeOf(typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO)));
             IntPtr num8 = new IntPtr((long)encryptParam.rgpEncryptedKey[index1].DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO), "RecipientPublicKey"));
             ptr4 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "cbData"));
             Marshal.WriteInt32(ptr4, (int)certInfo.SubjectPublicKeyInfo.PublicKey.cbData);
             ptr5 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "pbData"));
             Marshal.WriteIntPtr(ptr5, certInfo.SubjectPublicKeyInfo.PublicKey.pbData);
             Marshal.WriteInt32(new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "cUnusedBits")), (int)certInfo.SubjectPublicKeyInfo.PublicKey.cUnusedBits);
             IntPtr num9 = new IntPtr((long)encryptParam.rgpEncryptedKey[index1].DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO), "RecipientId"));
             IntPtr ptr6 = new IntPtr((long)num9 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "dwIdChoice"));
             if (cmsRecipient.RecipientIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier)
             {
                 Marshal.WriteInt32(ptr6, 2);
                 IntPtr num10 = new IntPtr((long)num9 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "Value"));
                 uint pcbData = 0U;
                 SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle;
                 if (!CAPI.CAPISafe.CertGetCertificateContextProperty(X509Utils.GetCertContext(certificate), 20U, invalidHandle, out pcbData))
                     throw new CryptographicException(Marshal.GetLastWin32Error());
                 SafeLocalAllocHandle pvData = CAPI.LocalAlloc(64U, new IntPtr((long)pcbData));
                 if (!CAPI.CAPISafe.CertGetCertificateContextProperty(X509Utils.GetCertContext(certificate), 20U, pvData, out pcbData))
                     throw new CryptographicException(Marshal.GetLastWin32Error());
                 encryptParam.rgSubjectKeyIdentifier[index1] = pvData;
                 ptr4 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData"));
                 Marshal.WriteInt32(ptr4, (int)pcbData);
                 ptr5 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData"));
                 Marshal.WriteIntPtr(ptr5, pvData.DangerousGetHandle());
             }
             else
             {
                 Marshal.WriteInt32(ptr6, 1);
                 IntPtr num10 = new IntPtr((long)num9 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "Value"));
                 IntPtr num11 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ISSUER_SERIAL_NUMBER), "Issuer"));
                 ptr4 = new IntPtr((long)num11 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData"));
                 Marshal.WriteInt32(ptr4, (int)certInfo.Issuer.cbData);
                 ptr5 = new IntPtr((long)num11 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData"));
                 Marshal.WriteIntPtr(ptr5, certInfo.Issuer.pbData);
                 IntPtr num12 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ISSUER_SERIAL_NUMBER), "SerialNumber"));
                 ptr4 = new IntPtr((long)num12 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData"));
                 Marshal.WriteInt32(ptr4, (int)certInfo.SerialNumber.cbData);
                 ptr5 = new IntPtr((long)num12 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData"));
                 Marshal.WriteIntPtr(ptr5, certInfo.SerialNumber.pbData);
             }
             ++index1;
             num3 = new IntPtr((long)num3 + (long)Marshal.SizeOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO)));
         }
     }
 }
Esempio n. 7
0
 public Pkcs5Scheme2PbeKey(
     char[]                          password,
     AlgorithmIdentifier keyDerivationAlgorithm)
     : base(password, keyDerivationAlgorithm)
 {
 }
Esempio n. 8
0
        private OcspReq GenerateRequest(
            DerObjectIdentifier signingAlgorithm,
            AsymmetricKeyParameter privateKey,
            X509Certificate[]               chain,
            SecureRandom random)
        {
            Asn1EncodableVector requests = new Asn1EncodableVector();

            foreach (RequestObject reqObj in list)
            {
                try
                {
                    requests.Add(reqObj.ToRequest());
                }
                catch (Exception e)
                {
                    throw new OcspException("exception creating Request", e);
                }
            }

            TbsRequest tbsReq = new TbsRequest(requestorName, new DerSequence(requests), requestExtensions);

            ISigner   sig       = null;
            Signature signature = null;

            if (signingAlgorithm != null)
            {
                if (requestorName == null)
                {
                    throw new OcspException("requestorName must be specified if request is signed.");
                }

                try
                {
                    sig = SignerUtilities.GetSigner(signingAlgorithm.Id);
                    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 = tbsReq.GetEncoded();
                    sig.BlockUpdate(encoded, 0, encoded.Length);

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

                AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(signingAlgorithm, DerNull.Instance);

                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);
                    }

                    signature = new Signature(sigAlgId, bitSig, new DerSequence(v));
                }
                else
                {
                    signature = new Signature(sigAlgId, bitSig);
                }
            }

            return(new OcspReq(new OcspRequest(tbsReq, signature)));
        }
            internal SignerInfo ToSignerInfo(
                DerObjectIdentifier contentType,
                CmsProcessable content,
                SecureRandom random)
            {
                AlgorithmIdentifier digAlgId = DigestAlgorithmID;
                string  digestName           = Helper.GetDigestAlgName(digestOID);
                IDigest dig = Helper.GetDigestInstance(digestName);

                string  signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID);
                ISigner sig           = Helper.GetSignatureInstance(signatureName);

                // TODO Optimise the case where more than one signer with same digest
                if (content != null)
                {
                    content.Write(new DigOutputStream(dig));
                }

                byte[] hash = DigestUtilities.DoFinal(dig);
                outer._digests.Add(digestOID, hash.Clone());

                sig.Init(true, new ParametersWithRandom(key, random));
#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT
                Stream sigStr = new SigOutputStream(sig);
#else
                Stream sigStr = new BufferedStream(new SigOutputStream(sig));
#endif

                Asn1Set signedAttr = null;
                if (sAttr != null)
                {
                    IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

//					Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(Collections.unmodifiableMap(parameters));
                    Asn1.Cms.AttributeTable signed = sAttr.GetAttributes(parameters);

                    if (contentType == null) //counter signature
                    {
                        if (signed != null && signed[CmsAttributes.ContentType] != null)
                        {
                            IDictionary tmpSigned = signed.ToDictionary();
                            tmpSigned.Remove(CmsAttributes.ContentType);
                            signed = new Asn1.Cms.AttributeTable(tmpSigned);
                        }
                    }

                    // TODO Validate proposed signed attributes

                    signedAttr = outer.GetAttributeSet(signed);

                    // sig must be composed from the DER encoding.
                    new DerOutputStream(sigStr).WriteObject(signedAttr);
                }
                else if (content != null)
                {
                    // TODO Use raw signature of the hash value instead
                    content.Write(sigStr);
                }

                sigStr.Close();
                byte[] sigBytes = sig.GenerateSignature();

                Asn1Set unsignedAttr = null;
                if (unsAttr != null)
                {
                    IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash);
                    baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone();

//					Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters));
                    Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(baseParameters);

                    // TODO Validate proposed unsigned attributes

                    unsignedAttr = outer.GetAttributeSet(unsigned);
                }

                // TODO[RSAPSS] Need the ability to specify non-default parameters
                Asn1Encodable       sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName);
                AlgorithmIdentifier encAlgId          = CmsSignedGenerator.GetEncAlgorithmIdentifier(
                    new DerObjectIdentifier(encOID), sigX509Parameters);

                return(new SignerInfo(signerIdentifier, digAlgId,
                                      signedAttr, encAlgId, new DerOctetString(sigBytes), unsignedAttr));
            }
        private BasicOcspResp GenerateResponse(
            string signatureName,
            AsymmetricKeyParameter 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);

            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 (Security.Certificates.CertificateEncodingException e)
                {
                    throw new OcspException("error encoding certs", e);
                }

                return(new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, new DerSequence(v))));
            }
            else
            {
                return(new BasicOcspResp(new BasicOcspResponse(tbsResp, sigAlgId, bitSig, null)));
            }
        }
Esempio n. 11
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");
            }

            //
            // 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)
                {
                    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)));
                }

                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());
            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)));
                }

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

                certSeq.Add(sBag);

                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))));
                }

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

                certSeq.Add(sBag);

                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])));
                }

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

                certSeq.Add(sBag);
            }

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

            byte[] certBytes = CryptPbeData(true, cAlgId, password, false, derEncodedBytes);

            EncryptedData cInfo = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes));

            ContentInfo[] info = new ContentInfo[]
            {
                new ContentInfo(PkcsObjectIdentifiers.Data, keyString),
                new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object())
            };

            byte[] data = new AuthenticatedSafe(info).GetEncoded();

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

            //
            // create the mac
            //
            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 mData = new MacData(dInfo, mSalt, MinIterations);

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

            BerOutputStream berOut = new BerOutputStream(stream);

            berOut.WriteObject(pfx);
        }
 public CompressedDataParser(Asn1SequenceParser seq)
 {
     _version = (DerInteger)seq.ReadObject();
     _compressionAlgorithm = AlgorithmIdentifier.GetInstance(seq.ReadObject().ToAsn1Object());
     _encapContentInfo     = new ContentInfoParser((Asn1SequenceParser)seq.ReadObject());
 }
Esempio n. 13
0
 public static ICipherParameters GenerateCipherParameters(
     AlgorithmIdentifier algID,
     char[]              password)
 {
     return(GenerateCipherParameters(algID.ObjectID.Id, password, false, algID.Parameters));
 }
Esempio n. 14
0
        static X509Utilities()
        {
            algorithms.Add("MD2WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD2WithRsaEncryption);
            algorithms.Add("MD2WITHRSA", PkcsObjectIdentifiers.MD2WithRsaEncryption);
            algorithms.Add("MD5WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD5WithRsaEncryption);
            algorithms.Add("MD5WITHRSA", PkcsObjectIdentifiers.MD5WithRsaEncryption);
            algorithms.Add("SHA1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
            algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
            algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
            algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
            algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
            algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
            algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
            algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
            algorithms.Add("SHA1WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
            algorithms.Add("SHA224WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
            algorithms.Add("SHA256WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
            algorithms.Add("SHA384WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
            algorithms.Add("SHA512WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
            algorithms.Add("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
            algorithms.Add("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
            algorithms.Add("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
            algorithms.Add("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
            algorithms.Add("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
            algorithms.Add("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
            algorithms.Add("SHA1WITHDSA", X9ObjectIdentifiers.IdDsaWithSha1);
            algorithms.Add("DSAWITHSHA1", X9ObjectIdentifiers.IdDsaWithSha1);
            algorithms.Add("SHA224WITHDSA", NistObjectIdentifiers.DsaWithSha224);
            algorithms.Add("SHA256WITHDSA", NistObjectIdentifiers.DsaWithSha256);
            algorithms.Add("SHA384WITHDSA", NistObjectIdentifiers.DsaWithSha384);
            algorithms.Add("SHA512WITHDSA", NistObjectIdentifiers.DsaWithSha512);
            algorithms.Add("SHA1WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha1);
            algorithms.Add("ECDSAWITHSHA1", X9ObjectIdentifiers.ECDsaWithSha1);
            algorithms.Add("SHA224WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha224);
            algorithms.Add("SHA256WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha256);
            algorithms.Add("SHA384WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha384);
            algorithms.Add("SHA512WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha512);
            algorithms.Add("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
            algorithms.Add("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
            algorithms.Add("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
            algorithms.Add("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
            algorithms.Add("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);

            //
            // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field.
            // The parameters field SHALL be NULL for RSA based signature algorithms.
            //
            noParams.Add(X9ObjectIdentifiers.ECDsaWithSha1);
            algorithms.Add("GOST3411_2012_256WITHECGOST3410", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256);
            algorithms.Add("GOST3411_2012_512WITHECGOST3410", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512);

            noParams.Add(X9ObjectIdentifiers.ECDsaWithSha224);
            noParams.Add(X9ObjectIdentifiers.ECDsaWithSha256);
            noParams.Add(X9ObjectIdentifiers.ECDsaWithSha384);
            noParams.Add(X9ObjectIdentifiers.ECDsaWithSha512);
            noParams.Add(X9ObjectIdentifiers.IdDsaWithSha1);
            noParams.Add(NistObjectIdentifiers.DsaWithSha224);
            noParams.Add(NistObjectIdentifiers.DsaWithSha256);
            noParams.Add(NistObjectIdentifiers.DsaWithSha384);
            noParams.Add(NistObjectIdentifiers.DsaWithSha512);

            //
            // RFC 4491
            //
            noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
            noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
            noParams.Add(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256);
            noParams.Add(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512);

            //
            // explicit params
            //
            AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance);

            exParams.Add("SHA1WITHRSAANDMGF1", CreatePssParams(sha1AlgId, 20));

            AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance);

            exParams.Add("SHA224WITHRSAANDMGF1", CreatePssParams(sha224AlgId, 28));

            AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance);

            exParams.Add("SHA256WITHRSAANDMGF1", CreatePssParams(sha256AlgId, 32));

            AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance);

            exParams.Add("SHA384WITHRSAANDMGF1", CreatePssParams(sha384AlgId, 48));

            AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha512, DerNull.Instance);

            exParams.Add("SHA512WITHRSAANDMGF1", CreatePssParams(sha512AlgId, 64));
        }
Esempio n. 15
0
 public static object CreateEngine(
     AlgorithmIdentifier algID)
 {
     return(CreateEngine(algID.ObjectID.Id));
 }
Esempio n. 16
0
 public EssCertIDv2(
     AlgorithmIdentifier algId,
     byte[]                          certHash)
     : this(algId, certHash, null)
 {
 }
Esempio n. 17
0
 public KeyAgreeRecipientInfo(OriginatorIdentifierOrKey originator, Asn1OctetString ukm, AlgorithmIdentifier keyEncryptionAlgorithm, Asn1Sequence recipientEncryptedKeys)
 {
     this.version                = new DerInteger(3);
     this.originator             = originator;
     this.ukm                    = ukm;
     this.keyEncryptionAlgorithm = keyEncryptionAlgorithm;
     this.recipientEncryptedKeys = recipientEncryptedKeys;
 }
Esempio n. 18
0
 /**
  * The default version
  */
 public RsaesOaepParameters()
 {
     hashAlgorithm    = DefaultHashAlgorithm;
     maskGenAlgorithm = DefaultMaskGenFunction;
     pSourceAlgorithm = DefaultPSourceAlgorithm;
 }
Esempio n. 19
0
 public EnvelopedCms(ContentInfo contentInfo, AlgorithmIdentifier encryptionAlgorithm)
     : this(SubjectIdentifierType.IssuerAndSerialNumber, contentInfo, encryptionAlgorithm)
 {
 }
Esempio n. 20
0
 public virtual PkiHeaderBuilder SetProtectionAlg(AlgorithmIdentifier aid)
 {
     protectionAlg = aid;
     return(this);
 }
Esempio n. 21
0
        public static ICipherParameters GenerateCipherParameters(
            string algorithm,
            char[]          password,
            bool wrongPkcs12Zero,
            Asn1Encodable pbeParameters)
        {
            //TODO: SUSTITUIDO
            //string	mechanism = (string) algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)];
            string mechanism = (string)algorithms[algorithm.ToUpper()];

            byte[] keyBytes       = null;
            byte[] salt           = null;
            int    iterationCount = 0;

            if (IsPkcs12(mechanism))
            {
                Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(pbeParameters);
                salt           = pbeParams.GetIV();
                iterationCount = pbeParams.Iterations.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero);
            }
            else if (IsPkcs5Scheme2(mechanism))
            {
                // See below
            }
            else
            {
                PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters);
                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
            }

            ICipherParameters parameters = null;

            if (IsPkcs5Scheme2(mechanism))
            {
                PbeS2Parameters     s2p       = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object());
                AlgorithmIdentifier encScheme = s2p.EncryptionScheme;
                DerObjectIdentifier encOid    = encScheme.ObjectID;
                Asn1Object          encParams = encScheme.Parameters.ToAsn1Object();

                // TODO What about s2p.KeyDerivationFunc.ObjectID?
                Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(s2p.KeyDerivationFunc.Parameters.ToAsn1Object());

                byte[] iv;
                if (encOid.Equals(PkcsObjectIdentifiers.RC2Cbc))                 // PKCS5.B.2.3
                {
                    RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(encParams);
                    iv = rc2Params.GetIV();
                }
                else
                {
                    iv = Asn1OctetString.GetInstance(encParams).GetOctets();
                }

                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);

                int keyLength = pbeParams.KeyLength != null
                                        ?       pbeParams.KeyLength.IntValue * 8
                                        :       GeneratorUtilities.GetDefaultKeySize(encOid);

                PbeParametersGenerator gen = MakePbeGenerator(
                    (string)algorithmType[mechanism], null, keyBytes, salt, iterationCount);

                parameters = gen.GenerateDerivedParameters(encOid.Id, keyLength);

                if (iv != null)
                {
                    // FIXME? OpenSSL weirdness with IV of zeros (for ECB keys?)
                    if (Arrays.AreEqual(iv, new byte[iv.Length]))
                    {
                        //Console.Error.Write("***** IV all 0 (length " + iv.Length + ") *****");
                    }
                    else
                    {
                        parameters = new ParametersWithIV(parameters, iv);
                    }
                }
            }
            else if (mechanism.StartsWith("PBEwithSHA-1"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithSHA-1and128bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters("RC4", 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters("RC4", 40);
                }
                else if (mechanism.Equals("PBEwithSHA-1and3-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DESEDE", 192, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and2-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DESEDE", 128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 40, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithSHA-256"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithSHA-256and128bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithMD5"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithMD5andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (mechanism.StartsWith("PBEwithMD2"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount);
                if (mechanism.Equals("PBEwithMD2andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD2andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
            }
            else if (mechanism.StartsWith("PBEwithHmac"))
            {
                string  digestName = mechanism.Substring("PBEwithHmac".Length);
                IDigest digest     = DigestUtilities.GetDigest(digestName);

                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], digest, keyBytes, salt, iterationCount);

                int bitLen = digest.GetDigestSize() * 8;
                parameters = generator.GenerateDerivedMacParameters(bitLen);
            }

            Array.Clear(keyBytes, 0, keyBytes.Length);

            return(FixDesParity(mechanism, parameters));
        }
Esempio n. 22
0
        public void Load(
            Stream input,
            char[]  password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            Asn1Sequence obj             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          bag             = new Pfx(obj);
            ContentInfo  info            = bag.AuthSafe;
            bool         unmarkedKey     = false;
            bool         wrongPkcs12Zero = false;

            if (bag.MacData != null)             // check the mac code
            {
                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

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

                byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data);
                byte[] dig = dInfo.GetDigest();

                if (!Arrays.AreEqual(mac, dig))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    // Try with incorrect zero length password
                    mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data);

                    if (!Arrays.AreEqual(mac, dig))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    wrongPkcs12Zero = true;
                }
            }

            keys.Clear();
            localIds.Clear();

            ArrayList chain = new ArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octs     = ((Asn1OctetString)info.Content).GetOctets();
                AuthenticatedSafe authSafe = new AuthenticatedSafe(
                    (Asn1Sequence)Asn1OctetString.FromByteArray(octs));
                ContentInfo[] cis = authSafe.GetContentInfo();

                foreach (ContentInfo ci in cis)
                {
                    DerObjectIdentifier oid = ci.ContentType;

                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        byte[]       octets = ((Asn1OctetString)ci.Content).GetOctets();
                        Asn1Sequence seq    = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                                    password, wrongPkcs12Zero, eIn);
                                AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                Hashtable          attributes = new Hashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                string             alias      = null;
                                Asn1OctetString    localId    = null;

                                if (b.BagAttributes != null)
                                {
                                    foreach (Asn1Sequence sq in b.BagAttributes)
                                    {
                                        DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                        Asn1Set             attrSet = (Asn1Set)sq[1];
                                        Asn1Encodable       attr    = null;

                                        if (attrSet.Count > 0)
                                        {
                                            // TODO We should be adding all attributes in the set
                                            attr = attrSet[0];

                                            // TODO We might want to "merge" attribute sets with
                                            // the same OID - currently, differing values give an error
                                            if (attributes.ContainsKey(aOid.Id))
                                            {
                                                // OK, but the value has to be the same
                                                if (!attributes[aOid.Id].Equals(attr))
                                                {
                                                    throw new IOException("attempt to add existing attribute with different value");
                                                }
                                            }
                                            else
                                            {
                                                attributes.Add(aOid.Id, attr);
                                            }

                                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                            {
                                                alias = ((DerBmpString)attr).GetString();
                                                // TODO Do these in a separate loop, just collect aliases here
                                                keys[alias] = pkcs12Key;
                                            }
                                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                            {
                                                localId = (Asn1OctetString)attr;
                                            }
                                        }
                                    }
                                }

                                if (localId != null)
                                {
                                    byte[] hex  = Hex.Encode(localId.GetOctets());
                                    string name = Encoding.ASCII.GetString(hex, 0, hex.Length);

                                    if (alias == null)
                                    {
                                        keys[name] = pkcs12Key;
                                    }
                                    else
                                    {
                                        // TODO There may have been more than one alias
                                        localIds[alias] = name;
                                    }
                                }
                                else
                                {
                                    unmarkedKey      = true;
                                    keys["unmarked"] = pkcs12Key;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                chain.Add(b);
                            }
                            else
                            {
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
                            }
                        }
                    }
                    else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        EncryptedData d      = EncryptedData.GetInstance(ci.Content);
                        byte[]        octets = CryptPbeData(false, d.EncryptionAlgorithm,
                                                            password, wrongPkcs12Zero, d.Content.GetOctets());
                        Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                chain.Add(b);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                EncryptedPrivateKeyInfo eIn      = EncryptedPrivateKeyInfo.GetInstance(b.BagValue);
                                PrivateKeyInfo          privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
                                    password, wrongPkcs12Zero, eIn);
                                AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privInfo);

                                //
                                // set the attributes on the key
                                //
                                Hashtable          attributes = new Hashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);
                                string             alias      = null;
                                Asn1OctetString    localId    = null;

                                foreach (Asn1Sequence sq in b.BagAttributes)
                                {
                                    DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                    Asn1Set             attrSet = (Asn1Set)sq[1];
                                    Asn1Encodable       attr    = null;

                                    if (attrSet.Count > 0)
                                    {
                                        // TODO We should be adding all attributes in the set
                                        attr = attrSet[0];

                                        // TODO We might want to "merge" attribute sets with
                                        // the same OID - currently, differing values give an error
                                        if (attributes.ContainsKey(aOid.Id))
                                        {
                                            // OK, but the value has to be the same
                                            if (!attributes[aOid.Id].Equals(attr))
                                            {
                                                throw new IOException("attempt to add existing attribute with different value");
                                            }
                                        }
                                        else
                                        {
                                            attributes.Add(aOid.Id, attr);
                                        }

                                        if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                        {
                                            alias = ((DerBmpString)attr).GetString();
                                            // TODO Do these in a separate loop, just collect aliases here
                                            keys[alias] = pkcs12Key;
                                        }
                                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                        {
                                            localId = (Asn1OctetString)attr;
                                        }
                                    }
                                }

                                // TODO Should we be checking localIds != null here
                                // as for PkcsObjectIdentifiers.Data version above?

                                byte[] hex  = Hex.Encode(localId.GetOctets());
                                string name = Encoding.ASCII.GetString(hex, 0, hex.Length);

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    // TODO There may have been more than one alias
                                    localIds[alias] = name;
                                }
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                PrivateKeyInfo         privKeyInfo = PrivateKeyInfo.GetInstance(b.BagValue);
                                AsymmetricKeyParameter privKey     = PrivateKeyFactory.CreateKey(privKeyInfo);

                                //
                                // set the attributes on the key
                                //
                                string             alias      = null;
                                Asn1OctetString    localId    = null;
                                Hashtable          attributes = new Hashtable();
                                AsymmetricKeyEntry pkcs12Key  = new AsymmetricKeyEntry(privKey, attributes);

                                foreach (Asn1Sequence sq in b.BagAttributes)
                                {
                                    DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                                    Asn1Set             attrSet = (Asn1Set)sq[1];
                                    Asn1Encodable       attr    = null;

                                    if (attrSet.Count > 0)
                                    {
                                        // TODO We should be adding all attributes in the set
                                        attr = attrSet[0];

                                        // TODO We might want to "merge" attribute sets with
                                        // the same OID - currently, differing values give an error
                                        if (attributes.ContainsKey(aOid.Id))
                                        {
                                            // OK, but the value has to be the same
                                            if (!attributes[aOid.Id].Equals(attr))
                                            {
                                                throw new IOException("attempt to add existing attribute with different value");
                                            }
                                        }
                                        else
                                        {
                                            attributes.Add(aOid.Id, attr);
                                        }

                                        if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                                        {
                                            alias = ((DerBmpString)attr).GetString();
                                            // TODO Do these in a separate loop, just collect aliases here
                                            keys[alias] = pkcs12Key;
                                        }
                                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                                        {
                                            localId = (Asn1OctetString)attr;
                                        }
                                    }
                                }

                                // TODO Should we be checking localIds != null here
                                // as for PkcsObjectIdentifiers.Data version above?

                                byte[] hex  = Hex.Encode(localId.GetOctets());
                                string name = Encoding.ASCII.GetString(hex, 0, hex.Length);

                                if (alias == null)
                                {
                                    keys[name] = pkcs12Key;
                                }
                                else
                                {
                                    // TODO There may have been more than one alias
                                    localIds[alias] = name;
                                }
                            }
                            else
                            {
                                Console.WriteLine("extra " + b.BagID);
                                Console.WriteLine("extra " + Asn1Dump.DumpAsString(b));
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("extra " + oid);
                        Console.WriteLine("extra " + Asn1Dump.DumpAsString(ci.Content));
                    }
                }
            }

            certs.Clear();
            chainCerts.Clear();
            keyCerts.Clear();

            foreach (SafeBag b in chain)
            {
                CertBag         cb     = new CertBag((Asn1Sequence)b.BagValue);
                byte[]          octets = ((Asn1OctetString)cb.CertValue).GetOctets();
                X509Certificate cert   = new X509CertificateParser().ReadCertificate(octets);

                //
                // set the attributes
                //
                Hashtable       attributes = new Hashtable();
                Asn1OctetString localId    = null;
                string          alias      = null;

                if (b.BagAttributes != null)
                {
                    foreach (Asn1Sequence sq in b.BagAttributes)
                    {
                        DerObjectIdentifier aOid    = (DerObjectIdentifier)sq[0];
                        Asn1Set             attrSet = (Asn1Set)sq[1];

                        if (attrSet.Count > 0)
                        {
                            // TODO We should be adding all attributes in the set
                            Asn1Encodable attr = attrSet[0];

                            // TODO We might want to "merge" attribute sets with
                            // the same OID - currently, differing values give an error
                            if (attributes.ContainsKey(aOid.Id))
                            {
                                // OK, but the value has to be the same
                                if (!attributes[aOid.Id].Equals(attr))
                                {
                                    throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                attributes.Add(aOid.Id, attr);
                            }

                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                alias = ((DerBmpString)attr).GetString();
                            }
                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                localId = (Asn1OctetString)attr;
                            }
                        }
                    }
                }

                CertId certId = new CertId(cert.GetPublicKey());
                X509CertificateEntry pkcs12Cert = new X509CertificateEntry(cert, attributes);

                chainCerts[certId] = pkcs12Cert;

                if (unmarkedKey)
                {
                    if (keyCerts.Count == 0)
                    {
                        byte[] hex  = Hex.Encode(certId.Id);
                        string name = Encoding.ASCII.GetString(hex, 0, hex.Length);

                        keyCerts[name] = pkcs12Cert;

                        object temp = keys["unmarked"];
                        keys.Remove("unmarked");
                        keys[name] = temp;
                    }
                }
                else
                {
                    if (localId != null)
                    {
                        byte[] hex  = Hex.Encode(localId.GetOctets());
                        string name = Encoding.ASCII.GetString(hex, 0, hex.Length);

                        keyCerts[name] = pkcs12Cert;
                    }

                    if (alias != null)
                    {
                        // TODO There may have been more than one alias
                        certs[alias] = pkcs12Cert;
                    }
                }
            }
        }
        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))));
        }
Esempio n. 24
0
        /// <summary>
        /// Create a Subject Public Key Info object for a given public key.
        /// </summary>
        /// <param name="key">One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters</param>
        /// <returns>A subject public key info object.</returns>
        /// <exception cref="Exception">Throw exception if object provided is not one of the above.</exception>
        public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo(
            AsymmetricKeyParameter key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (key.IsPrivate)
            {
                throw new ArgumentException("Private key passed - public key expected.", "key");
            }

            if (key is ElGamalPublicKeyParameters)
            {
                ElGamalPublicKeyParameters _key = (ElGamalPublicKeyParameters)key;
                ElGamalParameters          kp   = _key.Parameters;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(
                        OiwObjectIdentifiers.ElGamalAlgorithm,
                        new ElGamalParameter(kp.P, kp.G).ToAsn1Object()),
                    new DerInteger(_key.Y));

                return(info);
            }

            if (key is DsaPublicKeyParameters)
            {
                DsaPublicKeyParameters _key = (DsaPublicKeyParameters)key;
                DsaParameters          kp   = _key.Parameters;
                Asn1Encodable          ae   = kp == null
                                        ?       null
                                        :       new DsaParameter(kp.P, kp.Q, kp.G).ToAsn1Object();

                return(new SubjectPublicKeyInfo(
                           new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, ae),
                           new DerInteger(_key.Y)));
            }

            if (key is DHPublicKeyParameters)
            {
                DHPublicKeyParameters _key = (DHPublicKeyParameters)key;
                DHParameters          kp   = _key.Parameters;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(
                        X9ObjectIdentifiers.DHPublicNumber,
                        new DHParameter(kp.P, kp.G, kp.L).ToAsn1Object()),
                    new DerInteger(_key.Y));

                return(info);
            } // End of DH

            if (key is RsaKeyParameters)
            {
                RsaKeyParameters _key = (RsaKeyParameters)key;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance),
                    new RsaPublicKeyStructure(_key.Modulus, _key.Exponent).ToAsn1Object());

                return(info);
            } // End of RSA.

            if (key is ECPublicKeyParameters)
            {
                ECPublicKeyParameters _key = (ECPublicKeyParameters)key;

                if (_key.AlgorithmName == "ECGOST3410")
                {
                    if (_key.PublicKeyParamSet == null)
                    {
                        throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
                    }

                    ECPoint    q  = _key.Q;
                    BigInteger bX = q.X.ToBigInteger();
                    BigInteger bY = q.Y.ToBigInteger();

                    byte[] encKey = new byte[64];
                    ExtractBytes(encKey, 0, bX);
                    ExtractBytes(encKey, 32, bY);

                    Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                        _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);

                    AlgorithmIdentifier algID = new AlgorithmIdentifier(
                        CryptoProObjectIdentifiers.GostR3410x2001,
                        gostParams.ToAsn1Object());

                    return(new SubjectPublicKeyInfo(algID, new DerOctetString(encKey)));
                }
                else
                {
                    X962Parameters x962;
                    if (_key.PublicKeyParamSet == null)
                    {
                        ECDomainParameters kp  = _key.Parameters;
                        X9ECParameters     ecP = new X9ECParameters(kp.Curve, kp.G, kp.N, kp.H, kp.GetSeed());

                        x962 = new X962Parameters(ecP);
                    }
                    else
                    {
                        x962 = new X962Parameters(_key.PublicKeyParamSet);
                    }

                    Asn1OctetString p = (Asn1OctetString)(new X9ECPoint(_key.Q).ToAsn1Object());

                    AlgorithmIdentifier algID = new AlgorithmIdentifier(
                        X9ObjectIdentifiers.IdECPublicKey, x962.ToAsn1Object());

                    return(new SubjectPublicKeyInfo(algID, p.GetOctets()));
                }
            }             // End of EC

            if (key is Gost3410PublicKeyParameters)
            {
                Gost3410PublicKeyParameters _key = (Gost3410PublicKeyParameters)key;

                if (_key.PublicKeyParamSet == null)
                {
                    throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
                }

                byte[] keyEnc   = _key.Y.ToByteArrayUnsigned();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyBytes.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i];                     // must be little endian
                }

                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);

                AlgorithmIdentifier algID = new AlgorithmIdentifier(
                    CryptoProObjectIdentifiers.GostR3410x94,
                    algParams.ToAsn1Object());

                return(new SubjectPublicKeyInfo(algID, new DerOctetString(keyBytes)));
            }

            throw new ArgumentException("Class provided no convertible: " + key.GetType().FullName);
        }
Esempio n. 25
0
        public void CheckAttributeCertificate(
            int id,
            byte[]  cert)
        {
            Asn1Sequence seq  = (Asn1Sequence)Asn1Object.FromByteArray(cert);
            string       dump = Asn1Dump.DumpAsString(seq);

            AttributeCertificate     obj    = AttributeCertificate.GetInstance(seq);
            AttributeCertificateInfo acInfo = obj.ACInfo;

            // Version
            if (!(acInfo.Version.Equals(new DerInteger(1))) &&
                (!(acInfo.Version.Equals(new DerInteger(2)))))
            {
                Fail("failed AC Version test for id " + id);
            }

            // Holder
            Holder h = acInfo.Holder;

            if (h == null)
            {
                Fail("failed AC Holder test, it's null, for id " + id);
            }

            // Issuer
            AttCertIssuer aci = acInfo.Issuer;

            if (aci == null)
            {
                Fail("failed AC Issuer test, it's null, for id " + id);
            }

            // Signature
            AlgorithmIdentifier sig = acInfo.Signature;

            if (sig == null)
            {
                Fail("failed AC Signature test for id " + id);
            }

            // Serial
            DerInteger serial = acInfo.SerialNumber;

            // Validity
            AttCertValidityPeriod validity = acInfo.AttrCertValidityPeriod;

            if (validity == null)
            {
                Fail("failed AC AttCertValidityPeriod test for id " + id);
            }

            // Attributes
            Asn1Sequence attribSeq = acInfo.Attributes;

            AttributeX509[] att = new AttributeX509[attribSeq.Count];
            for (int i = 0; i < attribSeq.Count; i++)
            {
                att[i] = AttributeX509.GetInstance(attribSeq[i]);
            }

            // IssuerUniqueId
            // TODO, how to best test?

            // X509 Extensions
            X509Extensions ext = acInfo.Extensions;

            if (ext != null)
            {
                foreach (DerObjectIdentifier oid in ext.ExtensionOids)
                {
                    X509Extension extVal = ext.GetExtension(oid);
                }
            }
        }
Esempio n. 26
0
        private Stream Open(
            Stream outStream,
            AlgorithmIdentifier encAlgID,
            ICipherParameters cipherParameters,
            Asn1EncodableVector recipientInfos)
        {
            try
            {
                //
                // ContentInfo
                //
                BerSequenceGenerator cGen = new BerSequenceGenerator(outStream);

                cGen.AddObject(CmsObjectIdentifiers.EnvelopedData);

                //
                // Encrypted Data
                //
                BerSequenceGenerator envGen = new BerSequenceGenerator(
                    cGen.GetRawOutputStream(), 0, true);

                envGen.AddObject(this.Version);

                Stream        envRaw   = envGen.GetRawOutputStream();
                Asn1Generator recipGen = _berEncodeRecipientSet
                                        ?       (Asn1Generator) new BerSetGenerator(envRaw)
                                        :       new DerSetGenerator(envRaw);

                foreach (Asn1Encodable ae in recipientInfos)
                {
                    recipGen.AddObject(ae);
                }

                recipGen.Close();

                BerSequenceGenerator eiGen = new BerSequenceGenerator(envRaw);
                eiGen.AddObject(CmsObjectIdentifiers.Data);
                eiGen.AddObject(encAlgID);

                Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream(
                    eiGen.GetRawOutputStream(), 0, false, _bufferSize);

                IBufferedCipher cipher = CipherUtilities.GetCipher(encAlgID.Algorithm);
                cipher.Init(true, new ParametersWithRandom(cipherParameters, rand));
                CipherStream cOut = new CipherStream(octetOutputStream, null, cipher);

                return(new CmsEnvelopedDataOutputStream(this, cOut, cGen, envGen, eiGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }
        }
Esempio n. 27
0
        /**
         * base constructor
         *
         * @param signedContent the content that was signed.
         * @param sigData the signature object.
         */
        public CmsSignedDataParser(
            CmsTypedStream signedContent,
            Stream sigData)
            : base(sigData)
        {
            try
            {
                this._signedContent = signedContent;
                this._signedData    = SignedDataParser.GetInstance(this.contentInfo.GetContent(Asn1Tags.Sequence));
                this._digests       = Platform.CreateHashtable();
                this._digestOids    = new HashSet();

                Asn1SetParser    digAlgs = _signedData.GetDigestAlgorithms();
                IAsn1Convertible o;

                while ((o = digAlgs.ReadObject()) != null)
                {
                    AlgorithmIdentifier id = AlgorithmIdentifier.GetInstance(o.ToAsn1Object());

                    try
                    {
                        string digestOid  = id.ObjectID.Id;
                        string digestName = Helper.GetDigestAlgName(digestOid);

                        if (!this._digests.Contains(digestName))
                        {
                            this._digests[digestName] = Helper.GetDigestInstance(digestName);
                            this._digestOids.Add(digestOid);
                        }
                    }
                    catch (SecurityUtilityException)
                    {
                        // TODO Should do something other than ignore it
                    }
                }

                //
                // If the message is simply a certificate chain message GetContent() may return null.
                //
                ContentInfoParser     cont = _signedData.GetEncapContentInfo();
                Asn1OctetStringParser octs = (Asn1OctetStringParser)
                                             cont.GetContent(Asn1Tags.OctetString);

                if (octs != null)
                {
                    CmsTypedStream ctStr = new CmsTypedStream(
                        cont.ContentType.Id, octs.GetOctetStream());

                    if (_signedContent == null)
                    {
                        this._signedContent = ctStr;
                    }
                    else
                    {
                        //
                        // content passed in, need to read past empty encapsulated content info object if present
                        //
                        ctStr.Drain();
                    }
                }

                _signedContentType = _signedContent == null
                                        ?       cont.ContentType
                                        :       new DerObjectIdentifier(_signedContent.ContentType);
            }
            catch (IOException e)
            {
                throw new CmsException("io exception: " + e.Message, e);
            }

            if (_digests.Count < 1)
            {
                throw new CmsException("no digests could be created for message.");
            }
        }
Esempio n. 28
0
        static Pkcs10CertificationRequest()
        {
            algorithms.Add("MD2WITHRSAENCRYPTION", new DerObjectIdentifier("1.2.840.113549.1.1.2"));
            algorithms.Add("MD2WITHRSA", new DerObjectIdentifier("1.2.840.113549.1.1.2"));
            algorithms.Add("MD5WITHRSAENCRYPTION", new DerObjectIdentifier("1.2.840.113549.1.1.4"));
            algorithms.Add("MD5WITHRSA", new DerObjectIdentifier("1.2.840.113549.1.1.4"));
            algorithms.Add("RSAWITHMD5", new DerObjectIdentifier("1.2.840.113549.1.1.4"));
            algorithms.Add("SHA1WITHRSAENCRYPTION", new DerObjectIdentifier("1.2.840.113549.1.1.5"));
            algorithms.Add("SHA1WITHRSA", new DerObjectIdentifier("1.2.840.113549.1.1.5"));
            algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
            algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption);
            algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
            algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption);
            algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
            algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption);
            algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
            algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption);
            algorithms.Add("SHA1WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
            algorithms.Add("SHA224WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
            algorithms.Add("SHA256WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
            algorithms.Add("SHA384WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
            algorithms.Add("SHA512WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss);
            algorithms.Add("RSAWITHSHA1", new DerObjectIdentifier("1.2.840.113549.1.1.5"));
            algorithms.Add("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
            algorithms.Add("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128);
            algorithms.Add("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
            algorithms.Add("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160);
            algorithms.Add("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
            algorithms.Add("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256);
            algorithms.Add("SHA1WITHDSA", new DerObjectIdentifier("1.2.840.10040.4.3"));
            algorithms.Add("DSAWITHSHA1", new DerObjectIdentifier("1.2.840.10040.4.3"));
            algorithms.Add("SHA224WITHDSA", NistObjectIdentifiers.DsaWithSha224);
            algorithms.Add("SHA256WITHDSA", NistObjectIdentifiers.DsaWithSha256);
            algorithms.Add("SHA384WITHDSA", NistObjectIdentifiers.DsaWithSha384);
            algorithms.Add("SHA512WITHDSA", NistObjectIdentifiers.DsaWithSha512);
            algorithms.Add("SHA1WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha1);
            algorithms.Add("SHA224WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha224);
            algorithms.Add("SHA256WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha256);
            algorithms.Add("SHA384WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha384);
            algorithms.Add("SHA512WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha512);
            algorithms.Add("ECDSAWITHSHA1", X9ObjectIdentifiers.ECDsaWithSha1);
            algorithms.Add("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
            algorithms.Add("GOST3410WITHGOST3411", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
            algorithms.Add("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
            algorithms.Add("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);
            algorithms.Add("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);

            //
            // reverse mappings
            //
            oids.Add(new DerObjectIdentifier("1.2.840.113549.1.1.5"), "SHA1WITHRSA");
            oids.Add(PkcsObjectIdentifiers.Sha224WithRsaEncryption, "SHA224WITHRSA");
            oids.Add(PkcsObjectIdentifiers.Sha256WithRsaEncryption, "SHA256WITHRSA");
            oids.Add(PkcsObjectIdentifiers.Sha384WithRsaEncryption, "SHA384WITHRSA");
            oids.Add(PkcsObjectIdentifiers.Sha512WithRsaEncryption, "SHA512WITHRSA");
            oids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94, "GOST3411WITHGOST3410");
            oids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001, "GOST3411WITHECGOST3410");

            oids.Add(new DerObjectIdentifier("1.2.840.113549.1.1.4"), "MD5WITHRSA");
            oids.Add(new DerObjectIdentifier("1.2.840.113549.1.1.2"), "MD2WITHRSA");
            oids.Add(new DerObjectIdentifier("1.2.840.10040.4.3"), "SHA1WITHDSA");
            oids.Add(X9ObjectIdentifiers.ECDsaWithSha1, "SHA1WITHECDSA");
            oids.Add(X9ObjectIdentifiers.ECDsaWithSha224, "SHA224WITHECDSA");
            oids.Add(X9ObjectIdentifiers.ECDsaWithSha256, "SHA256WITHECDSA");
            oids.Add(X9ObjectIdentifiers.ECDsaWithSha384, "SHA384WITHECDSA");
            oids.Add(X9ObjectIdentifiers.ECDsaWithSha512, "SHA512WITHECDSA");
            oids.Add(OiwObjectIdentifiers.Sha1WithRsa, "SHA1WITHRSA");
            oids.Add(OiwObjectIdentifiers.DsaWithSha1, "SHA1WITHDSA");
            oids.Add(NistObjectIdentifiers.DsaWithSha224, "SHA224WITHDSA");
            oids.Add(NistObjectIdentifiers.DsaWithSha256, "SHA256WITHDSA");

            //
            // key types
            //
            keyAlgorithms.Add(PkcsObjectIdentifiers.RsaEncryption, "RSA");
            keyAlgorithms.Add(X9ObjectIdentifiers.IdDsa, "DSA");

            //
            // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field.
            // The parameters field SHALL be NULL for RSA based signature algorithms.
            //
            noParams.Add(X9ObjectIdentifiers.ECDsaWithSha1);
            noParams.Add(X9ObjectIdentifiers.ECDsaWithSha224);
            noParams.Add(X9ObjectIdentifiers.ECDsaWithSha256);
            noParams.Add(X9ObjectIdentifiers.ECDsaWithSha384);
            noParams.Add(X9ObjectIdentifiers.ECDsaWithSha512);
            noParams.Add(X9ObjectIdentifiers.IdDsaWithSha1);
            noParams.Add(NistObjectIdentifiers.DsaWithSha224);
            noParams.Add(NistObjectIdentifiers.DsaWithSha256);

            //
            // RFC 4491
            //
            noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94);
            noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001);

            //
            // explicit params
            //
            AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance);

            exParams.Add("SHA1WITHRSAANDMGF1", CreatePssParams(sha1AlgId, 20));

            AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance);

            exParams.Add("SHA224WITHRSAANDMGF1", CreatePssParams(sha224AlgId, 28));

            AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance);

            exParams.Add("SHA256WITHRSAANDMGF1", CreatePssParams(sha256AlgId, 32));

            AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance);

            exParams.Add("SHA384WITHRSAANDMGF1", CreatePssParams(sha384AlgId, 48));

            AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha512, DerNull.Instance);

            exParams.Add("SHA512WITHRSAANDMGF1", CreatePssParams(sha512AlgId, 64));
        }
Esempio n. 29
0
        /**
         * base constructor
         *
         * @param signedContent the content that was signed.
         * @param sigData the signature object.
         */
        public CmsSignedDataParser(
            CmsTypedStream signedContent,
            Stream sigData)
            : base(sigData)
        {
            try
            {
                this._signedContent = signedContent;
                this._signedData    = SignedDataParser.GetInstance(this.contentInfo.GetContent(Asn1Tags.Sequence));
                this._digests       = new Hashtable();

                Asn1SetParser    digAlgs = _signedData.GetDigestAlgorithms();
                IAsn1Convertible o;

                while ((o = digAlgs.ReadObject()) != null)
                {
                    AlgorithmIdentifier id = AlgorithmIdentifier.GetInstance(o.ToAsn1Object());

                    try
                    {
                        string  digestName = Helper.GetDigestAlgName(id.ObjectID.Id);
                        IDigest dig        = DigestUtilities.GetDigest(digestName);

                        this._digests[digestName] = dig;
                    }
                    catch (SecurityUtilityException)
                    {
                        //  ignore
                    }
                }

                if (_signedContent == null)
                {
                    //
                    // If the message is simply a certificate chain message GetContent() may return null.
                    //
                    Asn1OctetStringParser octs = (Asn1OctetStringParser)
                                                 _signedData.GetEncapContentInfo().GetContent(Asn1Tags.OctetString);

                    if (octs != null)
                    {
                        this._signedContent = new CmsTypedStream(octs.GetOctetStream());
                    }
                }
                else
                {
                    //
                    // content passed in, need to read past empty encapsulated content info object if present
                    //
                    Asn1OctetStringParser octs = (Asn1OctetStringParser)
                                                 _signedData.GetEncapContentInfo().GetContent(Asn1Tags.OctetString);

                    if (octs != null)
                    {
                        Stream inStream = octs.GetOctetStream();

                        while (inStream.ReadByte() >= 0)
                        {
                            // ignore
                        }
                    }
                }
            }
            catch (IOException e)
            {
                throw new CmsException("io exception: " + e.Message, e);
            }

            if (_digests.Count < 1)
            {
                throw new CmsException("no digests could be created for message.");
            }
        }
Esempio n. 30
0
 public Pkcs5Scheme2PbeKey(
     string password,
     AlgorithmIdentifier keyDerivationAlgorithm)
     : this(password.ToCharArray(), keyDerivationAlgorithm)
 {
 }
Esempio n. 31
0
 private PKMacValue(Asn1Sequence seq)
 {
     this.algID    = AlgorithmIdentifier.GetInstance(seq[0]);
     this.macValue = DerBitString.GetInstance(seq[1]);
 }
Esempio n. 32
0
 public void Decode(byte[] encodedMessage)
 {
     if (encodedMessage == null)
         throw new ArgumentNullException("encodedMessage");
     if (this.m_safeCryptMsgHandle != null && !this.m_safeCryptMsgHandle.IsInvalid)
         this.m_safeCryptMsgHandle.Dispose();
     this.m_safeCryptMsgHandle = EnvelopedCms.OpenToDecode(encodedMessage);
     this.m_version = (int)PkcsUtils.GetVersion(this.m_safeCryptMsgHandle);
     this.m_contentInfo = new ContentInfo(PkcsUtils.GetContentType(this.m_safeCryptMsgHandle), PkcsUtils.GetContent(this.m_safeCryptMsgHandle));
     this.m_encryptionAlgorithm = PkcsUtils.GetAlgorithmIdentifier(this.m_safeCryptMsgHandle);
     this.m_certificates = PkcsUtils.GetCertificates(this.m_safeCryptMsgHandle);
     this.m_unprotectedAttributes = PkcsUtils.GetUnprotectedAttributes(this.m_safeCryptMsgHandle);
 }
Esempio n. 33
0
        public virtual PkixCertPathValidatorResult Validate(
            PkixCertPath certPath,
            PkixParameters paramsPkix)
        {
            if (paramsPkix.GetTrustAnchors() == null)
            {
                throw new ArgumentException(
                          "trustAnchors is null, this is not allowed for certification path validation.",
                          "parameters");
            }

            //
            // 6.1.1 - inputs
            //

            //
            // (a)
            //
            IList certs = certPath.Certificates;
            int   n     = certs.Count;

            if (certs.Count == 0)
            {
                throw new PkixCertPathValidatorException("Certification path is empty.", null, certPath, 0);
            }

            //
            // (b)
            //
            // DateTime validDate = PkixCertPathValidatorUtilities.GetValidDate(paramsPkix);

            //
            // (c)
            //
            ISet userInitialPolicySet = paramsPkix.GetInitialPolicies();

            //
            // (d)
            //
            TrustAnchor trust;

            try
            {
                trust = PkixCertPathValidatorUtilities.FindTrustAnchor(
                    (X509Certificate)certs[certs.Count - 1],
                    paramsPkix.GetTrustAnchors());
            }
            catch (Exception e)
            {
                throw new PkixCertPathValidatorException(e.Message, e, certPath, certs.Count - 1);
            }

            if (trust == null)
            {
                throw new PkixCertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
            }

            //
            // (e), (f), (g) are part of the paramsPkix object.
            //
            IEnumerator certIter;
            int         index = 0;
            int         i;

            // Certificate for each interation of the validation loop
            // Signature information for each iteration of the validation loop
            //
            // 6.1.2 - setup
            //

            //
            // (a)
            //
            IList[] policyNodes = new IList[n + 1];
            for (int j = 0; j < policyNodes.Length; j++)
            {
                policyNodes[j] = Platform.CreateArrayList();
            }

            ISet policySet = new HashSet();

            policySet.Add(Rfc3280CertPathUtilities.ANY_POLICY);

            PkixPolicyNode validPolicyTree = new PkixPolicyNode(Platform.CreateArrayList(), 0, policySet, null, new HashSet(),
                                                                Rfc3280CertPathUtilities.ANY_POLICY, false);

            policyNodes[0].Add(validPolicyTree);

            //
            // (b) and (c)
            //
            PkixNameConstraintValidator nameConstraintValidator = new PkixNameConstraintValidator();

            // (d)
            //
            int  explicitPolicy;
            ISet acceptablePolicies = new HashSet();

            if (paramsPkix.IsExplicitPolicyRequired)
            {
                explicitPolicy = 0;
            }
            else
            {
                explicitPolicy = n + 1;
            }

            //
            // (e)
            //
            int inhibitAnyPolicy;

            if (paramsPkix.IsAnyPolicyInhibited)
            {
                inhibitAnyPolicy = 0;
            }
            else
            {
                inhibitAnyPolicy = n + 1;
            }

            //
            // (f)
            //
            int policyMapping;

            if (paramsPkix.IsPolicyMappingInhibited)
            {
                policyMapping = 0;
            }
            else
            {
                policyMapping = n + 1;
            }

            //
            // (g), (h), (i), (j)
            //
            AsymmetricKeyParameter workingPublicKey;
            X509Name workingIssuerName;

            X509Certificate sign = trust.TrustedCert;

            try
            {
                if (sign != null)
                {
                    workingIssuerName = sign.SubjectDN;
                    workingPublicKey  = sign.GetPublicKey();
                }
                else
                {
                    workingIssuerName = new X509Name(trust.CAName);
                    workingPublicKey  = trust.CAPublicKey;
                }
            }
            catch (ArgumentException ex)
            {
                throw new PkixCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath,
                                                         -1);
            }

            AlgorithmIdentifier workingAlgId = null;

            try
            {
                workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey);
            }
            catch (PkixCertPathValidatorException e)
            {
                throw new PkixCertPathValidatorException(
                          "Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
            }

//			DerObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.Algorithm;
//			Asn1Encodable workingPublicKeyParameters = workingAlgId.Parameters;

            //
            // (k)
            //
            int maxPathLength = n;

            //
            // 6.1.3
            //

            X509CertStoreSelector certConstraints = paramsPkix.GetTargetCertConstraints();

            if (certConstraints != null && !certConstraints.Match((X509Certificate)certs[0]))
            {
                throw new PkixCertPathValidatorException(
                          "Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
            }

            //
            // initialize CertPathChecker's
            //
            IList pathCheckers = paramsPkix.GetCertPathCheckers();

            certIter = pathCheckers.GetEnumerator();

            while (certIter.MoveNext())
            {
                ((PkixCertPathChecker)certIter.Current).Init(false);
            }

            X509Certificate cert = null;

            for (index = certs.Count - 1; index >= 0; index--)
            {
                // try
                // {
                //
                // i as defined in the algorithm description
                //
                i = n - index;

                //
                // set certificate to be checked in this round
                // sign and workingPublicKey and workingIssuerName are set
                // at the end of the for loop and initialized the
                // first time from the TrustAnchor
                //
                cert = (X509Certificate)certs[index];

                //
                // 6.1.3
                //

                Rfc3280CertPathUtilities.ProcessCertA(certPath, paramsPkix, index, workingPublicKey,
                                                      workingIssuerName, sign);

                Rfc3280CertPathUtilities.ProcessCertBC(certPath, index, nameConstraintValidator);

                validPolicyTree = Rfc3280CertPathUtilities.ProcessCertD(certPath, index,
                                                                        acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy);

                validPolicyTree = Rfc3280CertPathUtilities.ProcessCertE(certPath, index, validPolicyTree);

                Rfc3280CertPathUtilities.ProcessCertF(certPath, index, validPolicyTree, explicitPolicy);

                //
                // 6.1.4
                //

                if (i != n)
                {
                    if (cert != null && cert.Version == 1)
                    {
                        throw new PkixCertPathValidatorException(
                                  "Version 1 certificates can't be used as CA ones.", null, certPath, index);
                    }

                    Rfc3280CertPathUtilities.PrepareNextCertA(certPath, index);

                    validPolicyTree = Rfc3280CertPathUtilities.PrepareCertB(certPath, index, policyNodes,
                                                                            validPolicyTree, policyMapping);

                    Rfc3280CertPathUtilities.PrepareNextCertG(certPath, index, nameConstraintValidator);

                    // (h)
                    explicitPolicy   = Rfc3280CertPathUtilities.PrepareNextCertH1(certPath, index, explicitPolicy);
                    policyMapping    = Rfc3280CertPathUtilities.PrepareNextCertH2(certPath, index, policyMapping);
                    inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertH3(certPath, index, inhibitAnyPolicy);

                    //
                    // (i)
                    //
                    explicitPolicy = Rfc3280CertPathUtilities.PrepareNextCertI1(certPath, index, explicitPolicy);
                    policyMapping  = Rfc3280CertPathUtilities.PrepareNextCertI2(certPath, index, policyMapping);

                    // (j)
                    inhibitAnyPolicy = Rfc3280CertPathUtilities.PrepareNextCertJ(certPath, index, inhibitAnyPolicy);

                    // (k)
                    Rfc3280CertPathUtilities.PrepareNextCertK(certPath, index);

                    // (l)
                    maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertL(certPath, index, maxPathLength);

                    // (m)
                    maxPathLength = Rfc3280CertPathUtilities.PrepareNextCertM(certPath, index, maxPathLength);

                    // (n)
                    Rfc3280CertPathUtilities.PrepareNextCertN(certPath, index);

                    ISet criticalExtensions1 = cert.GetCriticalExtensionOids();

                    if (criticalExtensions1 != null)
                    {
                        criticalExtensions1 = new HashSet(criticalExtensions1);

                        // these extensions are handled by the algorithm
                        criticalExtensions1.Remove(X509Extensions.KeyUsage.Id);
                        criticalExtensions1.Remove(X509Extensions.CertificatePolicies.Id);
                        criticalExtensions1.Remove(X509Extensions.PolicyMappings.Id);
                        criticalExtensions1.Remove(X509Extensions.InhibitAnyPolicy.Id);
                        criticalExtensions1.Remove(X509Extensions.IssuingDistributionPoint.Id);
                        criticalExtensions1.Remove(X509Extensions.DeltaCrlIndicator.Id);
                        criticalExtensions1.Remove(X509Extensions.PolicyConstraints.Id);
                        criticalExtensions1.Remove(X509Extensions.BasicConstraints.Id);
                        criticalExtensions1.Remove(X509Extensions.SubjectAlternativeName.Id);
                        criticalExtensions1.Remove(X509Extensions.NameConstraints.Id);
                    }
                    else
                    {
                        criticalExtensions1 = new HashSet();
                    }

                    // (o)
                    Rfc3280CertPathUtilities.PrepareNextCertO(certPath, index, criticalExtensions1, pathCheckers);

                    // set signing certificate for next round
                    sign = cert;

                    // (c)
                    workingIssuerName = sign.SubjectDN;

                    // (d)
                    try
                    {
                        workingPublicKey = PkixCertPathValidatorUtilities.GetNextWorkingKey(certPath.Certificates, index);
                    }
                    catch (PkixCertPathValidatorException e)
                    {
                        throw new PkixCertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
                    }

                    workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey);
                    // (f)
//                    workingPublicKeyAlgorithm = workingAlgId.Algorithm;
                    // (e)
//                    workingPublicKeyParameters = workingAlgId.Parameters;
                }
            }

            //
            // 6.1.5 Wrap-up procedure
            //

            explicitPolicy = Rfc3280CertPathUtilities.WrapupCertA(explicitPolicy, cert);

            explicitPolicy = Rfc3280CertPathUtilities.WrapupCertB(certPath, index + 1, explicitPolicy);

            //
            // (c) (d) and (e) are already done
            //

            //
            // (f)
            //
            ISet criticalExtensions = cert.GetCriticalExtensionOids();

            if (criticalExtensions != null)
            {
                criticalExtensions = new HashSet(criticalExtensions);

                // Requires .Id
                // these extensions are handled by the algorithm
                criticalExtensions.Remove(X509Extensions.KeyUsage.Id);
                criticalExtensions.Remove(X509Extensions.CertificatePolicies.Id);
                criticalExtensions.Remove(X509Extensions.PolicyMappings.Id);
                criticalExtensions.Remove(X509Extensions.InhibitAnyPolicy.Id);
                criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id);
                criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id);
                criticalExtensions.Remove(X509Extensions.PolicyConstraints.Id);
                criticalExtensions.Remove(X509Extensions.BasicConstraints.Id);
                criticalExtensions.Remove(X509Extensions.SubjectAlternativeName.Id);
                criticalExtensions.Remove(X509Extensions.NameConstraints.Id);
                criticalExtensions.Remove(X509Extensions.CrlDistributionPoints.Id);
            }
            else
            {
                criticalExtensions = new HashSet();
            }

            Rfc3280CertPathUtilities.WrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);

            PkixPolicyNode intersection = Rfc3280CertPathUtilities.WrapupCertG(certPath, paramsPkix, userInitialPolicySet,
                                                                               index + 1, policyNodes, validPolicyTree, acceptablePolicies);

            if ((explicitPolicy > 0) || (intersection != null))
            {
                return(new PkixCertPathValidatorResult(trust, intersection, cert.GetPublicKey()));
            }

            throw new PkixCertPathValidatorException("Path processing failed on policy.", null, certPath, index);
        }
Esempio n. 34
0
 private static void SetCspParams(AlgorithmIdentifier contentEncryptionAlgorithm, ref EnvelopedCms.CMSG_ENCRYPT_PARAM encryptParam)
 {
     encryptParam.safeCryptProvHandle = SafeCryptProvHandle.InvalidHandle;
     encryptParam.pvEncryptionAuxInfo = SafeLocalAllocHandle.InvalidHandle;
     SafeCryptProvHandle invalidHandle = SafeCryptProvHandle.InvalidHandle;
     if (!CAPI.CryptAcquireContext(ref invalidHandle, IntPtr.Zero, IntPtr.Zero, 1U, 4026531840U))
         throw new CryptographicException(Marshal.GetLastWin32Error());
     uint algId = X509Utils.OidToAlgId(contentEncryptionAlgorithm.Oid.Value);
     switch (algId)
     {
         case 26114U:
         case 26625U:
             CAPI.CMSG_RC2_AUX_INFO cmsgRc2AuxInfo = new CAPI.CMSG_RC2_AUX_INFO(Marshal.SizeOf(typeof(CAPI.CMSG_RC2_AUX_INFO)));
             uint num = (uint)contentEncryptionAlgorithm.KeyLength;
             if ((int)num == 0)
                 num = (uint)PkcsUtils.GetMaxKeyLength(invalidHandle, algId);
             cmsgRc2AuxInfo.dwBitLen = num;
             SafeLocalAllocHandle localAllocHandle = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_RC2_AUX_INFO))));
             Marshal.StructureToPtr((object)cmsgRc2AuxInfo, localAllocHandle.DangerousGetHandle(), false);
             encryptParam.pvEncryptionAuxInfo = localAllocHandle;
             break;
     }
     encryptParam.safeCryptProvHandle = invalidHandle;
 }
Esempio n. 35
0
 private void Reset(uint originatorChoice, uint version, CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_INFO encryptedKeyInfo, uint subIndex)
 {
     this.m_encryptedKeyInfo = encryptedKeyInfo;
     this.m_originatorChoice = originatorChoice;
     this.m_version = (int)version;
     this.m_originatorIdentifier = (SubjectIdentifierOrKey)null;
     this.m_userKeyMaterial = new byte[0];
     this.m_encryptionAlgorithm = (AlgorithmIdentifier)null;
     this.m_recipientIdentifier = (SubjectIdentifier)null;
     this.m_encryptedKey = new byte[0];
     this.m_date = DateTime.MinValue;
     this.m_otherKeyAttribute = (CryptographicAttributeObject)null;
     this.m_subIndex = subIndex;
 }
	public EnvelopedCms(SubjectIdentifierType recipientIdentifierType, ContentInfo contentInfo, AlgorithmIdentifier encryptionAlgorithm) {}
Esempio n. 37
0
        public void Load(
            Stream input,
            char[] password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            Asn1Sequence obj             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          bag             = new Pfx(obj);
            ContentInfo  info            = bag.AuthSafe;
            bool         wrongPkcs12Zero = false;

            if (password != null && bag.MacData != null) // check the mac code
            {
                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

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

                byte[] mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, false, data);
                byte[] dig = dInfo.GetDigest();

                if (!Arrays.ConstantTimeAreEqual(mac, dig))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    // Try with incorrect zero length password
                    mac = CalculatePbeMac(algId.Algorithm, salt, itCount, password, true, data);

                    if (!Arrays.ConstantTimeAreEqual(mac, dig))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    wrongPkcs12Zero = true;
                }
            }

            keys.Clear();
            localIds.Clear();
            unmarkedKeyEntry = null;

            IList certBags = Platform.CreateArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octs     = ((Asn1OctetString)info.Content).GetOctets();
                AuthenticatedSafe authSafe = new AuthenticatedSafe(
                    (Asn1Sequence)Asn1OctetString.FromByteArray(octs));
                ContentInfo[] cis = authSafe.GetContentInfo();

                foreach (ContentInfo ci in cis)
                {
                    DerObjectIdentifier oid = ci.ContentType;

                    byte[] octets = null;
                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        octets = ((Asn1OctetString)ci.Content).GetOctets();
                    }
                    else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        if (password != null)
                        {
                            EncryptedData d = EncryptedData.GetInstance(ci.Content);
                            octets = CryptPbeData(false, d.EncryptionAlgorithm,
                                                  password, wrongPkcs12Zero, d.Content.GetOctets());
                        }
                    }
                    else
                    {
                        // TODO Other data types
                    }

                    if (octets != null)
                    {
                        Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                certBags.Add(b);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(b.BagValue),
                                                        b.BagAttributes, password, wrongPkcs12Zero);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                LoadKeyBag(PrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes);
                            }
                            else
                            {
                                // TODO Other bag types
                            }
                        }
                    }
                }
            }

            certs.Clear();
            chainCerts.Clear();
            keyCerts.Clear();

            foreach (SafeBag b in certBags)
            {
                CertBag         certBag = new CertBag((Asn1Sequence)b.BagValue);
                byte[]          octets  = ((Asn1OctetString)certBag.CertValue).GetOctets();
                X509Certificate cert    = new X509CertificateParser().ReadCertificate(octets);

                //
                // set the attributes
                //
                IDictionary     attributes = Platform.CreateHashtable();
                Asn1OctetString localId    = null;
                string          alias      = null;

                if (b.BagAttributes != null)
                {
                    foreach (Asn1Sequence sq in b.BagAttributes)
                    {
                        DerObjectIdentifier aOid    = DerObjectIdentifier.GetInstance(sq[0]);
                        Asn1Set             attrSet = Asn1Set.GetInstance(sq[1]);

                        if (attrSet.Count > 0)
                        {
                            // TODO We should be adding all attributes in the set
                            Asn1Encodable attr = attrSet[0];

                            // TODO We might want to "merge" attribute sets with
                            // the same OID - currently, differing values give an error
                            if (attributes.Contains(aOid.Id))
                            {
                                // OK, but the value has to be the same
                                if (!attributes[aOid.Id].Equals(attr))
                                {
                                    //throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                attributes.Add(aOid.Id, attr);
                            }

                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                alias = ((DerBmpString)attr).GetString();
                            }
                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                localId = (Asn1OctetString)attr;
                            }
                        }
                    }
                }

                CertId certId = new CertId(cert.GetPublicKey());
                X509CertificateEntry certEntry = new X509CertificateEntry(cert, attributes);

                chainCerts[certId] = certEntry;

                if (unmarkedKeyEntry != null)
                {
                    if (keyCerts.Count == 0)
                    {
                        string name = Hex.ToHexString(certId.Id);

                        keyCerts[name] = certEntry;
                        keys[name]     = unmarkedKeyEntry;
                    }
                    else
                    {
                        keys["unmarked"] = unmarkedKeyEntry;
                    }
                }
                else
                {
                    if (localId != null)
                    {
                        string name = Hex.ToHexString(localId.GetOctets());

                        keyCerts[name] = certEntry;
                    }

                    if (alias != null)
                    {
                        // TODO There may have been more than one alias
                        certs[alias] = certEntry;
                    }
                }
            }
        }
Esempio n. 38
0
 public SignerInfo(SignerIdentifier sid, AlgorithmIdentifier digAlgorithm, Attributes authenticatedAttributes, AlgorithmIdentifier digEncryptionAlgorithm, Asn1OctetString encryptedDigest, Attributes unauthenticatedAttributes)
 {
     version                        = new DerInteger((!sid.IsTagged) ? 1 : 3);
     this.sid                       = sid;
     this.digAlgorithm              = digAlgorithm;
     this.authenticatedAttributes   = Asn1Set.GetInstance(authenticatedAttributes);
     this.digEncryptionAlgorithm    = digEncryptionAlgorithm;
     this.encryptedDigest           = encryptedDigest;
     this.unauthenticatedAttributes = Asn1Set.GetInstance(unauthenticatedAttributes);
 }
        public static AsymmetricKeyParameter CreateKey(
            SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.AlgorithmID;
            DerObjectIdentifier algOid = algID.ObjectID;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(
                    keyInfo.GetPublicKey());

                return(new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.GetPublicKey());

                BigInteger y = dhPublicKey.Y.Value;

                if (IsPkcsDHParam(seq))
                {
                    return(ReadPkcsDHParam(algOid, y, seq));
                }

                DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq);

                BigInteger p = dhParams.P.Value;
                BigInteger g = dhParams.G.Value;
                BigInteger q = dhParams.Q.Value;

                BigInteger j = null;
                if (dhParams.J != null)
                {
                    j = dhParams.J.Value;
                }

                DHValidationParameters validation        = null;
                DHValidationParms      dhValidationParms = dhParams.ValidationParms;
                if (dhValidationParms != null)
                {
                    byte[]     seed        = dhValidationParms.Seed.GetBytes();
                    BigInteger pgenCounter = dhValidationParms.PgenCounter.Value;

                    // TODO Check pgenCounter size?

                    validation = new DHValidationParameters(seed, pgenCounter.IntValue);
                }

                return(new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation)));
            }
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object());

                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return(ReadPkcsDHParam(algOid, derY.Value, seq));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return(new ElGamalPublicKeyParameters(
                           derY.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) ||
                     algOid.Equals(OiwObjectIdentifiers.DsaWithSha1))
            {
                DerInteger    derY = (DerInteger)keyInfo.GetPublicKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPublicKeyParameters(derY.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object());

                X9ECParameters x9;
                if (para.IsNamedCurve)
                {
                    x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                Asn1OctetString key  = new DerOctetString(keyInfo.PublicKeyData.GetBytes());
                X9ECPoint       derQ = new X9ECPoint(x9.Curve, key);
                ECPoint         q    = derQ.Point;

                if (para.IsNamedCurve)
                {
                    return(new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters));
                }

                ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                return(new ECPublicKeyParameters(q, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                Asn1OctetString key;
                try
                {
                    key = (Asn1OctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc = key.GetOctets();
                byte[] x      = new byte[32];
                byte[] y      = new byte[32];

                for (int i = 0; i != y.Length; i++)
                {
                    x[i] = keyEnc[32 - 1 - i];
                }

                for (int i = 0; i != x.Length; i++)
                {
                    y[i] = keyEnc[64 - 1 - i];
                }

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    return(null);
                }

                ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y));

                return(new ECPublicKeyParameters("ECGOST3410", q, gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence)algID.Parameters);

                DerOctetString derY;
                try
                {
                    derY = (DerOctetString)keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc   = derY.GetOctets();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyEnc.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian
                }

                BigInteger y = new BigInteger(1, keyBytes);

                return(new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid);
            }
        }
	public EnvelopedCms(ContentInfo contentInfo, AlgorithmIdentifier encryptionAlgorithm) {}
Esempio n. 41
0
 public CompressedData(AlgorithmIdentifier compressionAlgorithm, ContentInfo encapContentInfo)
 {
     this.version = new DerInteger(0);
     this.compressionAlgorithm = compressionAlgorithm;
     this.encapContentInfo     = encapContentInfo;
 }
Esempio n. 42
0
 private void Reset(int version)
 {
     this.m_version = version;
     this.m_recipientIdentifier = (SubjectIdentifier)null;
     this.m_encryptionAlgorithm = (AlgorithmIdentifier)null;
     this.m_encryptedKey = new byte[0];
 }
Esempio n. 43
0
 public CompressedData(Asn1Sequence seq)
 {
     this.version = (DerInteger)seq[0];
     this.compressionAlgorithm = AlgorithmIdentifier.GetInstance(seq[1]);
     this.encapContentInfo     = ContentInfo.GetInstance(seq[2]);
 }