public DigestAlgorithmAndValueModel(DigestAlgorithm digest, byte[] value)
        {
            Value = value;
            if (value != null)
            {
                HexValue = string.Join("", value.Select(b => b.ToString("X2")));
            }

            if (digest == DigestAlgorithm.MD5)
            {
                Algorithm = DigestAlgorithms.MD5;
            }
            else if (digest == DigestAlgorithm.SHA1)
            {
                Algorithm = DigestAlgorithms.SHA1;
            }
            else if (digest == DigestAlgorithm.SHA256)
            {
                Algorithm = DigestAlgorithms.SHA256;
            }
            else if (digest == DigestAlgorithm.SHA384)
            {
                Algorithm = DigestAlgorithms.SHA384;
            }
            else if (digest == DigestAlgorithm.SHA512)
            {
                Algorithm = DigestAlgorithms.SHA512;
            }
        }
示例#2
0
 public SignatureAlgorithm(int id, ContentDigestAlgorithm contentDigestAlgorithm, string jcaKeyAlgorithm, DigestAlgorithm digestAlgorithm)
 {
     Id = id;
     JcaKeyAlgorithm        = jcaKeyAlgorithm;
     ContentDigestAlgorithm = contentDigestAlgorithm;
     DigestAlgorithm        = digestAlgorithm;
 }
示例#3
0
        /// <summary>
        /// Get the string name of the digest algorithm for use with the micalg parameter of a multipart/signed part.
        /// </summary>
        /// <remarks>
        /// <para>Maps the <see cref="DigestAlgorithm"/> to the appropriate string identifier
        /// as used by the micalg parameter value of a multipart/signed Content-Type
        /// header. For example:</para>
        /// <list type="table">
        /// <listheader><term>Algorithm</term><description>Name</description></listheader>
        /// <item><term><see cref="DigestAlgorithm.MD2"/></term><description>md2</description></item>
        /// <item><term><see cref="DigestAlgorithm.MD4"/></term><description>md4</description></item>
        /// <item><term><see cref="DigestAlgorithm.MD5"/></term><description>md5</description></item>
        /// <item><term><see cref="DigestAlgorithm.Sha1"/></term><description>sha-1</description></item>
        /// <item><term><see cref="DigestAlgorithm.Sha224"/></term><description>sha-224</description></item>
        /// <item><term><see cref="DigestAlgorithm.Sha256"/></term><description>sha-256</description></item>
        /// <item><term><see cref="DigestAlgorithm.Sha384"/></term><description>sha-384</description></item>
        /// <item><term><see cref="DigestAlgorithm.Sha512"/></term><description>sha-512</description></item>
        /// <item><term><see cref="DigestAlgorithm.Tiger192"/></term><description>tiger-192</description></item>
        /// <item><term><see cref="DigestAlgorithm.RipeMD160"/></term><description>ripemd160</description></item>
        /// <item><term><see cref="DigestAlgorithm.Haval5160"/></term><description>haval-5-160</description></item>
        /// </list>
        /// </remarks>
        /// <returns>The micalg value.</returns>
        /// <param name="micalg">The digest algorithm.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="micalg"/> is out of range.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
        /// </exception>
        public override string GetDigestAlgorithmName(DigestAlgorithm micalg)
        {
            switch (micalg)
            {
            case DigestAlgorithm.MD5:        return("md5");

            case DigestAlgorithm.Sha1:       return("sha-1");

            case DigestAlgorithm.RipeMD160:  return("ripemd160");

            case DigestAlgorithm.MD2:        return("md2");

            case DigestAlgorithm.Tiger192:   return("tiger192");

            case DigestAlgorithm.Haval5160:  return("haval-5-160");

            case DigestAlgorithm.Sha256:     return("sha-256");

            case DigestAlgorithm.Sha384:     return("sha-384");

            case DigestAlgorithm.Sha512:     return("sha-512");

            case DigestAlgorithm.Sha224:     return("sha-224");

            case DigestAlgorithm.MD4:        return("md4");

            case DigestAlgorithm.DoubleSha:
                throw new NotSupportedException(string.Format("{0} is not supported.", micalg));

            default:
                throw new ArgumentOutOfRangeException(nameof(micalg), micalg, string.Format("Unknown DigestAlgorithm: {0}", micalg));
            }
        }
示例#4
0
        /// <summary>
        /// Gets the <see cref="CmsSigner"/> for the specified mailbox.
        /// </summary>
        /// <returns>A <see cref="CmsSigner"/>.</returns>
        /// <param name="mailbox">The mailbox.</param>
        /// <param name="digestAlgo">The preferred digest algorithm.</param>
        /// <exception cref="CertificateNotFoundException">
        /// A certificate for the specified <paramref name="mailbox"/> could not be found.
        /// </exception>
        protected override CmsSigner GetCmsSigner(MailboxAddress mailbox, DigestAlgorithm digestAlgo)
        {
            var now = DateTime.Now;

            foreach (var certificate in certificates)
            {
                AsymmetricKeyParameter key;

                if (certificate.NotBefore > now || certificate.NotAfter < now)
                {
                    continue;
                }

                var keyUsage = certificate.GetKeyUsageFlags();
                if (keyUsage != 0 && (keyUsage & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0)
                {
                    continue;
                }

                if (!keys.TryGetValue(certificate, out key))
                {
                    continue;
                }

                if (certificate.GetSubjectEmailAddress() == mailbox.Address)
                {
                    var signer = new CmsSigner(certificate, key);
                    signer.DigestAlgorithm = digestAlgo;
                    return(signer);
                }
            }

            throw new CertificateNotFoundException(mailbox, "A valid signing certificate could not be found.");
        }
示例#5
0
 /// <summary>
 /// Initializes an instance, specifying the encryption and digest algorithm to use.
 /// </summary>
 /// <param name="encryptionAlgorithm">The <see cref="EncryptionAlgorithm"/> to use in this cryptographer</param>
 /// <param name="digestAlgorithm">The <see cref="DigestAlgorithm"/> to use in this cryptographer</param>
 public SMIMECryptographer(EncryptionAlgorithm encryptionAlgorithm, DigestAlgorithm digestAlgorithm)
 {
     EncryptionAlgorithm = encryptionAlgorithm;
     DigestAlgorithm     = digestAlgorithm;
     IncludeMultipartEpilogueInSignature = true;
     IncludeCertChainInSignature         = X509IncludeOption.EndCertOnly;
 }
示例#6
0
        /// <summary>
        /// Gets the string name of the digest algorithm for use with the micalg parameter of a multipart/signed part.
        /// </summary>
        /// <returns>The micalg value.</returns>
        /// <param name="micalg">The digest algorithm.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="micalg"/> is out of range.
        /// </exception>
        public override string GetMicAlgorithmName(DigestAlgorithm micalg)
        {
            switch (micalg)
            {
            case DigestAlgorithm.MD5:        return("md5");

            case DigestAlgorithm.Sha1:       return("sha1");

            case DigestAlgorithm.RipeMD160:  return("ripemd160");

            case DigestAlgorithm.MD2:        return("md2");

            case DigestAlgorithm.Tiger192:   return("tiger192");

            case DigestAlgorithm.Haval5160:  return("haval-5-160");

            case DigestAlgorithm.Sha256:     return("sha256");

            case DigestAlgorithm.Sha384:     return("sha384");

            case DigestAlgorithm.Sha512:     return("sha512");

            case DigestAlgorithm.Sha224:     return("sha224");

            case DigestAlgorithm.MD4:        return("md4");

            default: throw new ArgumentOutOfRangeException("micalg");
            }
        }
示例#7
0
        protected static string GetOid(DigestAlgorithm digestAlgo)
        {
            switch (digestAlgo)
            {
            case DigestAlgorithm.MD5:        return(PkcsObjectIdentifiers.MD5.Id);

            case DigestAlgorithm.Sha1:       return(PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id);

            case DigestAlgorithm.MD2:        return(PkcsObjectIdentifiers.MD2.Id);

            case DigestAlgorithm.Sha256:     return(PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id);

            case DigestAlgorithm.Sha384:     return(PkcsObjectIdentifiers.Sha384WithRsaEncryption.Id);

            case DigestAlgorithm.Sha512:     return(PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id);

            case DigestAlgorithm.Sha224:     return(PkcsObjectIdentifiers.Sha224WithRsaEncryption.Id);

            case DigestAlgorithm.MD4:        return(PkcsObjectIdentifiers.MD4.Id);

            case DigestAlgorithm.RipeMD160:
            case DigestAlgorithm.DoubleSha:
            case DigestAlgorithm.Tiger192:
            case DigestAlgorithm.Haval5160:
                throw new NotSupportedException();

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#8
0
        /// <summary>
        /// Gets the <see cref="CmsSigner"/> for the specified mailbox.
        /// </summary>
        /// <remarks>
        /// <para>Constructs a <see cref="CmsSigner"/> with the appropriate signing certificate
        /// for the specified mailbox.</para>
        /// <para>If the mailbox is a <see cref="SecureMailboxAddress"/>, the
        /// <see cref="SecureMailboxAddress.Fingerprint"/> property will be used instead of
        /// the mailbox address for database lookups.</para>
        /// </remarks>
        /// <returns>A <see cref="CmsSigner"/>.</returns>
        /// <param name="mailbox">The signer's mailbox address.</param>
        /// <param name="digestAlgo">The preferred digest algorithm.</param>
        /// <exception cref="CertificateNotFoundException">
        /// A certificate for the specified <paramref name="mailbox"/> could not be found.
        /// </exception>
        protected override CmsSigner GetCmsSigner(MailboxAddress mailbox, DigestAlgorithm digestAlgo)
        {
            AsymmetricKeyParameter privateKey  = null;
            X509Certificate        certificate = null;

            foreach (var record in dbase.Find(mailbox, DateTime.UtcNow, true, CmsSignerFields))
            {
                if (record.KeyUsage != X509KeyUsageFlags.None && (record.KeyUsage & DigitalSignatureKeyUsageFlags) == 0)
                {
                    continue;
                }

                certificate = record.Certificate;
                privateKey  = record.PrivateKey;
                break;
            }

            if (certificate != null && privateKey != null)
            {
                var signer = new CmsSigner(BuildCertificateChain(certificate), privateKey);
                signer.DigestAlgorithm = digestAlgo;

                return(signer);
            }

            throw new CertificateNotFoundException(mailbox, "A valid signing certificate could not be found.");
        }
示例#9
0
        /// <summary>
        /// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>.
        /// </summary>
        /// <returns>The cms signer.</returns>
        /// <param name="mailbox">The mailbox.</param>
        /// <param name="digestAlgo">The preferred digest algorithm.</param>
        /// <exception cref="CertificateNotFoundException">
        /// A certificate for the specified <paramref name="mailbox"/> could not be found.
        /// </exception>
        protected override CmsSigner GetCmsSigner(MailboxAddress mailbox, DigestAlgorithm digestAlgo)
        {
            var certificates = CertificateStore.Certificates;            //.Find (X509FindType.FindByKeyUsage, flags, true);

            foreach (var certificate in certificates)
            {
                if (certificate.GetNameInfo(X509NameType.EmailName, false) != mailbox.Address)
                {
                    continue;
                }

                if (!certificate.HasPrivateKey)
                {
                    continue;
                }

                var pair   = DotNetUtilities.GetKeyPair(certificate.PrivateKey);
                var cert   = DotNetUtilities.FromX509Certificate(certificate);
                var signer = new CmsSigner(cert, pair.Private);
                signer.DigestAlgorithm = digestAlgo;

                return(signer);
            }

            throw new CertificateNotFoundException(mailbox, "A valid signing certificate could not be found.");
        }
        public DefaultApkSignerEngine(X509Certificate2 certificate, int minSdkVersion, bool v1SigningEnabled,
                                      bool v2SigningEnabled, DigestAlgorithm digestAlgorithm)
        {
            _v1SigningEnabled   = v1SigningEnabled;
            _v2SigningEnabled   = v2SigningEnabled;
            _v1SignaturePending = v1SigningEnabled;
            _v2SignaturePending = v2SigningEnabled;

            if (v1SigningEnabled)
            {
                var v1SignerName = V1SchemeSigner.GetSafeSignerName(certificate.FriendlyName);
                // Check whether the signer's name is unique among all v1 signers
                var v1SignatureDigestAlgorithm = digestAlgorithm ??
                                                 V1SchemeSigner.GetSuggestedSignatureDigestAlgorithm(
                    certificate.PublicKey, minSdkVersion);
                var v1SignerConfig = new V1SchemeSigner.SignerConfig();
                v1SignerConfig.Name        = v1SignerName;
                v1SignerConfig.Certificate = certificate;
                v1SignerConfig.SignatureDigestAlgorithm = v1SignatureDigestAlgorithm;

                _v1SignerConfigs                      = v1SignerConfig;
                _v1ContentDigestAlgorithm             = v1SignatureDigestAlgorithm;
                _signatureExpectedOutputJarEntryNames = V1SchemeSigner.GetOutputEntryNames(_v1SignerConfigs, minSdkVersion);

                _v1ContentDigestAlgorithm = V1SchemeSigner.GetSuggestedSignatureDigestAlgorithm(certificate.PublicKey, minSdkVersion);
            }

            if (v2SigningEnabled)
            {
                var v2SignerConfig = new V2SchemeSigner.SignerConfig();
                v2SignerConfig.Certificates       = certificate;
                v2SignerConfig.SignatureAlgorithm = V2SchemeSigner.GetSuggestedSignatureAlgorithms(certificate.PublicKey, minSdkVersion, digestAlgorithm);
                _v2SignerConfigs = v2SignerConfig;
            }
        }
示例#11
0
        internal static bool TryGetDigestAlgorithm(string id, out DigestAlgorithm algorithm)
        {
            if (id == CmsSignedGenerator.DigestSha1)
            {
                algorithm = DigestAlgorithm.Sha1;
                return(true);
            }

            if (id == CmsSignedGenerator.DigestSha224)
            {
                algorithm = DigestAlgorithm.Sha224;
                return(true);
            }

            if (id == CmsSignedGenerator.DigestSha256)
            {
                algorithm = DigestAlgorithm.Sha256;
                return(true);
            }

            if (id == CmsSignedGenerator.DigestSha384)
            {
                algorithm = DigestAlgorithm.Sha384;
                return(true);
            }

            if (id == CmsSignedGenerator.DigestSha512)
            {
                algorithm = DigestAlgorithm.Sha512;
                return(true);
            }

            if (id == CmsSignedGenerator.DigestRipeMD160)
            {
                algorithm = DigestAlgorithm.RipeMD160;
                return(true);
            }

            if (id == CmsSignedGenerator.DigestMD5)
            {
                algorithm = DigestAlgorithm.MD5;
                return(true);
            }

            if (id == PkcsObjectIdentifiers.MD4.Id)
            {
                algorithm = DigestAlgorithm.MD4;
                return(true);
            }

            if (id == PkcsObjectIdentifiers.MD2.Id)
            {
                algorithm = DigestAlgorithm.MD2;
                return(true);
            }

            algorithm = DigestAlgorithm.None;

            return(false);
        }
        /// <summary>
        /// Signs the provided APK using JAR signing (aka v1 signature scheme) and returns the list of
        /// JAR entries which need to be added to the APK as part of the signature.
        /// </summary>
        /// <param name="signerConfig"></param>
        /// <param name="digestAlgorithm"></param>
        /// <param name="apkSigningSchemeIds"></param>
        /// <param name="manifest"></param>
        /// <returns></returns>
        public static List <Tuple <string, byte[]> > SignManifest(SignerConfig signerConfig,
                                                                  DigestAlgorithm digestAlgorithm, IList <int> apkSigningSchemeIds, OutputManifestFile manifest)
        {
            // For each signer output .SF and .(RSA|DSA|EC) file, then output MANIFEST.MF.
            var signatureJarEntries =
                new List <Tuple <string, byte[]> >(2 * 1 + 1);
            var sfBytes        = GenerateSignatureFile(apkSigningSchemeIds, digestAlgorithm, manifest);
            var signerName     = signerConfig.Name;
            var signatureBlock = GenerateSignatureBlock(signerConfig, sfBytes);

            signatureJarEntries.Add(Tuple.Create("META-INF/" + signerName + ".SF", sfBytes));

            var publicKey = signerConfig.Certificate.PublicKey;
            var signatureBlockFileName =
                "META-INF/" + signerName + ".";

            if (publicKey.Key is RSACryptoServiceProvider)
            {
                signatureBlockFileName += "RSA";
            }
            else if (publicKey.Key is DSACryptoServiceProvider)
            {
                signatureBlockFileName += "DSA";
            }

            signatureJarEntries.Add(
                Tuple.Create(signatureBlockFileName, signatureBlock));
            signatureJarEntries.Add(Tuple.Create(ManifestEntryName, manifest.Contents));
            return(signatureJarEntries);
        }
示例#13
0
        Stream Sign(Certificate certificate, IList <Certificate> chain, DigestAlgorithm digestAlgo, Stream content, bool detach)
        {
            var signerInfo = new CmsSignerInfo();
            var signers    = new CmsSignerInfo[1];

            byte[]  signedData;
            IBuffer buffer;

            signerInfo.HashAlgorithmName = GetHashAlgorithmName(digestAlgo);
            signerInfo.Certificate       = certificate;
            signers[0] = signerInfo;

            if (detach)
            {
                using (var input = content.AsInputStream())
                    buffer = CmsDetachedSignature.GenerateSignatureAsync(input, signers, chain).GetResults();
            }
            else
            {
                buffer = CryptographicBuffer.CreateFromByteArray(ReadAllBytes(content));
                buffer = CmsAttachedSignature.GenerateSignatureAsync(buffer, signers, chain).GetResults();
            }

            CryptographicBuffer.CopyToByteArray(buffer, out signedData);

            return(new MemoryStream(signedData, false));
        }
示例#14
0
        /// <summary>
        /// Returns implementation of specified digest algorithm
        /// </summary>
        /// <param name="algorithm">Digest algorithm</param>
        /// <returns>Implementation of specified digest algorithm</returns>
        private static IDigest GetHashGenerator(DigestAlgorithm algorithm)
        {
            IDigest digest;

            switch (algorithm)
            {
            default:
                throw new NotSupportedException("Unsupported hash algorithm");

            case DigestAlgorithm.SHA1:
                digest = new Sha1Digest();
                break;

            case DigestAlgorithm.SHA256:
                digest = new Sha256Digest();
                break;

            case DigestAlgorithm.SHA384:
                digest = new Sha384Digest();
                break;

            case DigestAlgorithm.SHA512:
                digest = new Sha512Digest(); break;
            }

            return(digest);
        }
示例#15
0
        /// <summary>
        /// Get the OID for the digest algorithm.
        /// </summary>
        /// <remarks>
        /// Gets the OID for the digest algorithm.
        /// </remarks>
        /// <returns>The digest oid.</returns>
        /// <param name="digestAlgo">The digest algorithm.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="digestAlgo"/> is out of range.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
        /// </exception>
        internal protected static string GetDigestOid(DigestAlgorithm digestAlgo)
        {
            switch (digestAlgo)
            {
            case DigestAlgorithm.MD5:        return(CmsSignedGenerator.DigestMD5);

            case DigestAlgorithm.Sha1:       return(CmsSignedGenerator.DigestSha1);

            case DigestAlgorithm.MD2:        return(PkcsObjectIdentifiers.MD2.Id);

            case DigestAlgorithm.Sha256:     return(CmsSignedGenerator.DigestSha256);

            case DigestAlgorithm.Sha384:     return(CmsSignedGenerator.DigestSha384);

            case DigestAlgorithm.Sha512:     return(CmsSignedGenerator.DigestSha512);

            case DigestAlgorithm.Sha224:     return(CmsSignedGenerator.DigestSha224);

            case DigestAlgorithm.MD4:        return(PkcsObjectIdentifiers.MD4.Id);

            case DigestAlgorithm.RipeMD160:  return(CmsSignedGenerator.DigestRipeMD160);

            case DigestAlgorithm.DoubleSha:
            case DigestAlgorithm.Tiger192:
            case DigestAlgorithm.Haval5160:
                throw new NotSupportedException(string.Format("{0} is not supported.", digestAlgo));

            default:
                throw new ArgumentOutOfRangeException(nameof(digestAlgo), digestAlgo, string.Format("Unknown DigestAlgorithm: {0}", digestAlgo));
            }
        }
 internal AsymmetricSphincsKey(Algorithm algorithm, Sphincs256KeyParams parameters)
 {
     this.approvedModeOnly = CryptoServicesRegistrar.IsInApprovedOnlyMode();
     this.algorithm        = algorithm;
     this.parameters       = parameters;
     this.treeAlgorithm    = parameters.TreeDigest.Algorithm.Equals(NistObjectIdentifiers.IdSha3_256) ? FipsShs.Sha3_256 : FipsShs.Sha512_256;
 }
示例#17
0
 /// <summary>
 /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the
 /// provided.
 /// </summary>
 /// <remarks>
 /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the
 /// provided. The hashing is performed by the method using the specified algorithm and a BouncyCastle provider.
 /// </remarks>
 /// <param name="signedData"></param>
 /// <exception cref="System.Exception">System.Exception</exception>
 protected internal virtual BcCms.Attribute GetTimeStampAttribute(DerObjectIdentifier oid
                                                                  , ITspSource tsa, AlgorithmIdentifier digestAlgorithm, byte[] messageImprint)
 {
     try
     {
         //jbonilla Hack para obtener el digest del TSA
         IDigest digest        = null;
         string  algorithmName = null;
         digest        = DigestUtilities.GetDigest(DigestAlgorithm.SHA1.GetName());
         algorithmName = DigestAlgorithm.SHA1.GetName();
         digest.BlockUpdate(messageImprint, 0, messageImprint.Length);
         byte[] r = new byte[digest.GetDigestSize()];
         digest.DoFinal(r, 0);
         byte[]            toTimeStamp = r;
         TimeStampResponse tsresp      = tsa.GetTimeStampResponse(DigestAlgorithm.GetByName(algorithmName)
                                                                  , toTimeStamp);
         TimeStampToken tstoken = tsresp.TimeStampToken;
         if (tstoken == null)
         {
             throw new ArgumentNullException("The TimeStampToken returned for the signature time stamp was empty."
                                             );
         }
         BcCms.Attribute signatureTimeStamp = new BcCms.Attribute(oid, new DerSet(Asn1Object.FromByteArray
                                                                                      (tstoken.GetEncoded())));
         return(signatureTimeStamp);
     }
     catch (IOException e)
     {
         throw new RuntimeException(e);
     }
     catch (NoSuchAlgorithmException e)
     {
         throw new RuntimeException(e);
     }
 }
示例#18
0
        /// <summary>
        /// Create the ContentType MIME header for a Signed MIME entity
        /// </summary>
        /// <param name="digestAlgorithm">Digest algorithm being used, such as SHA1</param>
        /// <returns>ContentType header</returns>
        public static ContentType CreateContentType(DigestAlgorithm digestAlgorithm)
        {
            ContentType contentType = new ContentType(SMIMEStandard.MultiPartTypeSigned);

            contentType.Parameters.Add(SMIMEStandard.ProtocolParameterKey, SMIMEStandard.SignatureProtocol);
            contentType.Parameters.Add(SMIMEStandard.MICAlgorithmKey, SMIMEStandard.ToString(digestAlgorithm));
            return(contentType);
        }
示例#19
0
 internal PbkdParameters(DigestAlgorithm digestAlgorithm, PasswordConverter converter, byte[] password, int iterationCount, byte[] salt) : base(ALGORITHM_PKCS12)
 {
     this.digestAlgorithm = digestAlgorithm;
     this.converter       = converter;
     this.password        = password;
     this.iterationCount  = iterationCount;
     this.salt            = salt;
 }
示例#20
0
 internal Pkcs12DeriverBuilder(byte[] password, PasswordConverter converter, DigestAlgorithm digestAlgorithm, byte[] salt, int iterationCount)
 {
     this.digestAlgorithm = digestAlgorithm;
     this.converter       = converter;
     this.password        = password;
     this.iterationCount  = iterationCount;
     this.salt            = salt;
 }
        RealCmsSigner GetRealCmsSigner(MailboxAddress mailbox, DigestAlgorithm digestAlgo)
        {
            var signer = new RealCmsSigner(GetCmsSignerCertificate(mailbox));

            signer.DigestAlgorithm = new Oid(GetDigestOid(digestAlgo));
            signer.IncludeOption   = X509IncludeOption.ExcludeRoot;
            return(signer);
        }
示例#22
0
		RealCmsSigner GetRealCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo)
		{
			var signer = new RealCmsSigner (GetCmsSignerCertificate (mailbox));
			signer.DigestAlgorithm = new Oid (GetDigestOid (digestAlgo));
			signer.SignedAttributes.Add (new Pkcs9SigningTime ());
			signer.IncludeOption = X509IncludeOption.ExcludeRoot;
			return signer;
		}
示例#23
0
        /// <summary>
        /// Verify the Data packet using the digest algorithm. This does not check the
        /// digest algorithm against the type of SignatureInfo in the Data packet such
        /// as DigestSha256Signature.
        /// </summary>
        ///
        /// <param name="data">The Data packet to verify.</param>
        /// <param name="digestAlgorithm">The digest algorithm, such as DigestAlgorithm.SHA256.</param>
        /// <param name="wireFormat">A WireFormat object used to encode the Data packet.</param>
        /// <returns>True if verification succeeds, false if verification fails.</returns>
        /// <exception cref="System.ArgumentException">for an invalid digestAlgorithm.</exception>
        public static bool verifyDataDigest(Data data,
                                            DigestAlgorithm digestAlgorithm, WireFormat wireFormat)
        {
            SignedBlob encoding = data.wireEncode(wireFormat);

            return(verifyDigest(encoding.signedBuf(), data.getSignature()
                                .getSignature(), digestAlgorithm));
        }
示例#24
0
        public static IDigest GetDigest(
            string algorithm)
        {
            //TODO: SUSTITUIDO
            //string upper = algorithm.ToUpper(CultureInfo.InvariantCulture);
            string upper     = algorithm.ToUpper();
            string mechanism = (string)algorithms[upper];

            if (mechanism == null)
            {
                mechanism = upper;
            }

            try
            {
                DigestAlgorithm digestAlgorithm = (DigestAlgorithm)Enums.GetEnumValue(
                    typeof(DigestAlgorithm), mechanism);

                switch (digestAlgorithm)
                {
                case DigestAlgorithm.GOST3411:  return(new Gost3411Digest());

                case DigestAlgorithm.MD2:               return(new MD2Digest());

                case DigestAlgorithm.MD4:               return(new MD4Digest());

                case DigestAlgorithm.MD5:               return(new MD5Digest());

                case DigestAlgorithm.RIPEMD128: return(new RipeMD128Digest());

                case DigestAlgorithm.RIPEMD160: return(new RipeMD160Digest());

                case DigestAlgorithm.RIPEMD256: return(new RipeMD256Digest());

                case DigestAlgorithm.RIPEMD320: return(new RipeMD320Digest());

                case DigestAlgorithm.SHA_1:             return(new Sha1Digest());

                case DigestAlgorithm.SHA_224:   return(new Sha224Digest());

                case DigestAlgorithm.SHA_256:   return(new Sha256Digest());

                case DigestAlgorithm.SHA_384:   return(new Sha384Digest());

                case DigestAlgorithm.SHA_512:   return(new Sha512Digest());

                case DigestAlgorithm.TIGER:             return(new TigerDigest());

                case DigestAlgorithm.WHIRLPOOL: return(new WhirlpoolDigest());
                }
            }
            catch (ArgumentException)
            {
            }

            throw new SecurityUtilityException("Digest " + mechanism + " not recognised.");
        }
示例#25
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (Name != null)
         {
             hashCode = hashCode * 59 + Name.GetHashCode();
         }
         if (Type != null)
         {
             hashCode = hashCode * 59 + Type.GetHashCode();
         }
         if (FormatTarget != null)
         {
             hashCode = hashCode * 59 + FormatTarget.GetHashCode();
         }
         if (TempFsFolder != null)
         {
             hashCode = hashCode * 59 + TempFsFolder.GetHashCode();
         }
         if (FileThreshold != null)
         {
             hashCode = hashCode * 59 + FileThreshold.GetHashCode();
         }
         if (MemoryUnit != null)
         {
             hashCode = hashCode * 59 + MemoryUnit.GetHashCode();
         }
         if (UseOffHeapMemory != null)
         {
             hashCode = hashCode * 59 + UseOffHeapMemory.GetHashCode();
         }
         if (DigestAlgorithm != null)
         {
             hashCode = hashCode * 59 + DigestAlgorithm.GetHashCode();
         }
         if (MonitoringQueueSize != null)
         {
             hashCode = hashCode * 59 + MonitoringQueueSize.GetHashCode();
         }
         if (CleanupDelay != null)
         {
             hashCode = hashCode * 59 + CleanupDelay.GetHashCode();
         }
         if (PackageFilters != null)
         {
             hashCode = hashCode * 59 + PackageFilters.GetHashCode();
         }
         if (PropertyFilters != null)
         {
             hashCode = hashCode * 59 + PropertyFilters.GetHashCode();
         }
         return(hashCode);
     }
 }
示例#26
0
		/// <summary>
		/// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>.
		/// </summary>
		/// <remarks>
		/// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>.
		/// </remarks>
		/// <returns>The cms signer.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <param name="digestAlgo">The preferred digest algorithm.</param>
		/// <exception cref="CertificateNotFoundException">
		/// A certificate for the specified <paramref name="mailbox"/> could not be found.
		/// </exception>
		protected override CmsSigner GetCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo)
		{
			var certificate = GetCmsSignerCertificate (mailbox);
			var pair = DotNetUtilities.GetKeyPair (certificate.PrivateKey);
			var cert = DotNetUtilities.FromX509Certificate (certificate);
			var signer = new CmsSigner (cert, pair.Private);
			signer.DigestAlgorithm = digestAlgo;
			return signer;
		}
示例#27
0
 /// <summary>
 /// Verify the Data packet using the public key. This does not check the
 /// type of public key or digest algorithm against the type of SignatureInfo in
 /// the Data packet such as Sha256WithRsaSignature.
 /// If the public key can't be decoded, this returns false instead of throwing
 /// a decoding exception. If you want to get a decoding exception then use
 /// the PublicKey constructor to decode and call verifyDataSignature with the
 /// PublicKey object.
 /// </summary>
 ///
 /// <param name="data">The Data packet to verify.</param>
 /// <param name="publicKeyDer">The DER-encoded public key.</param>
 /// <param name="digestAlgorithm">The digest algorithm.</param>
 /// <param name="wireFormat">A WireFormat object used to encode the Data packet.</param>
 /// <returns>True if verification succeeds, false if verification fails or for
 /// an error decoding the public key.</returns>
 /// <exception cref="System.ArgumentException">for an invalid public key type ordigestAlgorithm.</exception>
 public static bool verifyDataSignature(Data data, Blob publicKeyDer,
                                        DigestAlgorithm digestAlgorithm, WireFormat wireFormat)
 {
     try {
         return(verifyDataSignature(data, new PublicKey(publicKeyDer),
                                    digestAlgorithm));
     } catch (UnrecognizedKeyFormatException ex) {
         return(false);
     }
 }
示例#28
0
 /// <summary>
 /// Create a SafeBag with given private key and a new self-signed certificate
 /// for the given public key.
 /// Use getDefaultWireFormat() to encode the self-signed certificate in order
 /// to sign it.
 /// </summary>
 ///
 /// <param name="keyName">This copies the Name.</param>
 /// <param name="privateKeyBag">PKCS #8 PrivateKeyInfo.</param>
 /// <param name="publicKeyEncoding">The encoded public key for the certificate.</param>
 /// <param name="password">of 1 to 127. If the password is supplied, use it to decrypt the PKCS #8 EncryptedPrivateKeyInfo. If the password is null, privateKeyBag is an unencrypted PKCS #8 PrivateKeyInfo.</param>
 /// <param name="digestAlgorithm"></param>
 public SafeBag(Name keyName, Blob privateKeyBag, Blob publicKeyEncoding,
                ByteBuffer password, DigestAlgorithm digestAlgorithm)
 {
     this.certificate_   = null;
     this.privateKeyBag_ = new Blob();
     certificate_        = makeSelfSignedCertificate(keyName, privateKeyBag,
                                                     publicKeyEncoding, password, digestAlgorithm,
                                                     net.named_data.jndn.encoding.WireFormat.getDefaultWireFormat());
     privateKeyBag_ = privateKeyBag;
 }
        /// <summary>
        /// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>.
        /// </summary>
        /// <remarks>
        /// Gets the cms signer for the specified <see cref="MimeKit.MailboxAddress"/>.
        /// </remarks>
        /// <returns>The cms signer.</returns>
        /// <param name="mailbox">The mailbox.</param>
        /// <param name="digestAlgo">The preferred digest algorithm.</param>
        /// <exception cref="CertificateNotFoundException">
        /// A certificate for the specified <paramref name="mailbox"/> could not be found.
        /// </exception>
        protected override CmsSigner GetCmsSigner(MailboxAddress mailbox, DigestAlgorithm digestAlgo)
        {
            var certificate = GetCmsSignerCertificate(mailbox);
            var pair        = CmsSigner.GetBouncyCastleKeyPair(certificate.PrivateKey);
            var cert        = GetBouncyCastleCertificate(certificate);
            var signer      = new CmsSigner(cert, pair.Private);

            signer.DigestAlgorithm = digestAlgo;
            return(signer);
        }
示例#30
0
 /// <summary>
 /// Create a SafeBag with given private key and a new self-signed certificate
 /// for the given public key.
 /// </summary>
 ///
 /// <param name="keyName">This copies the Name.</param>
 /// <param name="privateKeyBag">PKCS #8 PrivateKeyInfo.</param>
 /// <param name="publicKeyEncoding">The encoded public key for the certificate.</param>
 /// <param name="password">of 1 to 127. If the password is supplied, use it to decrypt the PKCS #8 EncryptedPrivateKeyInfo. If the password is null, privateKeyBag is an unencrypted PKCS #8 PrivateKeyInfo.</param>
 /// <param name="digestAlgorithm"></param>
 /// <param name="wireFormat"></param>
 public SafeBag(Name keyName, Blob privateKeyBag, Blob publicKeyEncoding,
                ByteBuffer password, DigestAlgorithm digestAlgorithm,
                WireFormat wireFormat)
 {
     this.certificate_   = null;
     this.privateKeyBag_ = new Blob();
     certificate_        = makeSelfSignedCertificate(keyName, privateKeyBag,
                                                     publicKeyEncoding, password, digestAlgorithm, wireFormat);
     privateKeyBag_ = privateKeyBag;
 }
示例#31
0
 /// <summary>
 /// Creates an entity consisting of the content and signature.
 /// </summary>
 /// <param name="algorithm">The digest algorithm used in the signature, used for the <c>micalg</c> parameter</param>
 /// <param name="content">The content entity that was signed.</param>
 /// <param name="signature">The signature entity</param>
 public SignedEntity(DigestAlgorithm algorithm, MimeEntity content, MimeEntity signature)
     : base(CreateContentType(algorithm))
 {
     if (content == null)
     {
         throw new ArgumentNullException("content");
     }
     
     Content = content;
     Signature = signature;
 }
示例#32
0
 public void TestSignatureOIDs(DigestAlgorithm algo)
 {
     string messageText = m_tester.ReadMessageText("simple.eml");
     m_cryptographer.DigestAlgorithm = algo;
     SignedCms signedData = null;
     
     Assert.DoesNotThrow(() => signedData = m_cryptographer.CreateSignature(Encoding.ASCII.GetBytes(messageText), m_cert)); 
     
     Assert.True(signedData.SignerInfos.Count == 1);
     Assert.True(signedData.SignerInfos[0].DigestAlgorithm.Value == SMIMECryptographer.ToDigestAlgorithmOid(algo).Value);
 }
		public virtual TlsCipher CreateCipher(TlsClientContext context,
			EncryptionAlgorithm encryptionAlgorithm, DigestAlgorithm digestAlgorithm)
		{
			switch (encryptionAlgorithm)
			{
				case EncryptionAlgorithm.cls_3DES_EDE_CBC:
					return CreateDesEdeCipher(context, 24, digestAlgorithm);
				case EncryptionAlgorithm.AES_128_CBC:
					return CreateAesCipher(context, 16, digestAlgorithm);
				case EncryptionAlgorithm.AES_256_CBC:
					return CreateAesCipher(context, 32, digestAlgorithm);
				default:
					throw new TlsFatalAlert(AlertDescription.internal_error);
			}
		}
		/// <exception cref="IOException"></exception>
		protected virtual IDigest CreateDigest(DigestAlgorithm digestAlgorithm)
		{
			switch (digestAlgorithm)
			{
				case DigestAlgorithm.MD5:
					return new MD5Digest();
				case DigestAlgorithm.SHA:
					return new Sha1Digest();
				case DigestAlgorithm.SHA256:
					return new Sha256Digest();
				case DigestAlgorithm.SHA384:
					return new Sha384Digest();
				default:
					throw new TlsFatalAlert(AlertDescription.internal_error);
			}
		}
 /// <exception cref="Sharpen.NoSuchAlgorithmException"></exception>
 /// <exception cref="System.IO.IOException"></exception>
 public virtual byte[] Sign(Stream stream, DigestAlgorithm digestAlgo, IDssPrivateKeyEntry
      keyEntry)
 {
     if (SignatureAlgorithm.RSA == keyEntry.GetSignatureAlgorithm())
     {
         IDigest digester = DigestUtilities.GetDigest(digestAlgo.GetName());
         byte[] buffer = new byte[4096];
         int count = 0;
         while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
         {
             digester.BlockUpdate(buffer, 0, count);
         }
         byte[] digestValue = DigestUtilities.DoFinal(digester);
         return EncryptDigest(digestValue, digestAlgo, keyEntry);
     }
     else
     {
         //jbonilla
         throw new System.NotImplementedException("Implementar cuando no es RSA");
         //Sharpen.Signature signature = Sharpen.Signature.GetInstance(keyEntry.GetSignatureAlgorithm
         //    ().GetJavaSignatureAlgorithm(digestAlgo));
         //try
         //{
         //    signature.InitSign(((KSPrivateKeyEntry)keyEntry).GetPrivateKey());
         //    byte[] buffer = new byte[4096];
         //    int count = 0;
         //    while ((count = stream.Read(buffer)) > 0)
         //    {
         //        signature.Update(buffer, 0, count);
         //    }
         //    byte[] signValue = signature.Sign();
         //    return signValue;
         //}
         //catch (SignatureException e)
         //{
         //    throw new RuntimeException(e);
         //}
         //catch (InvalidKeyException e)
         //{
         //    throw new RuntimeException(e);
         //}
     }
 }
示例#36
0
        /// <summary>
        /// Sign and encapsulate the content using the specified signer.
        /// </summary>
        /// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> instance
        /// containing the detached signature data.</returns>
        /// <param name="signer">The signer.</param>
        /// <param name="digestAlgo">The digest algorithm to use for signing.</param>
        /// <param name="content">The content.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="signer"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="content"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="digestAlgo"/> is out of range.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
        /// </exception>
        /// <exception cref="CertificateNotFoundException">
        /// A signing certificate could not be found for <paramref name="signer"/>.
        /// </exception>
        /// <exception cref="Org.BouncyCastle.Cms.CmsException">
        /// An error occurred in the cryptographic message syntax subsystem.
        /// </exception>
        public virtual ApplicationPkcs7Mime EncapsulatedSign(MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
        {
            if (signer == null)
                throw new ArgumentNullException ("signer");

            if (content == null)
                throw new ArgumentNullException ("content");

            var cmsSigner = GetCmsSigner (signer, digestAlgo);

            return EncapsulatedSign (cmsSigner, content);
        }
示例#37
0
 /// <summary>
 /// Gets the string name of the digest algorithm for use with the micalg parameter of a multipart/signed part.
 /// </summary>
 /// <returns>The micalg value.</returns>
 /// <param name="micalg">The digest algorithm.</param>
 /// <exception cref="System.ArgumentOutOfRangeException">
 /// <paramref name="micalg"/> is out of range.
 /// </exception>
 public override string GetMicAlgorithmName(DigestAlgorithm micalg)
 {
     switch (micalg) {
     case DigestAlgorithm.MD5:        return "md5";
     case DigestAlgorithm.Sha1:       return "sha1";
     case DigestAlgorithm.RipeMD160:  return "ripemd160";
     case DigestAlgorithm.MD2:        return "md2";
     case DigestAlgorithm.Tiger192:   return "tiger192";
     case DigestAlgorithm.Haval5160:  return "haval-5-160";
     case DigestAlgorithm.Sha256:     return "sha256";
     case DigestAlgorithm.Sha384:     return "sha384";
     case DigestAlgorithm.Sha512:     return "sha512";
     case DigestAlgorithm.Sha224:     return "sha224";
     case DigestAlgorithm.MD4:        return "md4";
     default: throw new ArgumentOutOfRangeException ("micalg");
     }
 }
示例#38
0
 public Digest(DigestAlgorithm algorithm, byte[] value)
     : base()
 {
     this.algorithm = algorithm;
     this.value = value;
 }
示例#39
0
 /// <param name="algorithm">the algorithm to set</param>
 public virtual void SetAlgorithm(DigestAlgorithm algorithm)
 {
     this.algorithm = algorithm;
 }
示例#40
0
		/// <summary>
		/// Creates a new <see cref="MultipartEncrypted"/>.
		/// </summary>
		/// <remarks>
		/// Signs the entity using the supplied signer and digest algorithm and then encrypts to
		/// the specified recipients, encapsulating the result in a new multipart/encrypted part.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing
		/// the signed and encrypted version of the specified entity.</returns>
		/// <param name="ctx">The OpenPGP cryptography context to use for singing and encrypting.</param>
		/// <param name="signer">The signer to use to sign the entity.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="recipients">The recipients for the encrypted entity.</param>
		/// <param name="entity">The entity to sign and encrypt.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="ctx"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="recipients"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="entity"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="signer"/> cannot be used for signing.</para>
		/// <para>-or-</para>
		/// <para>One or more of the recipient keys cannot be used for encrypting.</para>
		/// <para>-or-</para>
		/// <para>No recipients were specified.</para>
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// The <paramref name="digestAlgo"/> was out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The <paramref name="digestAlgo"/> is not supported.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public static MultipartEncrypted Create (OpenPgpContext ctx, PgpSecretKey signer, DigestAlgorithm digestAlgo, IEnumerable<PgpPublicKey> recipients, MimeEntity entity)
		{
			if (ctx == null)
				throw new ArgumentNullException ("ctx");

			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (recipients == null)
				throw new ArgumentNullException ("recipients");

			if (entity == null)
				throw new ArgumentNullException ("entity");

			using (var memory = new MemoryStream ()) {
				var options = FormatOptions.Default.Clone ();
				options.NewLineFormat = NewLineFormat.Dos;

				PrepareEntityForEncrypting (entity);
				entity.WriteTo (options, memory);
				memory.Position = 0;

				var encrypted = new MultipartEncrypted ();
				encrypted.ContentType.Parameters["protocol"] = ctx.EncryptionProtocol;

				// add the protocol version part
				encrypted.Add (new ApplicationPgpEncrypted ());

				// add the encrypted entity as the second part
				encrypted.Add (ctx.SignAndEncrypt (signer, digestAlgo, recipients, memory));

				return encrypted;
			}
		}
		/// <summary>
		/// Cryptographically signs and encrypts the specified content for the specified recipients.
		/// </summary>
		/// <remarks>
		/// Cryptographically signs and encrypts the specified content for the specified recipients.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.MimePart"/> instance
		/// containing the encrypted data.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="recipients">The recipients.</param>
		/// <param name="content">The content.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="recipients"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="content"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="digestAlgo"/> is out of range.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para>One or more of the recipient keys cannot be used for encrypting.</para>
		/// <para>-or-</para>
		/// <para>No recipients were specified.</para>
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// The private key could not be found for <paramref name="signer"/>.
		/// </exception>
		/// <exception cref="PublicKeyNotFoundException">
		/// A public key could not be found for one or more of the <paramref name="recipients"/>.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public MimePart SignAndEncrypt (MailboxAddress signer, DigestAlgorithm digestAlgo, IEnumerable<MailboxAddress> recipients, Stream content)
		{
			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (recipients == null)
				throw new ArgumentNullException ("recipients");

			if (content == null)
				throw new ArgumentNullException ("content");

			var key = GetSigningKey (signer);

			return SignAndEncrypt (key, digestAlgo, GetPublicKeys (recipients), content);
		}
示例#42
0
		/// <summary>
		/// Gets the <see cref="CmsSigner"/> for the specified mailbox.
		/// </summary>
		/// <returns>A <see cref="CmsSigner"/>.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <param name="digestAlgo">The preferred digest algorithm.</param>
		/// <exception cref="CertificateNotFoundException">
		/// A certificate for the specified <paramref name="mailbox"/> could not be found.
		/// </exception>
		protected override CmsSigner GetCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo)
		{
			var now = DateTime.Now;

			foreach (var certificate in certificates) {
				AsymmetricKeyParameter key;

				if (certificate.NotBefore > now || certificate.NotAfter < now)
					continue;

				var keyUsage = certificate.GetKeyUsageFlags ();
				if (keyUsage != 0 && (keyUsage & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0)
					continue;

				if (!keys.TryGetValue (certificate, out key))
					continue;

				if (certificate.GetSubjectEmailAddress () == mailbox.Address) {
					var signer = new CmsSigner (certificate, key);
					signer.DigestAlgorithm = digestAlgo;
					return signer;
				}
			}

			throw new CertificateNotFoundException (mailbox, "A valid signing certificate could not be found.");
		}
示例#43
0
 /// <summary>
 /// Gets the <see cref="CmsSigner"/> for the specified mailbox.
 /// </summary>
 /// <returns>A <see cref="CmsSigner"/>.</returns>
 /// <param name="mailbox">The mailbox.</param>
 /// <param name="digestAlgo">The preferred digest algorithm.</param>
 /// <exception cref="CertificateNotFoundException">
 /// A certificate for the specified <paramref name="mailbox"/> could not be found.
 /// </exception>
 protected abstract CmsSigner GetCmsSigner(MailboxAddress mailbox, DigestAlgorithm digestAlgo);
 /// <exception cref="IOException"></exception>
 protected virtual TlsCipher CreateRC4Cipher(TlsClientContext context, int cipherKeySize, DigestAlgorithm digestAlgorithm)
 {
     return new TlsStreamCipher(context, CreateRC4StreamCipher(), CreateRC4StreamCipher(), CreateDigest(digestAlgorithm), CreateDigest(digestAlgorithm), cipherKeySize);
 }
		/// <summary>
		/// Cryptographically signs the content.
		/// </summary>
		/// <remarks>
		/// Cryptographically signs the content using the specified signer and digest algorithm.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.MimePart"/> instance
		/// containing the detached signature data.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="content">The content.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="content"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="signer"/> cannot be used for signing.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// The <paramref name="digestAlgo"/> was out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The <paramref name="digestAlgo"/> is not supported.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public ApplicationPgpSignature Sign (PgpSecretKey signer, DigestAlgorithm digestAlgo, Stream content)
		{
			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (!signer.IsSigningKey)
				throw new ArgumentException ("The specified secret key cannot be used for signing.", "signer");

			if (content == null)
				throw new ArgumentNullException ("content");

			var hashAlgorithm = GetHashAlgorithm (digestAlgo);
			var memory = new MemoryBlockStream ();

			using (var armored = new ArmoredOutputStream (memory)) {
				var compresser = new PgpCompressedDataGenerator (CompressionAlgorithmTag.ZLib);
				using (var compressed = compresser.Open (armored)) {
					var signatureGenerator = new PgpSignatureGenerator (signer.PublicKey.Algorithm, hashAlgorithm);
					var buf = new byte[4096];
					int nread;

					signatureGenerator.InitSign (PgpSignature.CanonicalTextDocument, GetPrivateKey (signer));

					while ((nread = content.Read (buf, 0, buf.Length)) > 0)
						signatureGenerator.Update (buf, 0, nread);

					var signature = signatureGenerator.Generate ();

					signature.Encode (compressed);
					compressed.Flush ();
				}

				armored.Flush ();
			}

			memory.Position = 0;

			return new ApplicationPgpSignature (memory);
		}
示例#46
0
		/// <summary>
		/// Creates a new <see cref="MultipartSigned"/>.
		/// </summary>
		/// <remarks>
		/// Cryptographically signs the entity using the supplied signer and digest algorithm in
		/// order to generate a detached signature and then adds the entity along with the
		/// detached signature data to a new multipart/signed part.
		/// </remarks>
		/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="entity">The entity to sign.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="entity"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="signer"/> cannot be used for signing.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// The <paramref name="digestAlgo"/> was out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// <para>A cryptography context suitable for signing could not be found.</para>
		/// <para>-or-</para>
		/// <para>The <paramref name="digestAlgo"/> is not supported.</para>
		/// </exception>
		/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
		/// An error occurred in the OpenPGP subsystem.
		/// </exception>
		public static MultipartSigned Create (PgpSecretKey signer, DigestAlgorithm digestAlgo, MimeEntity entity)
		{
			using (var ctx = (OpenPgpContext) CryptographyContext.Create ("application/pgp-signature")) {
				return Create (ctx, signer, digestAlgo, entity);
			}
		}
示例#47
0
		/// <summary>
		/// Creates a new <see cref="MultipartSigned"/>.
		/// </summary>
		/// <remarks>
		/// Cryptographically signs the entity using the supplied signer and digest algorithm in
		/// order to generate a detached signature and then adds the entity along with the
		/// detached signature data to a new multipart/signed part.
		/// </remarks>
		/// <returns>A new <see cref="MultipartSigned"/> instance.</returns>
		/// <param name="ctx">The OpenPGP context to use for signing.</param>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="entity">The entity to sign.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="ctx"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="entity"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="signer"/> cannot be used for signing.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// The <paramref name="digestAlgo"/> was out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The <paramref name="digestAlgo"/> is not supported.
		/// </exception>
		/// <exception cref="Org.BouncyCastle.Bcpg.OpenPgp.PgpException">
		/// An error occurred in the OpenPGP subsystem.
		/// </exception>
		public static MultipartSigned Create (OpenPgpContext ctx, PgpSecretKey signer, DigestAlgorithm digestAlgo, MimeEntity entity)
		{
			if (ctx == null)
				throw new ArgumentNullException ("ctx");

			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (entity == null)
				throw new ArgumentNullException ("entity");

			PrepareEntityForSigning (entity);

			using (var memory = new MemoryBlockStream ()) {
				using (var filtered = new FilteredStream (memory)) {
					// Note: see rfc3156, section 3 - second note
					filtered.Add (new ArmoredFromFilter ());

					// Note: see rfc3156, section 5.4 (this is the main difference between rfc2015 and rfc3156)
					filtered.Add (new TrailingWhitespaceFilter ());

					// Note: see rfc2015 or rfc3156, section 5.1
					filtered.Add (new Unix2DosFilter ());

					entity.WriteTo (filtered);
					filtered.Flush ();
				}

				memory.Position = 0;

				// Note: we need to parse the modified entity structure to preserve any modifications
				var parser = new MimeParser (memory, MimeFormat.Entity);
				var parsed = parser.ParseEntity ();
				memory.Position = 0;

				// sign the cleartext content
				var micalg = ctx.GetDigestAlgorithmName (digestAlgo);
				var signature = ctx.Sign (signer, digestAlgo, memory);
				var signed = new MultipartSigned ();

				// set the protocol and micalg Content-Type parameters
				signed.ContentType.Parameters["protocol"] = ctx.SignatureProtocol;
				signed.ContentType.Parameters["micalg"] = micalg;

				// add the modified/parsed entity as our first part
				signed.Add (parsed);

				// add the detached signature as the second part
				signed.Add (signature);

				return signed;
			}
		}
		/// <summary>
		/// Sign the content using the specified signer.
		/// </summary>
		/// <remarks>
		/// Sign the content using the specified signer.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.MimePart"/> instance
		/// containing the detached signature data.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="content">The content.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="content"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="digestAlgo"/> is out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
		/// </exception>
		/// <exception cref="CertificateNotFoundException">
		/// A signing certificate could not be found for <paramref name="signer"/>.
		/// </exception>
		/// <exception cref="System.Security.Cryptography.CryptographicException">
		/// An error occurred in the cryptographic message syntax subsystem.
		/// </exception>
		public override MimePart Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
		{
			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (content == null)
				throw new ArgumentNullException ("content");

			var contentInfo = new ContentInfo (ReadAllBytes (content));
			var cmsSigner = GetRealCmsSigner (signer, digestAlgo);
			var signed = new SignedCms (contentInfo, true);
			signed.ComputeSignature (cmsSigner);
			var signedData = signed.Encode ();

			return new ApplicationPkcs7Signature (new MemoryStream (signedData, false));
		}
示例#49
0
        /// <summary>
        /// Sign the content using the specified signer.
        /// </summary>
        /// <returns>A new <see cref="MimeKit.MimePart"/> instance
        /// containing the detached signature data.</returns>
        /// <param name="signer">The signer.</param>
        /// <param name="digestAlgo">The digest algorithm to use for signing.</param>
        /// <param name="content">The content.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="signer"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="content"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="digestAlgo"/> is out of range.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
        /// </exception>
        /// <exception cref="CertificateNotFoundException">
        /// A signing certificate could not be found for <paramref name="signer"/>.
        /// </exception>
        /// <exception cref="Org.BouncyCastle.Cms.CmsException">
        /// An error occurred in the cryptographic message syntax subsystem.
        /// </exception>
        public override MimePart Sign(MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
        {
            if (signer == null)
                throw new ArgumentNullException ("signer");

            if (content == null)
                throw new ArgumentNullException ("content");

            var cmsSigner = GetCmsSigner (signer, digestAlgo);

            return Sign (cmsSigner, content);
        }
		/// <summary>
		/// Cryptographically signs and encrypts the specified content for the specified recipients.
		/// </summary>
		/// <remarks>
		/// Cryptographically signs and encrypts the specified content for the specified recipients.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.MimePart"/> instance
		/// containing the encrypted data.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="cipherAlgo">The encryption algorithm.</param>
		/// <param name="recipients">The recipients.</param>
		/// <param name="content">The content.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="recipients"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="content"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="signer"/> cannot be used for signing.</para>
		/// <para>-or-</para>
		/// <para>One or more of the recipient keys cannot be used for encrypting.</para>
		/// <para>-or-</para>
		/// <para>No recipients were specified.</para>
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The specified encryption algorithm is not supported.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public MimePart SignAndEncrypt (PgpSecretKey signer, DigestAlgorithm digestAlgo, EncryptionAlgorithm cipherAlgo, IEnumerable<PgpPublicKey> recipients, Stream content)
		{
			// TODO: document the exceptions that can be thrown by BouncyCastle

			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (!signer.IsSigningKey)
				throw new ArgumentException ("The specified secret key cannot be used for signing.", "signer");

			if (recipients == null)
				throw new ArgumentNullException ("recipients");

			if (content == null)
				throw new ArgumentNullException ("content");

			var encrypter = new PgpEncryptedDataGenerator (GetSymmetricKeyAlgorithm (cipherAlgo), true);
			var hashAlgorithm = GetHashAlgorithm (digestAlgo);
			int count = 0;

			foreach (var recipient in recipients) {
				if (!recipient.IsEncryptionKey)
					throw new ArgumentException ("One or more of the recipient keys cannot be used for encrypting.", "recipients");

				encrypter.AddMethod (recipient);
				count++;
			}

			if (count == 0)
				throw new ArgumentException ("No recipients specified.", "recipients");

			var compresser = new PgpCompressedDataGenerator (CompressionAlgorithmTag.ZLib);

			using (var compressed = new MemoryBlockStream ()) {
				using (var signed = compresser.Open (compressed)) {
					var signatureGenerator = new PgpSignatureGenerator (signer.PublicKey.Algorithm, hashAlgorithm);
					signatureGenerator.InitSign (PgpSignature.CanonicalTextDocument, GetPrivateKey (signer));
					var subpacket = new PgpSignatureSubpacketGenerator ();

					foreach (string userId in signer.PublicKey.GetUserIds ()) {
						subpacket.SetSignerUserId (false, userId);
						break;
					}

					signatureGenerator.SetHashedSubpackets (subpacket.Generate ());

					var onepass = signatureGenerator.GenerateOnePassVersion (false);
					onepass.Encode (signed);

					var literalGenerator = new PgpLiteralDataGenerator ();
					using (var literal = literalGenerator.Open (signed, 't', "mime.txt", content.Length, DateTime.Now)) {
						var buf = new byte[4096];
						int nread;

						while ((nread = content.Read (buf, 0, buf.Length)) > 0) {
							signatureGenerator.Update (buf, 0, nread);
							literal.Write (buf, 0, nread);
						}

						literal.Flush ();
					}

					var signature = signatureGenerator.Generate ();
					signature.Encode (signed);

					signed.Flush ();
				}

				compressed.Position = 0;

				var memory = new MemoryBlockStream ();
				using (var armored = new ArmoredOutputStream (memory)) {
					using (var encrypted = encrypter.Open (armored, compressed.Length)) {
						compressed.CopyTo (encrypted, 4096);
						encrypted.Flush ();
					}

					armored.Flush ();
				}

				memory.Position = 0;

				return new MimePart ("application", "octet-stream") {
					ContentDisposition = new ContentDisposition ("attachment"),
					ContentObject = new ContentObject (memory)
				};
			}
		}
示例#51
0
 /// <summary>
 /// Gets the digest oid.
 /// </summary>
 /// <returns>The digest oid.</returns>
 /// <param name="digestAlgo">The digest algorithm.</param>
 /// <exception cref="System.ArgumentOutOfRangeException">
 /// <paramref name="digestAlgo"/> is out of range.
 /// </exception>
 /// <exception cref="System.NotSupportedException">
 /// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
 /// </exception>
 protected static string GetDigestOid(DigestAlgorithm digestAlgo)
 {
     switch (digestAlgo) {
     case DigestAlgorithm.MD5:        return PkcsObjectIdentifiers.MD5.Id;
     case DigestAlgorithm.Sha1:       return PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id;
     case DigestAlgorithm.MD2:        return PkcsObjectIdentifiers.MD2.Id;
     case DigestAlgorithm.Sha256:     return PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id;
     case DigestAlgorithm.Sha384:     return PkcsObjectIdentifiers.Sha384WithRsaEncryption.Id;
     case DigestAlgorithm.Sha512:     return PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id;
     case DigestAlgorithm.Sha224:     return PkcsObjectIdentifiers.Sha224WithRsaEncryption.Id;
     case DigestAlgorithm.MD4:        return PkcsObjectIdentifiers.MD4.Id;
     case DigestAlgorithm.RipeMD160:
     case DigestAlgorithm.DoubleSha:
     case DigestAlgorithm.Tiger192:
     case DigestAlgorithm.Haval5160:
         throw new NotSupportedException ();
     default:
         throw new ArgumentOutOfRangeException ();
     }
 }
示例#52
0
		/// <summary>
		/// Sign the message using the specified cryptography context and digest algorithm.
		/// </summary>
		/// <remarks>
		/// If either of the Resent-Sender or Resent-From headers are set, then the message
		/// will be signed using the Resent-Sender (or first mailbox in the Resent-From)
		/// address as the signer address, otherwise the Sender or From address will be
		/// used instead.
		/// </remarks>
		/// <param name="ctx">The cryptography context.</param>
		/// <param name="digestAlgo">The digest algorithm.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="ctx"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// <para>The <see cref="Body"/> has not been set.</para>
		/// <para>-or-</para>
		/// <para>A sender has not been specified.</para>
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// The <paramref name="digestAlgo"/> was out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The <paramref name="digestAlgo"/> is not supported.
		/// </exception>
		/// <exception cref="CertificateNotFoundException">
		/// A signing certificate could not be found for the sender.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// The private key could not be found for the sender.
		/// </exception>
		public void Sign (CryptographyContext ctx, DigestAlgorithm digestAlgo)
		{
			if (ctx == null)
				throw new ArgumentNullException ("ctx");

			if (Body == null)
				throw new InvalidOperationException ("No message body has been set.");

			var signer = GetMessageSigner ();
			if (signer == null)
				throw new InvalidOperationException ("The sender has not been set.");

			Body = MultipartSigned.Create (ctx, signer, digestAlgo, Body);
		}
		/// <summary>
		/// Cryptographically signs and encrypts the specified content for the specified recipients.
		/// </summary>
		/// <remarks>
		/// Cryptographically signs and encrypts the specified content for the specified recipients.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.MimePart"/> instance
		/// containing the encrypted data.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="recipients">The recipients.</param>
		/// <param name="content">The content.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="recipients"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="content"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="signer"/> cannot be used for signing.</para>
		/// <para>-or-</para>
		/// <para>One or more of the recipient keys cannot be used for encrypting.</para>
		/// <para>-or-</para>
		/// <para>No recipients were specified.</para>
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public MimePart SignAndEncrypt (PgpSecretKey signer, DigestAlgorithm digestAlgo, IEnumerable<PgpPublicKey> recipients, Stream content)
		{
			return SignAndEncrypt (signer, digestAlgo, defaultAlgorithm, recipients, content);
		}
示例#54
0
		/// <summary>
		/// Sign and encrypt the message to the sender and all of the recipients using
		/// the specified cryptography context and the specified digest algorithm.
		/// </summary>
		/// <remarks>
		/// <para>If either of the Resent-Sender or Resent-From headers are set, then the message
		/// will be signed using the Resent-Sender (or first mailbox in the Resent-From)
		/// address as the signer address, otherwise the Sender or From address will be
		/// used instead.</para>
		/// <para>Likewise, if either of the Resent-Sender or Resent-From headers are set, then the
		/// message will be encrypted to all of the addresses specified in the Resent headers
		/// (Resent-Sender, Resent-From, Resent-To, Resent-Cc, and Resent-Bcc),
		/// otherwise the message will be encrypted to all of the addresses specified in
		/// the standard address headers (Sender, From, To, Cc, and Bcc).</para>
		/// </remarks>
		/// <param name="ctx">The cryptography context.</param>
		/// <param name="digestAlgo">The digest algorithm.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="ctx"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// An unknown type of cryptography context was used.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// The <paramref name="digestAlgo"/> was out of range.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// <para>The <see cref="Body"/> has not been set.</para>
		/// <para>-or-</para>
		/// <para>The sender has been specified.</para>
		/// <para>-or-</para>
		/// <para>No recipients have been specified.</para>
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The <paramref name="digestAlgo"/> is not supported.
		/// </exception>
		/// <exception cref="CertificateNotFoundException">
		/// A certificate could not be found for the signer or one or more of the recipients.
		/// </exception>
		/// <exception cref="PrivateKeyNotFoundException">
		/// The private key could not be found for the sender.
		/// </exception>
		/// <exception cref="PublicKeyNotFoundException">
		/// The public key could not be found for one or more of the recipients.
		/// </exception>
		public void SignAndEncrypt (CryptographyContext ctx, DigestAlgorithm digestAlgo)
		{
			if (ctx == null)
				throw new ArgumentNullException ("ctx");

			if (Body == null)
				throw new InvalidOperationException ("No message body has been set.");

			var signer = GetMessageSigner ();
			if (signer == null)
				throw new InvalidOperationException ("The sender has not been set.");

			var recipients = GetMessageRecipients (true);
			if (recipients.Count == 0)
				throw new InvalidOperationException ("No recipients have been set.");

			if (ctx is SecureMimeContext) {
				Body = ApplicationPkcs7Mime.SignAndEncrypt ((SecureMimeContext) ctx, signer, digestAlgo, recipients, Body);
			} else if (ctx is OpenPgpContext) {
				Body = MultipartEncrypted.SignAndEncrypt ((OpenPgpContext) ctx, signer, digestAlgo, recipients, Body);
			} else {
				throw new ArgumentException ("Unknown type of cryptography context.", "ctx");
			}
		}
 /// <summary>The encryption of a digest it the atomic operation done by the SSCD.</summary>
 /// <remarks>
 /// The encryption of a digest it the atomic operation done by the SSCD. This encryption (RSA, DSA, ...) create the
 /// signature value.
 /// </remarks>
 /// <param name="digestValue"></param>
 /// <param name="digestAlgo"></param>
 /// <param name="keyEntry"></param>
 /// <returns></returns>
 /// <exception cref="Sharpen.NoSuchAlgorithmException"></exception>
 public abstract byte[] EncryptDigest(byte[] digestValue, DigestAlgorithm digestAlgo
     , IDssPrivateKeyEntry keyEntry);
		/// <exception cref="IOException"></exception>
		protected virtual TlsCipher CreateDesEdeCipher(TlsClientContext context, int cipherKeySize,
			DigestAlgorithm digestAlgorithm)
		{
			return new TlsBlockCipher(context, CreateDesEdeBlockCipher(), CreateDesEdeBlockCipher(),
				CreateDigest(digestAlgorithm), CreateDigest(digestAlgorithm), cipherKeySize);
		}
示例#57
0
		/// <summary>
		/// Creates a new <see cref="MultipartEncrypted"/>.
		/// </summary>
		/// <remarks>
		/// Signs the entity using the supplied signer and digest algorithm and then encrypts to
		/// the specified recipients, encapsulating the result in a new multipart/encrypted part.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.Cryptography.MultipartEncrypted"/> instance containing
		/// the signed and encrypted version of the specified entity.</returns>
		/// <param name="signer">The signer to use to sign the entity.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="recipients">The recipients for the encrypted entity.</param>
		/// <param name="entity">The entity to sign and encrypt.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="recipients"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="entity"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="signer"/> cannot be used for signing.</para>
		/// <para>-or-</para>
		/// <para>One or more of the recipient keys cannot be used for encrypting.</para>
		/// <para>-or-</para>
		/// <para>No recipients were specified.</para>
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// The <paramref name="digestAlgo"/> was out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// <para>A default <see cref="OpenPgpContext"/> has not been registered.</para>
		/// <para>-or-</para>
		/// <para>The <paramref name="digestAlgo"/> is not supported.</para>
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The user chose to cancel the password prompt.
		/// </exception>
		/// <exception cref="System.UnauthorizedAccessException">
		/// 3 bad attempts were made to unlock the secret key.
		/// </exception>
		public static MultipartEncrypted Create (PgpSecretKey signer, DigestAlgorithm digestAlgo, IEnumerable<PgpPublicKey> recipients, MimeEntity entity)
		{
			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (recipients == null)
				throw new ArgumentNullException ("recipients");

			if (entity == null)
				throw new ArgumentNullException ("entity");

			using (var ctx = (OpenPgpContext) CryptographyContext.Create ("application/pgp-encrypted")) {
				return Create (ctx, signer, digestAlgo, recipients, entity);
			}
		}
		/// <summary>
		/// Gets the equivalent <see cref="Org.BouncyCastle.Bcpg.HashAlgorithmTag"/> for the 
		/// specified <see cref="DigestAlgorithm"/>. 
		/// </summary>
		/// <remarks>
		/// Maps a <see cref="DigestAlgorithm"/> to the equivalent <see cref="Org.BouncyCastle.Bcpg.HashAlgorithmTag"/>.
		/// </remarks>
		/// <returns>The hash algorithm.</returns>
		/// <param name="digestAlgo">The digest algorithm.</param>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="digestAlgo"/> is out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// <paramref name="digestAlgo"/> does not have an equivalent
		/// <see cref="Org.BouncyCastle.Bcpg.HashAlgorithmTag"/> value.
		/// </exception>
		public static HashAlgorithmTag GetHashAlgorithm (DigestAlgorithm digestAlgo)
		{
			switch (digestAlgo) {
			case DigestAlgorithm.MD5:       return HashAlgorithmTag.MD5;
			case DigestAlgorithm.Sha1:      return HashAlgorithmTag.Sha1;
			case DigestAlgorithm.RipeMD160: return HashAlgorithmTag.RipeMD160;
			case DigestAlgorithm.DoubleSha: return HashAlgorithmTag.DoubleSha;
			case DigestAlgorithm.MD2:       return HashAlgorithmTag.MD2;
			case DigestAlgorithm.Tiger192:  return HashAlgorithmTag.Tiger192;
			case DigestAlgorithm.Haval5160: return HashAlgorithmTag.Haval5pass160;
			case DigestAlgorithm.Sha256:    return HashAlgorithmTag.Sha256;
			case DigestAlgorithm.Sha384:    return HashAlgorithmTag.Sha384;
			case DigestAlgorithm.Sha512:    return HashAlgorithmTag.Sha512;
			case DigestAlgorithm.Sha224:    return HashAlgorithmTag.Sha224;
			case DigestAlgorithm.MD4: throw new NotSupportedException ("The MD4 digest algorithm is not supported.");
			default: throw new ArgumentOutOfRangeException ("digestAlgo");
			}
		}