Пример #1
0
        // According to book ".NET Framework Security" this method
        // iterates all possible keys then return null
        protected virtual AsymmetricAlgorithm GetPublicKey()
        {
            if (m_signature.KeyInfo == null)
            {
                return(null);
            }

            if (pkEnumerator == null)
            {
                pkEnumerator = m_signature.KeyInfo.GetEnumerator();
            }

#if SECURITY_DEP
            if (_x509Enumerator != null)
            {
                if (_x509Enumerator.MoveNext())
                {
                    X509Certificate cert = (X509Certificate)_x509Enumerator.Current;
                    return(new X509Certificate2(cert.GetRawCertData()).PublicKey.Key);
                }
                else
                {
                    _x509Enumerator = null;
                }
            }
#endif
            while (pkEnumerator.MoveNext())
            {
                AsymmetricAlgorithm key = null;
                KeyInfoClause       kic = (KeyInfoClause)pkEnumerator.Current;

                if (kic is DSAKeyValue)
                {
                    key = DSA.Create();
                }
                else if (kic is RSAKeyValue)
                {
                    key = RSA.Create();
                }

                if (key != null)
                {
                    key.FromXmlString(kic.GetXml().InnerXml);
                    return(key);
                }

#if SECURITY_DEP
                if (kic is KeyInfoX509Data)
                {
                    _x509Enumerator = ((KeyInfoX509Data)kic).Certificates.GetEnumerator();
                    if (_x509Enumerator.MoveNext())
                    {
                        X509Certificate cert = (X509Certificate)_x509Enumerator.Current;
                        return(new X509Certificate2(cert.GetRawCertData()).PublicKey.Key);
                    }
                }
#endif
            }
            return(null);
        }
Пример #2
0
        /// <summary>
        /// Returns <c>true</c> if the key string passed is a valid XML key
        /// and is NOT a key container name.
        /// </summary>
        /// <param name="algorithm">The asymmetric algorithm.</param>
        /// <param name="key">The key string to be tested.</param>
        /// <returns><c>true</c> if the key is a valid XML key.</returns>
        /// <remarks>
        /// The current implementation supports only the "RSA" provider.
        /// </remarks>
        public static bool IsXmlKey(string algorithm, string key)
        {
            AsymmetricAlgorithm asymmetric = null;

            try
            {
                if (ParseKeyContainer(key) != null)
                {
                    return(false);
                }

                asymmetric = EncryptionConfig.CreateAsymmetric(algorithm, 0);
                asymmetric.FromXmlString(key);

                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                if (asymmetric != null)
                {
                    asymmetric.Clear();
                }
            }
        }
Пример #3
0
        protected virtual AsymmetricAlgorithm GetPublicKey()
        {
            AsymmetricAlgorithm key = null;

            if (signature.KeyInfo != null)
            {
                foreach (KeyInfoClause kic in signature.KeyInfo)
                {
                    if (kic is DSAKeyValue)
                    {
                        key = DSA.Create();
                    }
                    else if (kic is RSAKeyValue)
                    {
                        key = RSA.Create();
                    }
                    else if (kic is KeyInfoX509Data)
                    {
                        KeyInfoX509Data keyInfoData = kic as KeyInfoX509Data;

                        return((keyInfoData.Certificates[0] as X509Certificate2).PublicKey.Key);
                    }

                    if (key != null)
                    {
                        key.FromXmlString(kic.GetXml().InnerXml);
                        break;
                    }
                }
            }
            return(key);
        }
Пример #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EncryptedNewKeyCipher" /> class.
        /// </summary>
        /// <param name="hashAlgorithmName">
        /// The name of the hash algorithm implementation. Use any of the constants from <see cref="Algorithms.Hash"/> or
        /// <see langword="null"/>, empty or whitespace characters only - it will default to the default algorithm specified in the certificate.
        /// </param>
        /// <param name="signCertificate">
        /// The certificate containing the public and optionally the private key.
        /// If the parameter is <see langword="null"/> the method will try to resolve its value from the Common Service Locator with resolve name &quot;SigningCertificate&quot;.
        /// </param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when the <paramref name="signCertificate"/> is <see langword="null"/> and could not be resolved from the Common Service Locator.
        /// </exception>
        public RsaXmlSigner(
            X509Certificate2 signCertificate = null,
            string hashAlgorithmName         = null)
        {
            if (signCertificate == null)
            {
                try
                {
                    signCertificate = ServiceLocatorWrapper.Default.GetInstance <X509Certificate2>(Algorithms.Hash.CertificateResolveName);
                }
                catch (ActivationException x)
                {
                    throw new ArgumentNullException("The argument \"signCertificate\" was null and could not be resolved from the Common Service Locator.", x);
                }
            }

            if (hashAlgorithmName == null)
            {
                hashAlgorithmName = signCertificate.HashAlgorithm();
            }

            _hashAlgorithmName = hashAlgorithmName;

            int providerType;

            switch (hashAlgorithmName)
            {
            case Algorithms.Hash.Sha256:
                _canonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
                _signatureMethod        = XmlConstants.XmlDsigRSAPKCS1SHA256Url;
                _digestMethod           = XmlConstants.Sha256DigestMethod;
                providerType            = _sha256ProviderType;
                break;

#pragma warning disable 0612, 0618 // Type or member is obsolete - used for bacwards compatibility
            case Algorithms.Hash.Sha1:
#pragma warning restore 0612, 0618 // Type or member is obsolete
                _canonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;
                _signatureMethod        = SignedXml.XmlDsigRSASHA1Url;
                _digestMethod           = XmlConstants.Sha1DigestMethod;
                providerType            = _sha1ProviderType;
                break;

            default:
                throw new NotSupportedException("The signer does not support the hashing algorithm specified in the certificate.");
            }

            using (var key = signCertificate.HasPrivateKey
                                ? (RSACryptoServiceProvider)signCertificate.PrivateKey
                                : (RSACryptoServiceProvider)signCertificate.PublicKey.Key)
            {
                _asymmetric = new RSACryptoServiceProvider(new CspParameters(providerType));
                _asymmetric.FromXmlString(key.ToXmlString(signCertificate.HasPrivateKey));
            }
        }
Пример #5
0
        public byte[] EncryptSessionKeyByRSA(byte[] sessionKey, string keyToUse)
        {
            AsymmetricAlgorithm rsa = algo;

            if (!String.IsNullOrEmpty(keyToUse))
            {
                rsa.FromXmlString(keyToUse);
            }
            RSAOAEPKeyExchangeFormatter forma = new RSAOAEPKeyExchangeFormatter();

            forma.SetKey(rsa);
            byte[] exchangeData = forma.CreateKeyExchange(sessionKey);
            return(exchangeData);
        }
Пример #6
0
        public static string Sign(string privateKeyXmlString, byte[] buffer)
        {
            using (HashAlgorithm hashAlgorithm = SHA256.Create())
                using (AsymmetricAlgorithm rsa = RSA.Create())
                {
                    rsa.FromXmlString(privateKeyXmlString);

                    AsymmetricSignatureFormatter signatureFormatter = new RSAPKCS1SignatureFormatter(rsa);
                    signatureFormatter.SetHashAlgorithm(@"SHA256");

                    byte[] hash       = hashAlgorithm.ComputeHash(buffer);
                    byte[] signedHash = signatureFormatter.CreateSignature(hash);

                    return(Convert.ToBase64String(signedHash));
                }
        }
Пример #7
0
        public static bool Verify(string publicKeyXmlString, byte[] buffer, string signature)
        {
            using (HashAlgorithm hashAlgorithm = SHA256.Create())
                using (AsymmetricAlgorithm rsa = RSA.Create())
                {
                    rsa.FromXmlString(publicKeyXmlString);

                    AsymmetricSignatureDeformatter signatureDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
                    signatureDeformatter.SetHashAlgorithm(@"SHA256");

                    byte[] hash       = hashAlgorithm.ComputeHash(buffer);
                    byte[] signedHash = Convert.FromBase64String(signature);

                    return(signatureDeformatter.VerifySignature(hash, signedHash));
                }
        }
Пример #8
0
        public void ToCapiKeyBlob_AsymmetricAlgorithm()
        {
            AsymmetricAlgorithm rsa = RSA.Create();

            rsa.FromXmlString(strongNameString);
            byte[] keypair = CryptoConvert.ToCapiKeyBlob(rsa, true);
            AssertEquals("RSA-KeyPair", strongName, keypair);

            byte[] publicKey = CryptoConvert.ToCapiKeyBlob(rsa, false);
            Assert.AreEqual(BitConverter.ToString(strongNamePublicKey, 12), BitConverter.ToString(publicKey), "RSA-PublicKey");

            AsymmetricAlgorithm dsa = DSA.Create();

            dsa.FromXmlString(dsaKeyPairString);
            AssertEquals("DSA-KeyPair", dsaPrivBlob, CryptoConvert.ToCapiKeyBlob(dsa, true));
            Assert.AreEqual(BitConverter.ToString(dsaPubBlob), BitConverter.ToString(CryptoConvert.ToCapiKeyBlob(dsa, false)), "DSA-PublicKey");
        }
Пример #9
0
 public void ImportKey(string xml)
 {
     // Import key parameters from XML string.
     _algorithm.FromXmlString(xml);
 }
Пример #10
0
        /// <summary>公開鍵・暗号化</summary>
        private void button41_Click(object sender, EventArgs e)
        {
            this.textBox42.Text = "";
            this.textBox43.Text = "";
            this.textBox44.Text = "";

            if (this.textBox41a.Text == "" ||
                this.textBox41b.Text == "" ||
                this.textBox41c.Text == "")
            {
                return;
            }

            try
            {
                // 暗号のbyte型配列
                byte[] acb = null;
                // 元文字列をbyte型配列に変換する(UTF-8 Enc)
                byte[] asb = Encoding.UTF8.GetBytes(this.textBox41a.Text);

                // 公開鍵・暗号化サービスプロバイダ
                AsymmetricAlgorithm aa = this.CreateAsymmetricAlgorithmServiceProvider();
                this.SetKeyAndInitializationVectorToAsymmetricAlgorithmServiceProvider(aa);

                // 公開鍵
                aa.FromXmlString(this.textBox41b.Text);

                if (aa is DSACryptoServiceProvider)
                {
                    DSACryptoServiceProvider dsacsp = (DSACryptoServiceProvider)aa;

                    // 暗号化する
                    throw new NotImplementedException("DSACryptoServiceProviderの共通鍵暗号化はサポートされていません。");
                }
                else if (aa is ECDiffieHellmanCng)
                {
                    ECDiffieHellmanCng ecdhcng = (ECDiffieHellmanCng)aa;

                    // 暗号化する
                    throw new NotImplementedException("ECDiffieHellmanCngの共通鍵暗号化はサポートされていません。");
                }
                else if (aa is ECDsaCng)
                {
                    ECDsaCng ecdsa = (ECDsaCng)aa;

                    // 暗号化する
                    throw new NotImplementedException("ECDsaCngの共通鍵暗号化はサポートされていません。");
                }
                else if (aa is RSACryptoServiceProvider)
                {
                    RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)aa;

                    // 暗号化する(XP以降の場合のみ2項目にTrueを指定し、OAEPパディングを使用できる)
                    acb = rsa.Encrypt(asb, false);
                }

                // 結果を表示

                // 生バイト
                this.textBox42.Text = CustomEncode.ToHexString(acb);
                // Base64
                this.textBox43.Text = Convert.ToBase64String(acb);
            }
            catch (Exception ex)
            {
                // 結果を表示
                this.textBox44.Text = "エラーです。キーを変更した可能性があります。\r\n"
                                      + ex.ToString();
            }
        }
Пример #11
0
        private void button52_Click(object sender, EventArgs e)
        {
            this.textBox56.Text = "";

            if (this.textBox51a.Text == "" ||
                this.textBox51b.Text == "" ||
                this.textBox51c.Text == "")
            {
                return;
            }

            // 公開鍵・暗号化サービスプロバイダ
            AsymmetricAlgorithm aa = this.CreateAsymmetricAlgorithmServiceProvider2();

            // 公開鍵
            aa.FromXmlString(this.textBox51b.Text);

            try
            {
                // 結果フラグ
                bool flg = false;

                // 元文字列をbyte型配列に変換する(UTF-8 Enc)
                byte[] asb = Encoding.UTF8.GetBytes(this.textBox51a.Text);

                // ハッシュ値を取得
                byte[] ahb = Convert.FromBase64String(this.textBox53.Text);

                if (aa is DSACryptoServiceProvider)
                {
                    // キャスト
                    DSACryptoServiceProvider dsa = (DSACryptoServiceProvider)aa;

                    // DSASignatureFormatterオブジェクトを作成
                    DSASignatureDeformatter dsaSignatureDeformatter = new DSASignatureDeformatter(dsa);

                    // 検証に使用するハッシュアルゴリズムを指定し
                    // 上記で、ハッシュ値を計算した際と同じアルゴリズムを使用すること。
                    if (this.comboBox5.SelectedItem.ToString().IndexOf("SHA1") != -1)
                    {
                        dsaSignatureDeformatter.SetHashAlgorithm("SHA1");
                    }

                    // 検証する
                    flg = dsaSignatureDeformatter.VerifySignature(ahb, Convert.FromBase64String(this.textBox55.Text));
                }
                else if (aa is ECDiffieHellmanCng)
                {
                    // キャスト
                    ECDiffieHellmanCng ecdhcng = (ECDiffieHellmanCng)aa;

                    // 検証する
                    throw new NotImplementedException("ECDiffieHellmanCng:未実装");
                }
                else if (aa is ECDsaCng)
                {
                    // キャスト
                    ECDsaCng ecdsa = (ECDsaCng)aa;

                    // 検証する
                    throw new NotImplementedException("ECDsaCng:未実装");
                }
                else if (aa is RSACryptoServiceProvider)
                {
                    // キャスト
                    RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)aa;

                    // RSAPKCS1SignatureDeformatterオブジェクトを作成
                    RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);

                    // 検証に使用するハッシュアルゴリズムを指定し
                    // 上記で、ハッシュ値を計算した際と同じアルゴリズムを使用すること。
                    if (this.comboBox5.SelectedItem.ToString().IndexOf("SHA1") != -1)
                    {
                        rsaDeformatter.SetHashAlgorithm("SHA1");
                    }
                    else if (this.comboBox5.SelectedItem.ToString().IndexOf("MD5") != -1)
                    {
                        rsaDeformatter.SetHashAlgorithm("MD5");
                    }

                    // 検証する
                    flg = rsaDeformatter.VerifySignature(ahb, Convert.FromBase64String(this.textBox55.Text));
                }

                // 検証結果を表示
                if (flg)
                {
                    this.textBox56.Text = "デジタル署名は署名前のメッセージであることが検証されました。";
                }
                else
                {
                    this.textBox56.Text = "デジタル署名は署名前のメッセージであることが検証されませんでした。";
                }
            }
            catch (Exception ex)
            {
                // 結果を表示
                this.textBox56.Text = "エラーです。キーを変更した可能性があります。\r\n"
                                      + ex.ToString();
            }
        }
Пример #12
0
        /// <summary>署名</summary>
        private void button51_Click(object sender, EventArgs e)
        {
            this.textBox52.Text = "";
            this.textBox53.Text = "";
            this.textBox54.Text = "";
            this.textBox55.Text = "";
            this.textBox56.Text = "";

            if (this.textBox51a.Text == "" ||
                this.textBox51b.Text == "" ||
                this.textBox51c.Text == "")
            {
                return;
            }

            try
            {
                // 公開鍵・暗号化サービスプロバイダ
                AsymmetricAlgorithm aa = this.CreateAsymmetricAlgorithmServiceProvider2();

                // 秘密鍵
                aa.FromXmlString(this.textBox51c.Text);

                // 元文字列をbyte型配列に変換する(UTF-8 Enc)
                byte[] asb = Encoding.UTF8.GetBytes(this.textBox51a.Text);
                // ハッシュ値
                byte[] ahb = null;
                // 署名
                byte[] ab_sign = null;

                if (aa is DSACryptoServiceProvider)
                {
                    // キャスト
                    DSACryptoServiceProvider dsa = (DSACryptoServiceProvider)aa;

                    // DSASignatureFormatterオブジェクトを作成
                    DSASignatureFormatter dsaFormatter = new DSASignatureFormatter(dsa);

                    // 署名の作成に使用するハッシュアルゴリズムを指定し、ハッシュ値を計算
                    if (this.comboBox5.SelectedItem.ToString().IndexOf("SHA1") != -1)
                    {
                        dsaFormatter.SetHashAlgorithm("SHA1");
                        ahb = SHA1.Create().ComputeHash(asb);
                    }

                    // 署名を作成
                    ab_sign = dsaFormatter.CreateSignature(ahb);
                }
                else if (aa is ECDiffieHellmanCng)
                {
                    // キャスト
                    ECDiffieHellmanCng ecdhcng = (ECDiffieHellmanCng)aa;

                    // 署名を作成
                    throw new NotImplementedException("ECDiffieHellmanCng:未実装");
                }
                else if (aa is ECDsaCng)
                {
                    // キャスト
                    ECDsaCng ecdsa = (ECDsaCng)aa;

                    // 署名を作成
                    throw new NotImplementedException("ECDsaCng:未実装");
                }
                else if (aa is RSACryptoServiceProvider)
                {
                    // キャスト
                    RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)aa;

                    // RSAPKCS1SignatureFormatterオブジェクトを作成
                    RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);

                    // 署名の作成に使用するハッシュアルゴリズムを指定し、ハッシュ値を計算
                    if (this.comboBox5.SelectedItem.ToString().IndexOf("SHA1") != -1)
                    {
                        rsaFormatter.SetHashAlgorithm("SHA1");
                        ahb = SHA1.Create().ComputeHash(asb);
                    }
                    else if (this.comboBox5.SelectedItem.ToString().IndexOf("MD5") != -1)
                    {
                        rsaFormatter.SetHashAlgorithm("MD5");
                        ahb = MD5.Create().ComputeHash(asb);
                    }

                    // 署名を作成
                    ab_sign = rsaFormatter.CreateSignature(ahb);
                }

                // 結果を表示

                // ハッシュ

                // 生バイト
                this.textBox52.Text = CustomEncode.ToHexString(ahb);
                // Base64
                this.textBox53.Text = Convert.ToBase64String(ahb);

                // 署名

                // 生バイト
                this.textBox54.Text = CustomEncode.ToHexString(ab_sign);
                // Base64
                this.textBox55.Text = Convert.ToBase64String(ab_sign);
            }
            catch (Exception ex)
            {
                // 結果を表示
                this.textBox56.Text = "エラーです。キーを変更した可能性があります。\r\n"
                                      + ex.ToString();
            }
        }
 public void SetKey(string XMLString)
 {
     algorithm.FromXmlString(XMLString);
 }
Пример #14
0
 public override void FromXmlString(string keyParametersXml) => _algorithm.FromXmlString(keyParametersXml);