VerifySignature() public method

public VerifySignature ( byte rgbHash, byte rgbSignature ) : bool
rgbHash byte
rgbSignature byte
return bool
示例#1
0
文件: Program.cs 项目: 1v1expert/DSA
        //-------------------------------------------------------------------
        public static bool DSAVerifyHash(byte[] HashValue, byte[] SignedHashValue,
        DSAParameters DSAKeyInfo, string HashAlg)
        {
            bool verified = false;

            try
            {
            // Создаем новый экземпляр класса DSACryptoServiceProvider.
            using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
            {
                // Импортируем ключи
                DSA.ImportParameters(DSAKeyInfo);

                //Создаем объект класса DSASignatureFormatter и передаем ему DSACryptoServiceProvider закрытый ключ
                DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);

                // Устанавливаем алгоритм шифрования
                DSADeformatter.SetHashAlgorithm(HashAlg);

                // Сверяем подписи и возвращаем результат
                verified = DSADeformatter.VerifySignature(HashValue, SignedHashValue);
            }
            }
            catch (CryptographicException e)
            {
            Console.WriteLine(e.Message);
            }

            return verified;
        }
示例#2
0
		internal bool VerifySignature (DSA dsa) 
		{
			// signatureOID is check by both this.Hash and this.Signature
			DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
			// only SHA-1 is supported
			v.SetHashAlgorithm ("SHA1");
			return v.VerifySignature (this.Hash, this.Signature);
		}
示例#3
0
        public bool verify(byte[] sig)
        {
            m_cs.Close();
            DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();
            DSA.ImportParameters(m_DSAKeyInfo);
            DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);
            DSADeformatter.SetHashAlgorithm("SHA1");

            long i = 0;
            long j = 0;
            byte[] tmp;

            //This makes sure sig is always 40 bytes?
            if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0)
            {
                long i1 = (sig[i++] << 24) & 0xff000000;
                long i2 = (sig[i++] << 16) & 0x00ff0000;
                long i3 = (sig[i++] << 8) & 0x0000ff00;
                long i4 = (sig[i++]) & 0x000000ff;
                j = i1 | i2 | i3 | i4;

                i += j;

                i1 = (sig[i++] << 24) & 0xff000000;
                i2 = (sig[i++] << 16) & 0x00ff0000;
                i3 = (sig[i++] << 8) & 0x0000ff00;
                i4 = (sig[i++]) & 0x000000ff;
                j = i1 | i2 | i3 | i4;

                tmp = new byte[j];
                Array.Copy(sig, i, tmp, 0, j);
                sig = tmp;
            }
            return DSADeformatter.VerifySignature(m_sha1, sig);
        }
示例#4
0
文件: Form1.cs 项目: krt/OpenTouryo
        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();
            }
        }
 static bool VerifyDsaMessage(byte[] keyData, byte[] message, byte[] signature)
 {
     // Load the Public Key X.509 Format
     AsnKeyParser keyParser = new AsnKeyParser(keyData);
     DSAParameters publicKey = keyParser.ParseDSAPublicKey();
     CspParameters csp = new CspParameters();
     // Cannot use PROV_DSS_DH
     const int PROV_DSS = 3;
     csp.ProviderType = PROV_DSS;
     const int AT_SIGNATURE = 2;
     csp.KeyNumber = AT_SIGNATURE;
     csp.KeyContainerName = "DSA Test (OK to Delete)";
     DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(csp);
     dsa.PersistKeyInCsp = false;
     dsa.ImportParameters(publicKey);
     SHA1 sha = new SHA1CryptoServiceProvider();
     byte[] hash = sha.ComputeHash(message);
     DSASignatureDeformatter verifier = new DSASignatureDeformatter(dsa);
     verifier.SetHashAlgorithm("SHA1");
     bool result = verifier.VerifySignature(hash, signature);
     // See http://blogs.msdn.com/tess/archive/2007/10/31/
     //   asp-net-crash-system-security-cryptography-cryptographicexception.aspx
     dsa.Clear();
     return result;
 }
示例#6
0
        public AuthenticationResult Authenticate(int[] versionParts, string clientId, string b64IdSig, string b64PrivId)
        {
            //do version negotiation first so client and server know they'll
            //be using correct key pairs (in case signatures are changed in future).
            bool versionMatch = false;
            if (versionParts == null || versionParts.Length != 3)
                return new AuthenticationResult(2, clientId); // throw new AuthorisationException("Invalid version specification. Please state the version of RPC client that is requesting authorisation. This can differ from the version of your client application provided that the RPC interface remains identical.", -1, 2);

            Version versionClient = new Version(versionParts[0], versionParts[1], versionParts[2]);

            if (PluginVersion.CompareTo(versionClient) == 0)
                versionMatch = true;

            if (versionMatch == false)
                return new AuthenticationResult(3, clientId); // version mismatch

            if (string.IsNullOrEmpty(clientId))
                return new AuthenticationResult(4, clientId); // missing clientId parameter

            if (string.IsNullOrEmpty(b64IdSig))
                return new AuthenticationResult(5, clientId); // missing base64 encoded clientId signature parameter

            if (string.IsNullOrEmpty(b64PrivId))
                return new AuthenticationResult(6, clientId); // missing base64 encoded unique client hash parameter

            byte[] clientIdClaim = System.Text.Encoding.UTF8.GetBytes(clientId);
            byte[] clientIdSignature = Convert.FromBase64String(b64IdSig);

            // calculate hash of claimed client ID
            SHA1 sha1 = new SHA1CryptoServiceProvider(); //TODO2: SHA256
            byte[] clientIdClaimHash = sha1.ComputeHash(clientIdClaim);

            // Load public key information
            DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();
            DSA.ImportCspBlob(GetClientIdPublicKey());

            //Create an DSASignatureDeformatter object and pass it the
            //DSACryptoServiceProvider to transfer the key information.
            DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);

            //Verify the hash and the signature
            if (!DSADeformatter.VerifySignature(
                clientIdClaimHash, clientIdSignature))
            {
                return new AuthenticationResult(7, clientId); // Signature invalid
            }

            // hash the (now authenticated) client Id and the client's
            // secret unique identifier so we can tell if this particular
            // client has conencted to KeePassRPC before
            //TODO2: record failed attempts too so we can avoid bothering
            // the user if they choose to ignore certain clients
            byte[] data = System.Text.Encoding.UTF8.GetBytes("hash of: " + b64PrivId + clientId);
            byte[] result;
            SHA256 shaM = new SHA256Managed();
            result = shaM.ComputeHash(data);
            string clientHash = Convert.ToBase64String(result);

            string currentKnownClients = host.CustomConfig
                .GetString("KeePassRPC.knownClients." + clientId, "");
            string[] knownClients = new string[0];

            if (!string.IsNullOrEmpty(currentKnownClients))
            {
                knownClients = currentKnownClients.Split(',');
                foreach (string knownClient in knownClients)
                    if (knownClient == clientHash)
                        return new AuthenticationResult(0, clientId); // everything's good, access granted
            }

            // This is the first time this type of client has
            // connected to KeePassRPC so we start the new user
            // wizard.
            // TODO2: support wizards for different clients
            if (knownClients.Length == 0 && clientId == "KeeFox Firefox add-on")
            {
                // The wizard handles user confirmation - if user says yes,
                // the hash will be stored in the KeePass config file
                PendingRPCClient newClient = new PendingRPCClient(
                    clientId, clientHash, new List<string>(knownClients));
                object[] delParams = { newClient };
                object invokeResult = host.MainWindow.Invoke(
                    new KeePassRPCExt.WelcomeKeeFoxUserDelegate(
                        KeePassRPCPlugin.WelcomeKeeFoxUser), delParams);
                return new AuthenticationResult((int)invokeResult, clientId); // Should be 0 unless user cancels
            }
            else
            {
                DialogResult userConfirmationResult = MessageBox.Show(
                    "KeePass detected an attempt to connect to KeePass from '"
                    + clientId
                    + "'. Should KeePass allow this application to access your passwords?",
                    "Security check from the KeePassRPC plugin", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);

                // if user says yes, we store the hash in the KeePass config file
                if (userConfirmationResult == DialogResult.Yes)
                {
                    AddKnownRPCClient(new PendingRPCClient(clientId, clientHash, new List<string>(knownClients)));
                    return new AuthenticationResult(0, clientId); // everything's good, access granted
                }
                return new AuthenticationResult(5, clientId);
            }
            //TODO2: audit logging options? needs to be a KeePass supported
            //feature really or maybe a seperate plugin?
        }
示例#7
0
 /// <summary>
 /// Validates the signature that follows the Licence data
 /// </summary>
 /// <param name="hashValue">Hash value</param>
 /// <param name="signedHashValue">Signed hash value</param>
 /// <param name="xmlKeyInfo">Public Key</param>
 /// <param name="hashAlg">Hash Algorithm</param>
 /// <returns>True if signature is valid</returns>
 private static bool DSAVerifyHash(byte[] hashValue, byte[] signedHashValue, string xmlKeyInfo, string hashAlg)
 {
     DSACryptoServiceProvider.UseMachineKeyStore = false;
     using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
     {
         DSA.FromXmlString(xmlKeyInfo);
         DSASignatureDeformatter DSAFormatter = new DSASignatureDeformatter(DSA);
         DSAFormatter.SetHashAlgorithm(hashAlg);
         return DSAFormatter.VerifySignature(hashValue, signedHashValue);
     }
 }
示例#8
0
		/// <summary>
		/// DSA验证
		/// </summary>
		/// <param name="CypherText">签名后的Base64字符串</param>
		/// <param name="xmlString">密钥(至少含公钥)</param>
		/// <param name="signString">签名串</param>
		public static bool VerifyString(string CypherText, string xmlString, string signString)
		{
			DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
			dsa.FromXmlString(xmlString);

			if (!string.IsNullOrEmpty(CypherText))
			{
				byte[] bEnc = System.Convert.FromBase64String(CypherText);
				byte[] bText = System.Text.Encoding.UTF8.GetBytes(signString.ToCharArray());

				DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(dsa);
				DSADeformatter.SetHashAlgorithm("SHA1");
				return DSADeformatter.VerifySignature(bEnc, bText);
			}
			return false;
		}
示例#9
0
		internal bool VerifySignature (DSA dsa) 
		{
			if (signatureOID != "1.2.840.10040.4.3")
				throw new CryptographicException ("Unsupported hash algorithm: " + signatureOID);
			DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
			// only SHA-1 is supported
			string hashName = "SHA1";
			v.SetHashAlgorithm (hashName);
			ASN1 sign = new ASN1 (signature);
			if ((sign == null) || (sign.Count != 2))
				return false;
			// parts may be less than 20 bytes (i.e. first bytes were 0x00)
			byte[] part1 = sign [0].Value;
			byte[] part2 = sign [1].Value;
			byte[] sig = new byte [40];
			Buffer.BlockCopy (part1, 0, sig, (20 - part1.Length), part1.Length);
			Buffer.BlockCopy (part2, 0, sig, (40 - part2.Length), part2.Length);
			return v.VerifySignature (GetHash (hashName), sig);
		}
 public bool VerifySignature(Stream stream, string signature)
 {
     try
     {
         using (var dsaCryptoProvider = new DSACryptoServiceProvider())
         {
             byte[] hash = (new SHA1Managed()).ComputeHash(stream);//for file or text
             dsaCryptoProvider.ImportParameters(PublicKey);
             var dsaDeformatter = new DSASignatureDeformatter(dsaCryptoProvider);
             dsaDeformatter.SetHashAlgorithm("SHA1");
             return dsaDeformatter.VerifySignature(hash, StringToByteArray(signature));
         }
     }
     catch (CryptographicException e)
     {
         return false;
     }
 }
        /// <summary>
        /// Método verifica si firma digital es correcta.
        /// </summary>
        /// <param name="pClavePublica">Cadena clave pública.</param>
        /// <param name="pFirmaDigital">Array byte de firma digital.</param>
        /// <param name="pClaveHash">Array byte clave hash.</param>
        /// <returns>
        /// Resultado booleano de verificación.
        /// </returns>
        private static bool ComprobarFirmaDigitalDSA(string pClavePublica, byte[] pFirmaDigital, byte[] pClaveHash)
        {
            // Instancia servicio de criptación DSA.
            DSACryptoServiceProvider vServicioCriptorDSA = new DSACryptoServiceProvider();

            // Asigna clave pública a servicio criptor.
            vServicioCriptorDSA.FromXmlString(pClavePublica);

            // Instancia por medio de servicio criptor a formateador de firma por medio de DSA.
            DSASignatureDeformatter vFormateadorFirmaDSA = new DSASignatureDeformatter(vServicioCriptorDSA);

            // Indica el algoritmo hash a utilizar.
            vFormateadorFirmaDSA.SetHashAlgorithm(ALGORITMO);

            // Verifica si firma digital es correcto y asigna  resultado a una variable booleana.
            bool vFirmaEsCorrecta = vFormateadorFirmaDSA.VerifySignature(pClaveHash, pFirmaDigital);

            // Retorna resultado.
            return vFirmaEsCorrecta;
        }
示例#12
0
        /// <summary>
        /// Verify a file using a signature file and a public key.
        /// </summary>
        /// <param name="filePath">The file whose contents will be hashed.</param>
        /// <param name="signatureFilePath">The path of the signature file.</param>
        /// <param name="publicBlob">The public key.</param>
        /// <returns> True if the file is verified, otherwise false.</returns>
        public static bool VerifyFile(string filePath, string signatureFilePath, byte[] publicBlob)
        {
            if (publicBlob.Length == 0)
                return false;

            bool verified = false;
            byte[] hash = null;

            try
            {
                // Compute a hash of the installer
                using (Stream fileStream = File.Open(filePath, FileMode.Open))
                {
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    hash = sha1.ComputeHash(fileStream);
                }

                // Import the public key
                var dsa = new DSACryptoServiceProvider();
                dsa.ImportCspBlob(publicBlob);

                var dsaDeformatter = new DSASignatureDeformatter(dsa);
                dsaDeformatter.SetHashAlgorithm("SHA1");

                // Read the signature file
                byte[] signature = File.ReadAllBytes(signatureFilePath);

                // Verify the signature against the hash of the installer
                verified = dsaDeformatter.VerifySignature(hash, signature);

                Console.WriteLine("File verified: {0}", verified);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);

                return false;
            }

            return verified;
        }
示例#13
-1
 public static bool myVerifyHash(byte[] HashValue, byte[] SignedHashValue, DSAParameters DSAKeyInfo, string HashAlg)
 {
     try
     {
         //Create a new instance of DSACryptoServiceProvider.
         DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();
         //Import the key information.
         DSA.ImportParameters(DSAKeyInfo);
         //DSAKeyInfo.
         //Create an DSASignatureDeformatter object and pass it the
         //DSACryptoServiceProvider to transfer the private key.
         DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);
         //Set the hash algorithm to the passed value.
         DSADeformatter.SetHashAlgorithm(HashAlg);
         //Verify signature and return the result.
         return DSADeformatter.VerifySignature(HashValue, SignedHashValue);
     }
     catch (CryptographicException e)
     {
         Console.WriteLine(e.Message);
         return false;
     }
 }
示例#14
-1
文件: X509CRL.cs 项目: carrie901/mono
		internal bool VerifySignature (DSA dsa) 
		{
			if (signatureOID != "1.2.840.10040.4.3")
				throw new CryptographicException ("Unsupported hash algorithm: " + signatureOID);
			DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
			// only SHA-1 is supported
			v.SetHashAlgorithm ("SHA1");
			ASN1 sign = new ASN1 (signature);
			if ((sign == null) || (sign.Count != 2))
				return false;
			// parts may be less than 20 bytes (i.e. first bytes were 0x00)
			byte[] part1 = sign [0].Value;
			byte[] part2 = sign [1].Value;
			byte[] sig = new byte [40];
			// parts may be less than 20 bytes (i.e. first bytes were 0x00)
			// parts may be more than 20 bytes (i.e. first byte > 0x80, negative)
			int s1 = System.Math.Max (0, part1.Length - 20);
			int e1 = System.Math.Max (0, 20 - part1.Length);
			Buffer.BlockCopy (part1, s1, sig, e1, part1.Length - s1);
			int s2 = System.Math.Max (0, part2.Length - 20);
			int e2 = System.Math.Max (20, 40 - part2.Length);
			Buffer.BlockCopy (part2, s2, sig, e2, part2.Length - s2);
			return v.VerifySignature (Hash, sig);
		}
        /// <summary>
        /// Verifies the signature.
        /// </summary>
        /// <param name="hash">The hash.</param>
        /// <param name="signature">The signature.</param>
        /// <returns>
        /// true if signature verified; otherwise false.
        /// </returns>
        public override bool VerifySignature(IEnumerable<byte> hash, IEnumerable<byte> signature)
        {
            using (var sha1 = new SHA1CryptoServiceProvider())
            {
                using (var cs = new CryptoStream(System.IO.Stream.Null, sha1, CryptoStreamMode.Write))
                {
                    var data = hash.ToArray();
                    cs.Write(data, 0, data.Length);
                }

                using (var dsa = new DSACryptoServiceProvider())
                {
                    dsa.ImportParameters(new DSAParameters
                    {
                        Y = _publicKey.TrimLeadingZero().ToArray(),
                        P = _p.TrimLeadingZero().ToArray(),
                        Q = _q.TrimLeadingZero().ToArray(),
                        G = _g.TrimLeadingZero().ToArray(),
                    });
                    var dsaDeformatter = new DSASignatureDeformatter(dsa);
                    dsaDeformatter.SetHashAlgorithm("SHA1");

                    long i = 0;
                    long j = 0;
                    byte[] tmp;

                    var sig = signature.ToArray();
                    if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0)
                    {
                        long i1 = (sig[i++] << 24) & 0xff000000;
                        long i2 = (sig[i++] << 16) & 0x00ff0000;
                        long i3 = (sig[i++] << 8) & 0x0000ff00;
                        long i4 = (sig[i++]) & 0x000000ff;
                        j = i1 | i2 | i3 | i4;

                        i += j;

                        i1 = (sig[i++] << 24) & 0xff000000;
                        i2 = (sig[i++] << 16) & 0x00ff0000;
                        i3 = (sig[i++] << 8) & 0x0000ff00;
                        i4 = (sig[i++]) & 0x000000ff;
                        j = i1 | i2 | i3 | i4;

                        tmp = new byte[j];
                        Array.Copy(sig, (int)i, tmp, 0, (int)j);
                        sig = tmp;
                    }

                    return dsaDeformatter.VerifySignature(sha1, sig);
                }
            }
        }