Exemplo n.º 1
0
        public virtual byte[] Sign(DSA key)
        {
            string        hashoid       = "1.2.840.10040.4.3";
            ASN1          asn           = this.ToBeSigned(hashoid);
            HashAlgorithm hashAlgorithm = HashAlgorithm.Create(this.hashName);

            if (!(hashAlgorithm is SHA1))
            {
                throw new NotSupportedException("Only SHA-1 is supported for DSA");
            }
            byte[] rgbHash = hashAlgorithm.ComputeHash(asn.GetBytes());
            DSASignatureFormatter dsasignatureFormatter = new DSASignatureFormatter(key);

            dsasignatureFormatter.SetHashAlgorithm(this.hashName);
            byte[] src   = dsasignatureFormatter.CreateSignature(rgbHash);
            byte[] array = new byte[20];
            Buffer.BlockCopy(src, 0, array, 0, 20);
            byte[] array2 = new byte[20];
            Buffer.BlockCopy(src, 20, array2, 0, 20);
            ASN1 asn2 = new ASN1(48);

            asn2.Add(new ASN1(2, array));
            asn2.Add(new ASN1(2, array2));
            return(this.Build(asn, hashoid, asn2.GetBytes()));
        }
        public static byte[] DSASignHash(byte[] HashToSign, DSAParameters DSAKeyInfo,
                                         string HashAlg)
        {
            byte[] sig = null;

            try
            {
                // Create a new instance of DSACryptoServiceProvider.
                using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider(2048)) // GOOD
                {
                    // Import the key information.
                    DSA.ImportParameters(DSAKeyInfo);

                    // Create an DSASignatureFormatter object and pass it the
                    // DSACryptoServiceProvider to transfer the private key.
                    DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA);

                    // Set the hash algorithm to the passed value.
                    DSAFormatter.SetHashAlgorithm(HashAlg);

                    // Create a signature for HashValue and return it.
                    sig = DSAFormatter.CreateSignature(HashToSign);
                }
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
            }

            return(sig);
        }
Exemplo n.º 3
0
    static void Main()
    {
        try
        {
            //Create a new instance of DSACryptoServiceProvider.
            DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

            //The hash to sign.
            byte[] Hash = { 59, 4, 248, 102, 77, 97, 142, 201, 210, 12, 224, 93, 25, 41, 100, 197, 213, 134, 130, 135 };

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

            //Set the hash algorithm to SHA1.
            DSAFormatter.SetHashAlgorithm("SHA1");

            //Create a signature for HashValue and return it.
            byte[] SignedHash = DSAFormatter.CreateSignature(Hash);
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
    }
Exemplo n.º 4
0
        /// <summary>
        /// Generate a signature file using a private key.
        /// </summary>
        /// <param name="filePath">The file whose contents will be hashed.</param>
        /// <param name="signatureFilePath">The path of the generated signature file.</param>
        /// <param name="privateBlob">The private key.</param>
        public static void SignFile(string filePath, string signatureFilePath, byte[] privateBlob)
        {
            try
            {
                if (privateBlob.Length == 0)
                {
                    throw new Exception("The specified private key is invalid.");
                }

                byte[] hash = null;

                using (Stream fileStream = File.Open(filePath, FileMode.Open))
                {
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    hash = sha1.ComputeHash(fileStream);
                }

                // Import the private key
                var dsa = new DSACryptoServiceProvider();
                dsa.ImportCspBlob(privateBlob);
                var rsaFormatter = new DSASignatureFormatter(dsa);
                rsaFormatter.SetHashAlgorithm("SHA1");

                // Create a signature based on the private key
                byte[] signature = rsaFormatter.CreateSignature(hash);

                // Write the signature file
                File.WriteAllBytes(signatureFilePath, signature);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }
Exemplo n.º 5
0
 /// <summary>
 /// 数字签名实现
 /// </summary>
 /// <param name="hashToSign">准备签名的数据</param>
 /// <param name="dsaKeyInfo">公钥信息</param>
 /// <param name="hashAlg">Hash算法名称</param>
 /// <returns></returns>
 public static byte[] DsaSignHash(byte[] hashToSign, DSAParameters dsaKeyInfo, string hashAlg)
 {
     if (string.IsNullOrEmpty(hashAlg))
     {
         throw new ArgumentNullException(hashAlg);
     }
     byte[] sig;
     try
     {
         using (DSACryptoServiceProvider dsa = new DSACryptoServiceProvider())
         {
             dsa.ImportParameters(dsaKeyInfo);
             DSASignatureFormatter dsaFormatter = new DSASignatureFormatter(dsa);
             dsaFormatter.SetHashAlgorithm(hashAlg);
             sig = dsaFormatter.CreateSignature(hashToSign);
         }
     }
     catch (CryptographicException e)
     {
         throw new CryptographicException(e.Message);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
     return(sig);
 }
Exemplo n.º 6
0
        public static byte[] SignData(byte[] data, string keyContainerName)
        {
            byte[] signedData;
            byte[] hash = GetSha1Hash(data);

            DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();

            if (File.Exists(MainWindow.UserDirectoryPath + keyContainerName + ".akey"))
            {
                dsa.FromXmlString(File.ReadAllText(
                                      MainWindow.UserDirectoryPath + keyContainerName + ".akey"));
            }
            else
            {
                File.WriteAllText(MainWindow.UserDirectoryPath + keyContainerName + ".akey",
                                  dsa.ToXmlString(true)); // TODO: шифровать это
            }

            DSASignatureFormatter dsaFormatter = new DSASignatureFormatter(dsa);

            dsaFormatter.SetHashAlgorithm("SHA1");
            byte[] signedHash       = dsaFormatter.CreateSignature(hash);
            byte[] signedHashLength = BitConverter.GetBytes(signedHash.Length);

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(signedHashLength, 0, signedHashLength.Length);
                ms.Write(signedHash, 0, signedHash.Length);
                ms.Write(data, 0, data.Length);
                signedData = ms.ToArray();
            }

            return(signedData);
        }
Exemplo n.º 7
0
        public virtual byte[] Sign(DSA key)
        {
            string        hashName  = "1.2.840.10040.4.3";
            ASN1          tbs       = this.ToBeSigned(hashName);
            HashAlgorithm algorithm = HashAlgorithm.Create(this.hashName);

            if (!(algorithm is SHA1))
            {
                throw new NotSupportedException("Only SHA-1 is supported for DSA");
            }
            byte[] rgbHash = algorithm.ComputeHash(tbs.GetBytes());
            DSASignatureFormatter formatter = new DSASignatureFormatter(key);

            formatter.SetHashAlgorithm(this.hashName);
            byte[] src = formatter.CreateSignature(rgbHash);
            byte[] dst = new byte[20];
            Buffer.BlockCopy(src, 0, dst, 0, 20);
            byte[] buffer4 = new byte[20];
            Buffer.BlockCopy(src, 20, buffer4, 0, 20);
            ASN1 asn2 = new ASN1(0x30);

            asn2.Add(new ASN1(2, dst));
            asn2.Add(new ASN1(2, buffer4));
            return(this.Build(tbs, hashName, asn2.GetBytes()));
        }
Exemplo n.º 8
0
        private void button2_Click(object sender, EventArgs e)
        {
            var textBytes = Encoding.Default.GetBytes(richTextBox1.Text);

            cryptoServiceProvider.ImportParameters(privateKey);
            var formatter = new DSASignatureFormatter(cryptoServiceProvider);

            formatter.SetHashAlgorithm("SHA1");
            var sha       = SHA1.Create();
            var signature = formatter.CreateSignature(sha.ComputeHash(textBytes));

            currentSignature = signature;
            textBox1.Text    = BitConverter.ToString(signature).Replace("-", string.Empty);
            var saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "TXT files (*.txt)|*.txt";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(saveFileDialog.FileName, textBox1.Text);
            }
            else
            {
                return;
            }

            label1.Visible   = true;
            textBox1.Visible = true;
            button6.Visible  = true;
        }
        public static byte[] Sign(byte[] hash, string hashAlgo, AsymmetricEncryptionAlgorithm cryptoAlgo, string privateKey)
        {
            switch (cryptoAlgo)
            {
            case AsymmetricEncryptionAlgorithm.RSA:
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    RSA.FromXmlString(privateKey);

                    return(RSA.SignHash(hash, CryptoConfig.MapNameToOID(hashAlgo)));
                }

            case AsymmetricEncryptionAlgorithm.DSA:
                using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
                {
                    DSA.FromXmlString(privateKey);

                    DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA);
                    DSAFormatter.SetHashAlgorithm(hashAlgo);

                    return(DSAFormatter.CreateSignature(hash));
                }

            default:
                throw new NotImplementedException("Feature not implemented for specified algorithm.");
            }
        }
Exemplo n.º 10
0
        /// <summary>デジタル署名を作成する</summary>
        /// <param name="data">デジタル署名を行なう対象データ</param>
        /// <returns>対象データに対してデジタル署名したデジタル署名部分のデータ</returns>
        public virtual byte[] SignByFormatter(byte[] data)
        {
            // ハッシュ
            byte[] hash = this.HashAlgorithm.ComputeHash(data);

            // デジタル署名
            byte[] signedByte = null;

            if (this.AsymmetricAlgorithm is RSA)
            {
                // RSAPKCS1SignatureFormatterオブジェクトを作成
                RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(this.AsymmetricAlgorithm);
                rsaFormatter.SetHashAlgorithm(HashAlgorithmCmnFunc.GetHashAlgorithmName(this.HashAlgorithm));
                signedByte = rsaFormatter.CreateSignature(hash);
            }
            else if (this.AsymmetricAlgorithm is DSA)
            {
                // DSASignatureFormatterオブジェクトを作成
                DSASignatureFormatter dsaFormatter = new DSASignatureFormatter(this.AsymmetricAlgorithm);
                dsaFormatter.SetHashAlgorithm(HashNameConst.SHA1);
                signedByte = dsaFormatter.CreateSignature(hash);
            }
            else
            {
                throw new NotImplementedException(PublicExceptionMessage.NOT_IMPLEMENTED);
            }

            return(signedByte);
        }
Exemplo n.º 11
0
        public virtual byte[] Sign(DSA key)
        {
            string        oid = "1.2.840.10040.4.3";
            ASN1          tbs = ToBeSigned(oid);
            HashAlgorithm ha  = HashAlgorithm.Create(hashName);

            if (!(ha is SHA1))
            {
                throw new NotSupportedException("Only SHA-1 is supported for DSA");
            }
            byte[] hash = ha.ComputeHash(tbs.GetBytes());

            DSASignatureFormatter dsa = new DSASignatureFormatter(key);

            dsa.SetHashAlgorithm(hashName);
            byte[] rs = dsa.CreateSignature(hash);

            // split R and S
            byte[] r = new byte [20];
            Buffer.BlockCopy(rs, 0, r, 0, 20);
            byte[] s = new byte [20];
            Buffer.BlockCopy(rs, 20, s, 0, 20);
            ASN1 signature = new ASN1(0x30);

            signature.Add(new ASN1(0x02, r));
            signature.Add(new ASN1(0x02, s));

            // dsaWithSha1 (1 2 840 10040 4 3)
            return(Build(tbs, oid, signature.GetBytes()));
        }
Exemplo n.º 12
0
        public static string Hash(string text)
        {
            try
            {
                byte[] Hash = Sha1Hash(text);
                DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();

                DSASignatureFormatter dSASignatureFormatter = new DSASignatureFormatter(dsa);

                dSASignatureFormatter.SetHashAlgorithm("SHA1");
                byte[] SignedHash = dSASignatureFormatter.CreateSignature(Hash);
                string sign       = Convert.ToBase64String(SignedHash);
                DSASignatureDeformatter dSASignatureDeformatter = new DSASignatureDeformatter(dsa);
                if (dSASignatureDeformatter.VerifySignature(Hash, SignedHash))
                {
                    return(sign);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error! During DSA Hash siganture generation.");
            }
        }
Exemplo n.º 13
0
        /// <summary>デジタル署名を作成する</summary>
        /// <param name="data">デジタル署名を行なう対象データ</param>
        /// <returns>対象データに対してデジタル署名したデジタル署名部分のデータ</returns>
        public override byte[] Sign(byte[] data)
        {
            // ハッシュ
            byte[] hashedByte = this.HashAlgorithm.ComputeHash(data);
            // デジタル署名
            byte[] signedByte = null;

            if (this.AsymmetricAlgorithm is RSACryptoServiceProvider)
            {
                // RSAPKCS1SignatureFormatterオブジェクトを作成
                RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(this.AsymmetricAlgorithm);

                rsaFormatter.SetHashAlgorithm(
                    RsaAndDsaCmnFunc.GetHashAlgorithmName(this.HashAlgorithm));
                signedByte = rsaFormatter.CreateSignature(hashedByte);
            }
            else if (this.AsymmetricAlgorithm is DSACryptoServiceProvider)
            {
                // DSASignatureFormatterオブジェクトを作成
                DSASignatureFormatter dsaFormatter = new DSASignatureFormatter(this.AsymmetricAlgorithm);

                // デジタル署名を作成
                dsaFormatter.SetHashAlgorithm("SHA1");
                signedByte = dsaFormatter.CreateSignature(hashedByte);
            }

            return(signedByte);
        }
        public byte[] Sign(string message)
        {
            DSASignatureFormatter dsfm = new DSASignatureFormatter(_alg);

            dsfm.SetHashAlgorithm(_hashfn);
            Byte[] messagebyte = new UnicodeEncoding().GetBytes(message);
            Byte[] hash        = HashAlgorithm.Create(_hashfn).ComputeHash(messagebyte);
            return(dsfm.CreateSignature(hash));
        }
Exemplo n.º 15
0
 // TODO:
 public static string GenSign(string msg, string privateSignKey)
 {
     using (var provider = new DSACryptoServiceProvider())
     {
         provider.ImportCspBlob(Convert.FromBase64String(privateSignKey));
         var formatter = new DSASignatureFormatter(provider);
         formatter.SetHashAlgorithm("SHA1");
         var signature = formatter.CreateSignature(Encoding.UTF8.GetBytes(msg));
         return(Convert.ToBase64String(signature));
     }
 }
Exemplo n.º 16
0
 public static void VerifySignature_SHA1()
 {
     using (DSA dsa = DSAFactory.Create())
     {
         var formatter = new DSASignatureFormatter(dsa);
         var deformatter = new DSASignatureDeformatter(dsa);
         using (SHA1 alg = SHA1.Create())
         {
             VerifySignature(formatter, deformatter, alg, "SHA1");
             VerifySignature(formatter, deformatter, alg, "sha1");
         }
     }
 }
 public static void VerifySignature_SHA1()
 {
     using (DSA dsa = DSAFactory.Create())
     {
         var formatter   = new DSASignatureFormatter(dsa);
         var deformatter = new DSASignatureDeformatter(dsa);
         using (SHA1 alg = SHA1.Create())
         {
             VerifySignature(formatter, deformatter, alg, "SHA1");
             VerifySignature(formatter, deformatter, alg, "sha1");
         }
     }
 }
Exemplo n.º 18
0
        //This method will probably won't work, we need to get rid of the ASN.1 format (Tamir)
        public byte[] sign()
        {
            //byte[] sig=signature.sign();
            cs.Close();
            var DSA = new DSACryptoServiceProvider();

            DSA.ImportParameters(DSAKeyInfo);
            var DSAFormatter = new DSASignatureFormatter(DSA);

            DSAFormatter.SetHashAlgorithm("SHA1");

            byte[] sig = DSAFormatter.CreateSignature(sha1);
            return(sig);
        }
Exemplo n.º 19
0
        private void BtnSign_Click(object sender, EventArgs e)
        {
            if (textboxplaintext.Text == "")
            {
                return;
            }
            DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSAC);

            DSAFormatter.SetHashAlgorithm("SHA1");
            SHA1Managed SHhash = new SHA1Managed();

            byte[] SignedHashValue = DSAFormatter.CreateSignature(SHhash.ComputeHash(new UnicodeEncoding().GetBytes(textboxplaintext.Text)));
            textboxsigned.Text = Convert.ToBase64String(SignedHashValue);
        }
Exemplo n.º 20
0
        public byte[] Sign(byte[] hash, string hashAlgo)
        {
            switch (_cryptoAlgo)
            {
            case AsymmetricEncryptionAlgorithm.DSA:
                DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(_asymAlgo);
                DSAFormatter.SetHashAlgorithm(hashAlgo);
                return(DSAFormatter.CreateSignature(hash));

            case AsymmetricEncryptionAlgorithm.RSA:
                return((_asymAlgo as RSACryptoServiceProvider).SignHash(hash, CryptoConfig.MapNameToOID(hashAlgo)));

            default:
                throw new NotImplementedException("Feature not implemented for specified algorithm.");
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// 使用DSA算法签名哈希值
 /// </summary>
 /// <param name="HashToSign">要被签名的哈希值</param>
 /// <param name="dsaKeyInfo">DSA密钥信息</param>
 /// <param name="HashAlg">指定哈希算法</param>
 /// <returns>签名后的结果</returns>
 private byte[] DSASignHash(byte[] HashToSign, DSAParameters dsaKeyInfo, string HashAlg)
 {
     try
     {
         DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
         dsa.ImportParameters(dsaKeyInfo);
         DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(dsa);
         DSAFormatter.SetHashAlgorithm(HashAlg);
         return(DSAFormatter.CreateSignature(HashToSign));
     }
     catch (CryptographicException err)
     {
         MessageBox.Show(err.Message);
         return(null);
     }
 }
Exemplo n.º 22
0
        public static void VerifySignature_SHA1()
        {
            using (DSA dsa = DSAFactory.Create())
            {
                dsa.ImportParameters(DSATestData.GetDSA1024Params());

                var formatter   = new DSASignatureFormatter(dsa);
                var deformatter = new DSASignatureDeformatter(dsa);

                using (SHA1 alg = SHA1.Create())
                {
                    VerifySignature(formatter, deformatter, alg, "SHA1");
                    VerifySignature(formatter, deformatter, alg, "sha1");
                }
            }
        }
Exemplo n.º 23
0
 //--METHOD UNTUK CREATE SIGNATURE
 static byte[] CreateSignature(byte[] dataSign, string privateKey)
 {
     byte[] result = null;
     //--CREATE OBJEK DSACryptoServiceProvider
     using (DSACryptoServiceProvider dsa = new DSACryptoServiceProvider())
     {
         //--SET PRIVATE KEY
         dsa.FromXmlString(privateKey);
         //--CREATE FORMATTER UNTUK MENTRANSFER KEY
         DSASignatureFormatter formatter = new DSASignatureFormatter(dsa);
         //--SETTING ALGORITHM YANG DIPAKAI DENGAN SHA1
         formatter.SetHashAlgorithm("SHA1");
         //--CREATE SIGNATURE
         result = formatter.CreateSignature(dataSign);
     }
     return(result);
 }
Exemplo n.º 24
0
        //#region 文件处理
        ///// <summary>
        ///// 加密文件
        ///// </summary>
        ///// <param name="inName">来源文件</param>
        ///// <param name="outName">输出文件</param>
        ///// <param name="xmlString">密钥(至少含公钥)</param>
        //public static void EncryptFile(string inName, string outName, string xmlString)
        //{
        //    DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
        //    dsa.FromXmlString(xmlString);
        //    FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
        //    using (FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write))
        //    {
        //        fout.SetLength(0);

        //        long rdlen = 0;					//This is the total number of bytes written.
        //        int len;						//This is the number of bytes to be written at a time.
        //        byte[] bin = new byte[FileReadStep];
        //        while (rdlen < fin.Length)
        //        {
        //            len = fin.Read(bin, 0, FileReadStep);
        //            byte[] bs = dsa.Encrypt(bin, false);
        //            fout.Write(bs, 0, bs.Length);
        //            rdlen += len;
        //        }

        //        fin.Close();
        //    }
        //}

        ///// <summary>
        ///// 解密文件
        ///// </summary>
        ///// <param name="inName">来源文件</param>
        ///// <param name="outName">输出文件</param>
        ///// <param name="xmlString">密钥(公钥私钥俱有)</param>
        //public static void DecryptFile(string inName, string outName, string xmlString)
        //{
        //    DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
        //    dsa.FromXmlString(xmlString);
        //    FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
        //    using (FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write))
        //    {
        //        fout.SetLength(0);

        //        long rdlen = 0;					//This is the total number of bytes written.
        //        int len;						//This is the number of bytes to be written at a time.
        //        byte[] bin = new byte[FileReadStep];
        //        while (rdlen < fin.Length)
        //        {
        //            len = fin.Read(bin, 0, FileReadStep);
        //            byte[] bs = dsa.Decrypt(bin, false);
        //            fout.Write(bs, 0, bs.Length);
        //            rdlen += len;
        //        }

        //        fin.Close();
        //    }
        //}
        //#endregion

        #region 字符串处理
        /// <summary>
        /// DSA签名
        /// </summary>
        /// <param name="PlainText">原始字符串</param>
        /// <param name="xmlString">密钥(公钥私钥俱有)</param>
        /// <returns>Base64编码后的已签名字符串</returns>
        public static string SignString(string PlainText, string xmlString)
        {
            DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();

            dsa.FromXmlString(xmlString);

            if (!string.IsNullOrEmpty(PlainText))
            {
                byte[] bText = System.Text.Encoding.UTF8.GetBytes(PlainText.ToCharArray());

                DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(dsa);
                DSAFormatter.SetHashAlgorithm("SHA1");
                byte[] bEnc = DSAFormatter.CreateSignature(bText);

                return(System.Convert.ToBase64String(bEnc));
            }
            return(string.Empty);
        }
Exemplo n.º 25
0
        /// <summary>
        /// 校验签名是否正确
        /// </summary>
        /// <param name="decryptString"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool VerifySignature(string decryptString, string key = strKeys)
        {
            bool ret = false;

            byte[] hashValue = { 22, 45, 78, 53, 1, 2, 205, 98, 75, 123, 45, 76, 143, 189, 205, 65, 12, 193, 211, 255 };
            DSACryptoServiceProvider signer    = new DSACryptoServiceProvider();
            DSASignatureFormatter    formatter = new DSASignatureFormatter(signer);

            formatter.SetHashAlgorithm("SHA1");
            byte[] signedHashValue = formatter.CreateSignature(hashValue);
            DSASignatureDeformatter deformatter = new DSASignatureDeformatter(signer);

            deformatter.SetHashAlgorithm("SHA1");

            ret = deformatter.VerifySignature(hashValue, signedHashValue);
            signer.Clear();
            return(ret);
        }
Exemplo n.º 26
0
        public void ComputeSignature()
        {
            if (key != null)
            {
                if (m_signature.SignedInfo.SignatureMethod == null)
                {
                    // required before hashing
                    m_signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
                }
                else if (m_signature.SignedInfo.SignatureMethod != key.SignatureAlgorithm)
                {
                    throw new CryptographicException("Specified SignatureAlgorithm is not supported by the signing key.");
                }
                DigestReferences();

                AsymmetricSignatureFormatter signer = null;
                // in need for a CryptoConfig factory
                if (key is DSA)
                {
                    signer = new DSASignatureFormatter(key);
                }
                else if (key is RSA)
                {
                    signer = new RSAPKCS1SignatureFormatter(key);
                }

                if (signer != null)
                {
                    SignatureDescription sd = (SignatureDescription)CryptoConfig.CreateFromName(m_signature.SignedInfo.SignatureMethod);

                    HashAlgorithm hash = GetHash(sd.DigestAlgorithm, false);
                    // get the hash of the C14N SignedInfo element
                    byte[] digest = hash.ComputeHash(SignedInfoTransformed());

                    signer.SetHashAlgorithm("SHA1");
                    m_signature.SignatureValue = signer.CreateSignature(digest);
                }
            }
            else
            {
                throw new CryptographicException("signing key is not specified");
            }
        }
Exemplo n.º 27
0
 public string CreateSignatureForStream(Stream stream)
 {
     byte[] hash = (new SHA1Managed()).ComputeHash(stream);//for file or text
     try
     {
         using (var dsaCryptoProvider = new DSACryptoServiceProvider())
         {
             dsaCryptoProvider.ImportParameters(PrivateKey);
             var dsaFormatter = new DSASignatureFormatter(dsaCryptoProvider);
             dsaFormatter.SetHashAlgorithm("SHA1");
             byte[] signature = dsaFormatter.CreateSignature(hash);
             return(ByteArrayToString(signature));
         }
     }
     catch (CryptographicException e)
     {
         return(null);
     }
 }
Exemplo n.º 28
0
        public static void InvalidHashAlgorithm()
        {
            using (DSA dsa = DSAFactory.Create())
            {
                var formatter   = new DSASignatureFormatter(dsa);
                var deformatter = new DSASignatureDeformatter(dsa);

                // Unlike RSA, DSA will throw during SetHashAlgorithm
                Assert.Throws <CryptographicUnexpectedOperationException>(() =>
                                                                          formatter.SetHashAlgorithm("INVALIDVALUE"));
                Assert.Throws <CryptographicUnexpectedOperationException>(() =>
                                                                          deformatter.SetHashAlgorithm("INVALIDVALUE"));

                // Currently anything other than SHA1 fails
                Assert.Throws <CryptographicUnexpectedOperationException>(() =>
                                                                          formatter.SetHashAlgorithm("SHA256"));
                Assert.Throws <CryptographicUnexpectedOperationException>(() =>
                                                                          deformatter.SetHashAlgorithm("SHA256"));
            }
        }
Exemplo n.º 29
0
        public static void InvalidHashAlgorithm()
        {
            using (DSA dsa = DSAFactory.Create())
            {
                var formatter = new DSASignatureFormatter(dsa);
                var deformatter = new DSASignatureDeformatter(dsa);

                // Unlike RSA, DSA will throw during SetHashAlgorithm
                Assert.Throws<CryptographicUnexpectedOperationException>(() =>
                    formatter.SetHashAlgorithm("INVALIDVALUE"));
                Assert.Throws<CryptographicUnexpectedOperationException>(() =>
                    deformatter.SetHashAlgorithm("INVALIDVALUE"));

                // Currently anything other than SHA1 fails
                Assert.Throws<CryptographicUnexpectedOperationException>(() =>
                    formatter.SetHashAlgorithm("SHA256"));
                Assert.Throws<CryptographicUnexpectedOperationException>(() =>
                    deformatter.SetHashAlgorithm("SHA256"));
            }
        }
Exemplo n.º 30
0
        public static DataSignature CreateSignature(byte[] plainText)
        {
            DataSignature ds = new DataSignature();

            if (plainText != null)
            {
                SHA1Managed sha1 = new SHA1Managed();
                //if (dsa == null)
                dsa = new DSACryptoServiceProvider();
                DSASignatureFormatter formatter = new DSASignatureFormatter(dsa);
                byte[] data = plainText;
                byte[] hash = sha1.ComputeHash(data);
                formatter.SetHashAlgorithm("SHA1");
                byte[] signHash = formatter.CreateSignature(hash);
                ds.Data      = data;
                ds.Signature = signHash;
                ds.PublicKey = dsa.ToXmlString(false);
            }
            return(ds);
        }
Exemplo n.º 31
0
        public void ComputeSignature()
        {
            if (key != null)
            {
                // required before hashing
                DigestReferences();

                SignatureDescription sd = GetSignatureDescription(signature.SignedInfo.SignatureMethod);

                // the hard part - C14Ning the KeyInfo
                byte[] hash = Hash(sd.DigestAlgorithm);
                AsymmetricSignatureFormatter signer = null;

                // in need for a CryptoConfig factory
                if (key is DSA)
                {
                    signer = new DSASignatureFormatter(key);
                }
                else if (key is RSA)
                {
                    signer = sd.CreateFormatter(key); //new RSAPKCS1SignatureFormatter(key);
                }
                if (signer != null)
                {
                    if (sd.DigestAlgorithm == typeof(SHA1CryptoServiceProvider).FullName || sd.DigestAlgorithm == typeof(SHA1Cng).FullName)
                    {
                        signer.SetHashAlgorithm("SHA1");
                    }
                    else if (sd.DigestAlgorithm == typeof(SHA256Managed).FullName || sd.DigestAlgorithm == typeof(SHA256Cng).FullName)
                    {
                        signer.SetHashAlgorithm("SHA256");
                    }
                    else if (sd.DigestAlgorithm == typeof(SHA512Managed).FullName || sd.DigestAlgorithm == typeof(SHA512Cng).FullName)
                    {
                        signer.SetHashAlgorithm("SHA512");
                    }

                    signature.SignatureValue = signer.CreateSignature(hash);
                }
            }
        }
Exemplo n.º 32
0
        private byte[] DsaSignHash(byte[] hash, DSAParameters dsaKey, string hashAlg)
        {
            byte[] signature = null;

            try
            {
                using (var dsa = new DSACryptoServiceProvider())
                {
                    dsa.ImportParameters(dsaKey);
                    var dsaFormatter = new DSASignatureFormatter(dsa);
                    dsaFormatter.SetHashAlgorithm(hashAlg);
                    signature = dsaFormatter.CreateSignature(hash);
                }
            }
            catch (CryptographicException e)
            {
                MessageBox.Show(e.Message);
            }

            return(signature);
        }