CreateSignature() public méthode

public CreateSignature ( byte rgbHash ) : byte[]
rgbHash byte
Résultat byte[]
 public static void Signature(Stream input, Stream output, string privateKey)
 {
     using (var sha = new SHA256CryptoServiceProvider())
     using (var rsa = new RSACryptoServiceProvider())
     {
         // Compute hash
         var buffer = ReadAllBytes(input);
         var hash = sha.ComputeHash(buffer);
         // RSA Initialize
         rsa.FromXmlString(privateKey);
         // format
         var formatter = new RSAPKCS1SignatureFormatter(rsa);
         formatter.SetHashAlgorithm("SHA256");
         var signature = formatter.CreateSignature(hash);
         // Krile Signature Package
         var magic = MagicStr + ":" + signature.Length + ":";
         var magicbytes = Encoding.UTF8.GetBytes(magic);
         if (magicbytes.Length > 64)
             throw new Exception("Magic bits too long.");
         output.Write(magicbytes, 0, magicbytes.Length);
         var padding = new byte[64 - magicbytes.Length];
         output.Write(padding, 0, padding.Length);
         output.Write(signature, 0, signature.Length);
         output.Write(buffer, 0, buffer.Length);
     }
 }
        public byte[] SignData(byte[] hashOfDataToSign)
        {            
            var rsaFormatter = new RSAPKCS1SignatureFormatter(mRsa);
            rsaFormatter.SetHashAlgorithm("SHA256");

            return rsaFormatter.CreateSignature(hashOfDataToSign);            
        }
Exemple #3
0
        public string SignN3Rsa(string data)
        {
            var cspParams = new CspParameters {KeyContainerName = "XML_DSIG_RSA_KEY"};
            var key = new RSACryptoServiceProvider(cspParams);
            var cspBlob = key.ExportCspBlob(false);
            var base64Blob = Convert.ToBase64String(cspBlob);

            var rsaFormatter = new RSAPKCS1SignatureFormatter(key);
            rsaFormatter.SetHashAlgorithm("MD5");

            var hash = Md5Helper.GetMd5Hash(data);
            var base64Hash = Convert.ToBase64String(hash);
            var sign = rsaFormatter.CreateSignature(hash);
            var base64Sign = Convert.ToBase64String(sign);

            var signData = new SignData
                           {
                               data = data,
                               public_key = base64Blob,
                               hash = base64Hash,
                               sign = base64Sign
                           };

            return new SerializationHelper<SignData>().Serialize(signData);
        }
Exemple #4
0
        private byte[] Sign(SHA1CryptoServiceProvider hash)
        {
            var formatter = new RSAPKCS1SignatureFormatter(_certificate.PrivateKey).
                Tap(it => it.SetHashAlgorithm("MD5"));

            return formatter.CreateSignature(hash);
        }
        public static byte[] Sign(byte[] privateKey, Stream stream)
        {
            #if Windows
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(Encoding.ASCII.GetString(privateKey));

                var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
                rsaFormatter.SetHashAlgorithm("SHA256");

                using (var Sha256 = SHA256.Create())
                {
                    return rsaFormatter.CreateSignature(Sha256.ComputeHash(stream));
                }
            }
            #endif

            #if Unix
            lock (_lockObject)
            {
                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.FromXmlString(Encoding.ASCII.GetString(privateKey));

                    var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
                    rsaFormatter.SetHashAlgorithm("SHA256");

                    using (var Sha256 = SHA256.Create())
                    {
                        return rsaFormatter.CreateSignature(Sha256.ComputeHash(stream));
                    }
                }
            }
            #endif
        }
        public DigitalSignatureCreationResult Sign(DigitalSignatureCreationArguments arguments)
        {
            var res = new DigitalSignatureCreationResult();
            try
            {
                var rsaProviderReceiver = new RSACryptoServiceProvider();
                rsaProviderReceiver.FromXmlString(arguments.PublicKeyForEncryption.ToString());
                var encryptionResult = rsaProviderReceiver.Encrypt(Encoding.UTF8.GetBytes(arguments.Message), false);
                var hashed = _hashingService.Hash(Convert.ToBase64String(encryptionResult));

                var rsaProviderSender = new RSACryptoServiceProvider();
                rsaProviderSender.FromXmlString(arguments.FullKeyForSignature.ToString());
                var signatureFormatter = new RSAPKCS1SignatureFormatter(rsaProviderSender);
                signatureFormatter.SetHashAlgorithm(_hashingService.HashAlgorithmCode());
                var signature = signatureFormatter.CreateSignature(hashed.HashedBytes);

                res.Signature = signature;
                res.CipherText = Convert.ToBase64String(encryptionResult);
                res.Success = true;
            }
            catch (Exception ex)
            {
                res.ExceptionMessage = ex.Message;
            }

            return res;
        }
        public byte[] CreateSignature(byte[] hash)
	    {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA);
            RSAFormatter.SetHashAlgorithm("MD5");
            m_public = RSA.ExportParameters(false);
            return RSAFormatter.CreateSignature(hash);
        }
 public byte[] sign()
 {
     SSC.RSA rsa = SSC.RSA.Create();
     rsa.ImportParameters(RSAparams);
     SSC.RSAPKCS1SignatureFormatter signer = new SSC.RSAPKCS1SignatureFormatter(rsa);
     signer.SetHashAlgorithm("SHA1");
     sc.Close();
     return signer.CreateSignature(md.Hash);
 }
Exemple #9
0
        public byte[] sign()
        {
            m_cs.Close();
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSA.ImportParameters(m_RSAKeyInfo);
            RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA);
            RSAFormatter.SetHashAlgorithm("SHA1");

            return RSAFormatter.CreateSignature(m_sha1);
        }
Exemple #10
0
 public static string CreateSignature(string textToSign, string XMLprivateKey)
 {
     RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
     RSA.FromXmlString(XMLprivateKey);
     RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(RSA);
     RSAFormatter.SetHashAlgorithm("SHA1");
     SHA1Managed SHhash = new SHA1Managed();
     byte[] SignedHashValue = RSAFormatter.CreateSignature(SHhash.ComputeHash(new UnicodeEncoding().GetBytes(textToSign)));
     string signature = System.Convert.ToBase64String(SignedHashValue);
     return signature;
 }
        public static void GenerateLicense(int months)
        {
            // The license key, it must be 20 bytes long to be compatible with RSA
            string licenseKey = DateTime.Now.Date.AddMonths(months).ToShortDateString();
            // If a current license exists, add the new license length onto the old one.
            if (File.Exists(Environment.CurrentDirectory + @"\licenseinfo.xml"))
            {
                XmlDocument licenseFile = new XmlDocument();
                licenseFile.Load(Environment.CurrentDirectory + @"\licenseinfo.xml");
                string savedLicenseKey = licenseFile.DocumentElement.SelectSingleNode(@"/LicenseInfo/KEY").InnerText;
                string licenseExpiry = savedLicenseKey.Substring(0, savedLicenseKey.LastIndexOf(@"/") + 5);
                if (Convert.ToDateTime(licenseExpiry) > DateTime.Today)
                {
                    licenseKey = (Convert.ToDateTime(licenseExpiry).AddMonths(months)).ToShortDateString();
                }
            }
            string machineName = Environment.MachineName;
            licenseKey += machineName;
            // Adds trailing 0's if the date+machinename is less than 20 charachters
            while (licenseKey.Length < 20)
            {
                licenseKey += "0";
            }
            // Cuts the key down to 20 charachters if the date+machinename are too large.
            licenseKey = licenseKey.Substring(0, 20);

            // Byte arrays to store the license key
            byte[] byteLicenseKey = Encoding.ASCII.GetBytes(licenseKey);

            // The RSA handling and public key creation
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(RSA);
            rsaFormatter.SetHashAlgorithm("SHA1");
            string publicKey = RSA.ToXmlString(false);

            // The digital signature for the license
            byte[] digitalSignature = rsaFormatter.CreateSignature(byteLicenseKey);

            //An XML file that holds the public key, license key, and the Digital Signature
            XmlDocument licenseDocument = new XmlDocument();
            XmlElement parentNode = licenseDocument.CreateElement("LicenseInfo");
            licenseDocument.AppendChild(parentNode);
            XmlElement xmlDocLicenseKey = licenseDocument.CreateElement("KEY");
            xmlDocLicenseKey.InnerText = Encoding.Default.GetString(byteLicenseKey);
            parentNode.AppendChild(xmlDocLicenseKey);
            XmlElement xmlDocLicenseSignature = licenseDocument.CreateElement("SignedKey");
            xmlDocLicenseSignature.InnerText = Convert.ToBase64String(digitalSignature);
            parentNode.AppendChild(xmlDocLicenseSignature);
            XmlDocumentFragment publicKeyNode = licenseDocument.CreateDocumentFragment();
            publicKeyNode.InnerXml = publicKey;
            parentNode.AppendChild(publicKeyNode);
            licenseDocument.Save(Environment.CurrentDirectory + @"\licenseinfo.xml");
        }
 /// <summary>
 /// Calculate the signature of <paramref name="data"/>
 /// </summary>
 /// <param name="data">The data to sign</param>
 /// <param name="consumerSecret">The consumer secret</param>
 /// <param name="tokenSecret">The token secret</param>
 /// <returns>The signature</returns>
 public string CalculateSignature(byte[] data, string consumerSecret, string tokenSecret)
 {
     var signatureFormatter = new RSAPKCS1SignatureFormatter(_privateKey);
     signatureFormatter.SetHashAlgorithm("SHA1");
     using (var hasher = HashAlgorithm.Create("SHA1"))
     {
         Debug.Assert(hasher != null, "hasher != null");
         var hash = hasher.ComputeHash(data);
         var signature = signatureFormatter.CreateSignature(hash);
         return Convert.ToBase64String(signature);
     }
 }
Exemple #13
0
        public byte[] Sign(byte[] securedInput, object key)
        {
            using (var sha = HashAlgorithm)
            {
                var privateKey = Ensure.Type<AsymmetricAlgorithm>(key, "RsaUsingSha alg expects key to be of AsymmetricAlgorithm type."); 

                var pkcs1 = new RSAPKCS1SignatureFormatter(privateKey);
                pkcs1.SetHashAlgorithm(hashMethod);

                return pkcs1.CreateSignature(sha.ComputeHash(securedInput));                    
            } 
        }
		public byte[] SignData(byte[] hashOfDataToSign)
		{
			using (var rsa = new RSACryptoServiceProvider(2048))
			{
				rsa.PersistKeyInCsp = false;
				rsa.ImportParameters(_privateKey);

				var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
				rsaFormatter.SetHashAlgorithm("SHA256");

				return rsaFormatter.CreateSignature(hashOfDataToSign);
			}
		}
Exemple #15
0
		/// <summary>
		/// RSA签名
		/// </summary>
		/// <param name="PlainText">原始字符串</param>
		/// <param name="xmlString">密钥(公钥私钥俱有)</param>
		/// <returns>Base64编码后的已签名字符串</returns>
		public static string SignString(string PlainText, string xmlString)
		{
			RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
			rsa.FromXmlString(xmlString);

			RSAPKCS1SignatureFormatter f = new RSAPKCS1SignatureFormatter(rsa);
			f.SetHashAlgorithm("SHA1");
			byte[] bText = System.Text.Encoding.UTF8.GetBytes(PlainText);
			SHA1Managed sha = new SHA1Managed();
			byte[] hText = sha.ComputeHash(bText);
			byte[] bEnc = f.CreateSignature(hText);
			return System.Convert.ToBase64String(bEnc);
		}
        private string GenerateSignature(OAuthContext authContext, SigningContext signingContext)
        {
            if (signingContext.Algorithm == null) throw Error.AlgorithmPropertyNotSetOnSigningContext();

            SHA1CryptoServiceProvider sha1 = GenerateHash(signingContext);

            var formatter = new RSAPKCS1SignatureFormatter(signingContext.Algorithm);
            formatter.SetHashAlgorithm("MD5");

            byte[] signature = formatter.CreateSignature(sha1);

            return Convert.ToBase64String(signature);
        }
Exemple #17
0
        /// <summary>
        /// デジタル署名を作成する
        /// </summary>
        /// <param name="message">署名を付けるメッセージ</param>
        /// <param name="privateKey">署名に使用する秘密鍵</param>
        /// <returns>作成された署名</returns>
        public static byte[] CreateDigitalSignature_SHA1(byte[] message, string privateKey)
        {
            byte[] hashData = SHA1.Create().ComputeHash(message);

            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(privateKey);

                RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
                rsaFormatter.SetHashAlgorithm("SHA1");
                return rsaFormatter.CreateSignature(hashData);
            }
        }
Exemple #18
0
        static byte[] CreateStrongName(StrongNameKeyPair key_pair, byte [] hash)
        {
            const string hash_algo = "SHA1";

            using (var rsa = key_pair.CreateRSA ()) {
                var formatter = new RSAPKCS1SignatureFormatter (rsa);
                formatter.SetHashAlgorithm (hash_algo);

                byte [] signature = formatter.CreateSignature (hash);
                Array.Reverse (signature);

                return signature;
            }
        }
Exemple #19
0
        static void Main(string[] args)
        {
            string pubKey = ConfigurationManager.AppSettings["pubKey"];
            string priKey = ConfigurationManager.AppSettings["priKey"];
            string input = ConfigurationManager.AppSettings["input"];
            string user = ConfigurationManager.AppSettings["user"];

            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                SHA1Managed sha = new SHA1Managed();
                rsa.FromXmlString(priKey);
                Console.WriteLine("begin to encode:");
                RSAPKCS1SignatureFormatter signFormatter = new RSAPKCS1SignatureFormatter(rsa);
                signFormatter.SetHashAlgorithm("SHA1");
                byte[] source = System.Text.ASCIIEncoding.UTF8.GetBytes(input);
                byte[] result = sha.ComputeHash(source);
                byte[] b = signFormatter.CreateSignature(result);
                var signature = Convert.ToBase64String(b);

                string outputFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sn", input + ".key");
                FileInfo fi = new FileInfo(outputFile);
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }
                StreamWriter sw = new StreamWriter(fi.OpenWrite(), Encoding.UTF8);
                sw.Write(signature);
                sw.Close();
                Console.WriteLine();
                Console.WriteLine(signature);

                using (RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider())
                {
                    rsa2.FromXmlString(pubKey);
                    RSAPKCS1SignatureDeformatter decodeFormatter = new RSAPKCS1SignatureDeformatter(rsa2);
                    decodeFormatter.SetHashAlgorithm("SHA1");
                    byte[] key = Convert.FromBase64String(signature);
                    byte[] name = sha.ComputeHash(ASCIIEncoding.UTF8.GetBytes(input));
                    if (decodeFormatter.VerifySignature(name, key))
                    {
                        Console.WriteLine("===========can be decoded");
                    }
                    else
                    {
                        Console.WriteLine("===CANOT be decoded..................");
                    }
                }
            }
        }
Exemple #20
0
 private byte[] sign(byte[] message)
 {
     if (certificate.PrivateKey == null)
     {
         throw new Exception("a private key is required when generating RSA-SHA1 signatures.");
     }
     using (HashAlgorithm hasher = HashAlgorithm.Create("SHA1"))
     {
         RSAPKCS1SignatureFormatter signatureFormatter = new RSAPKCS1SignatureFormatter();
         signatureFormatter.SetKey(certificate.PrivateKey);
         signatureFormatter.SetHashAlgorithm("SHA1");
         byte[] hash = hasher.ComputeHash(message);
         return signatureFormatter.CreateSignature(hash);
     }
 }
Exemple #21
0
 public void MakeSign()
 {
     var returnStr = GetSign();
     byte[] bytes = System.Text.Encoding.UTF8.GetBytes(returnStr);
     var privateKey = CoreHelper.CustomSetting.GetConfigKey("快钱WEB私钥文件");
     var pass = CoreHelper.CustomSetting.GetConfigKey("快钱WEB私钥文件密码");
     X509Certificate2 cert = new X509Certificate2(privateKey, pass, X509KeyStorageFlags.MachineKeySet);
     RSACryptoServiceProvider rsapri = (RSACryptoServiceProvider)cert.PrivateKey;
     RSAPKCS1SignatureFormatter f = new RSAPKCS1SignatureFormatter(rsapri);
     byte[] result;
     f.SetHashAlgorithm("SHA1");
     SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
     result = sha.ComputeHash(bytes);
     var signMsg2 = System.Convert.ToBase64String(f.CreateSignature(result)).ToString();
     signMsg = signMsg2;
 }
Exemple #22
0
        //RSA签名
        public bool SignatureFormatter(string pStrKeyPrivate, string mStrHashbyteSignature, ref string mStrEncryptedSignatureData)
        {
            var hashbyteSignature = Convert.FromBase64String(mStrHashbyteSignature);

            System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();

            rsa.FromXmlString(pStrKeyPrivate);
            System.Security.Cryptography.RSAPKCS1SignatureFormatter rsaFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(rsa);
            //设置签名的算法为MD5
            rsaFormatter.SetHashAlgorithm("MD5");
            //执行签名
            var encryptedSignatureData = rsaFormatter.CreateSignature(hashbyteSignature);

            mStrEncryptedSignatureData = Convert.ToBase64String(encryptedSignatureData);

            return(true);
        }
        public bool SignatureFormatter(string p_strKeyPrivate, byte[] hashbyteSignature, ref byte[] encryptedSignatureData)

        {
            var RSA = new System.Security.Cryptography.RSACryptoServiceProvider();



            RSA.FromXmlString(p_strKeyPrivate);

            var RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);

            RSAFormatter.SetHashAlgorithm("MD5");

            encryptedSignatureData = RSAFormatter.CreateSignature(hashbyteSignature);

            return(true);
        }
Exemple #24
0
        //RSA签名
        public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData)
        {
            byte[] EncryptedSignatureData;

            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

            RSA.FromXmlString(p_strKeyPrivate);
            System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
            //设置签名的算法为MD5
            RSAFormatter.SetHashAlgorithm("MD5");
            //执行签名
            EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);

            m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);

            return(true);
        }
Exemple #25
0
        public string Encypt(string OriginalText)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(prikey);
                //使用私钥来加密对象
                RSAPKCS1SignatureFormatter f = new RSAPKCS1SignatureFormatter(rsa);
                f.SetHashAlgorithm("SHA1");

                byte[] source = System.Text.ASCIIEncoding.ASCII.GetBytes(OriginalText);
                SHA1Managed sha = new SHA1Managed();
                byte[] result = sha.ComputeHash(source);
                byte[] b = f.CreateSignature(result);

                return Convert.ToBase64String(b);
            }
        }
Exemple #26
0
 /// <summary>
 /// RSA签名
 /// </summary>
 /// <param name="strKeyPrivate">私钥</param>
 /// <param name="HashbyteSignature">待签名Hash描述</param>
 /// <param name="EncryptedSignatureData">签名后的结果</param>
 /// <returns></returns>
 public bool SignatureFormatter(string strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
 {
     try
     {
         System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
         RSA.FromXmlString(strKeyPrivate);
         System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
         //设置签名的算法为MD5
         RSAFormatter.SetHashAlgorithm("MD5");
         //执行签名
         EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
         return(true);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemple #27
0
        public byte[] Sign(byte[] securedInput, object key)
        {
            #if NET40
            var privateKey = Ensure.Type<RSA>(key, "RsaUsingSha alg expects key to be of AsymmetricAlgorithm type.");

            using (var sha = HashAlgorithm)
            {

                var pkcs1 = new RSAPKCS1SignatureFormatter(privateKey);
                pkcs1.SetHashAlgorithm(hashMethod);

                return pkcs1.CreateSignature(sha.ComputeHash(securedInput));
            }

            #elif NETSTANDARD1_4
            var privateKey = Ensure.Type<RSA>(key, "RsaUsingSha alg expects key to be of RSA type.");
                return privateKey.SignData(securedInput, HashAlgorithm, RSASignaturePadding.Pkcs1);
            #endif
        }
 /// <summary>
 /// RSA签名
 /// </summary>
 /// <param name="priRSA">私钥RSA</param>
 /// <param name="strHashbyteSignature">待签名Hash描述</param>
 /// <param name="strEncryptedSignatureData">签名后的结果</param>
 /// <returns></returns>
 public static bool SignatureFormatter(System.Security.Cryptography.RSACryptoServiceProvider priRSA, string strHashbyteSignature, out string strEncryptedSignatureData)
 {
     try
     {
         byte[] HashbyteSignature;
         byte[] EncryptedSignatureData;
         HashbyteSignature = Convert.FromBase64String(strHashbyteSignature);
         System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(priRSA);
         //设置签名的算法为MD5
         RSAFormatter.SetHashAlgorithm("MD5");
         //执行签名
         EncryptedSignatureData    = RSAFormatter.CreateSignature(HashbyteSignature);
         strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
         return(true);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemple #29
0
        /// <summary>
        /// 生成RSA签名
        /// </summary>
        /// <param name="content">数据</param>
        /// <param name="privateKeyPath">RSA私钥路径</param>
        /// <param name="password">RSA私钥密码</param>
        /// <returns></returns>
        public static byte[] BuildRsaSHA1Signature(this string content, string privateKeyPath, string password)
        {
            if (!System.IO.File.Exists(privateKeyPath))
            {
                throw new FileNotExistsException(privateKeyPath);
            }

            if (!System.IO.File.Exists(privateKeyPath))
            {
                throw new Maydear.Exceptions.ArgumentNullException(privateKeyPath);
            }

            X509Certificate2 x509Certificate = new X509Certificate2(privateKeyPath, password);

            var signatureFormatter = new RSAPKCS1SignatureFormatter(x509Certificate.PrivateKey);

            signatureFormatter.SetHashAlgorithm(HashAlgorithmName.SHA1.Name);
            byte[] bytes = signatureFormatter.CreateSignature(content.ToBytes());
            return(bytes);
        }
 /// <summary>
 /// RSA签名
 /// </summary>
 /// <param name="strKeyPrivate">私钥</param>
 /// <param name="HashbyteSignature">待签名Hash描述</param>
 /// <param name="m_strEncryptedSignatureData">签名后的结果</param>
 /// <returns></returns>
 public static bool SignatureFormatter(string strKeyPrivate, byte[] HashbyteSignature, out string strEncryptedSignatureData)
 {
     try
     {
         byte[] EncryptedSignatureData;
         System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
         strKeyPrivate = regBitStrength.Replace(strKeyPrivate, "");
         RSA.FromXmlString(strKeyPrivate);
         System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
         //设置签名的算法为MD5
         RSAFormatter.SetHashAlgorithm("MD5");
         //执行签名
         EncryptedSignatureData    = RSAFormatter.CreateSignature(HashbyteSignature);
         strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
         return(true);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemple #31
0
             /// <summary>  
             /// RSA签名  
             /// </summary>  
             /// <param name="strKeyPrivate">私钥</param>  
             /// <param name="strHashbyteSignature">待签名Hash描述</param>  
             /// <param name="EncryptedSignatureData">签名后的结果</param>  
             /// <returns></returns>  
            public bool SignatureFormatter(string strKeyPrivate,  string strHashbyteSignature,  ref byte[]  EncryptedSignatureData)   
            
        {
              
                    try  
                     {
                  
                            byte[]  HashbyteSignature;   
                  
                                HashbyteSignature  =  Convert.FromBase64String(strHashbyteSignature);   

                            System.Security.Cryptography.RSACryptoServiceProvider RSA  =  new System.Security.Cryptography.RSACryptoServiceProvider();   
                  
                  
                            RSA.FromXmlString(strKeyPrivate);   

                            System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter  =  new System.Security.Cryptography.RSAPKCS1SignatureFormatter  
                                                                                                      
                                                                                                        (RSA);   
                             //设置签名的算法为MD5   
                            RSAFormatter.SetHashAlgorithm("MD5");   
                             //执行签名   
                                EncryptedSignatureData  =  RSAFormatter.CreateSignature(HashbyteSignature);   
                  
                                return true;   

                            
            }   
                    catch (Exception ex)   
                    
            {
                  
                                throw ex;   

                            
            }

              
                        
        }
Exemple #32
0
 /// <summary>
 /// RSA签名
 /// </summary>
 /// <param name="strKeyPrivate">私钥</param>
 /// <param name="strHashbyteSignature">待签名Hash描述</param>
 /// <param name="strEncryptedSignatureData">签名后的结果</param>
 /// <returns></returns>
 public bool SignatureFormatter(string strKeyPrivate, string strHashbyteSignature, ref string strEncryptedSignatureData)
 {
     try
     {
         byte[] HashbyteSignature;
         byte[] EncryptedSignatureData;
         HashbyteSignature = Convert.FromBase64String(strHashbyteSignature);
         System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
         //RSA.FromXmlString(strKeyPrivate);
         RSA.ImportCspBlob(Convert.FromBase64String(strKeyPrivate));//载入钥
         System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
         //设置签名的算法为MD5
         RSAFormatter.SetHashAlgorithm("MD5");
         //执行签名
         EncryptedSignatureData    = RSAFormatter.CreateSignature(HashbyteSignature);
         strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
         return(true);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public string rtnUrl = ""; //定义显示结果show页面地址

        #endregion Fields

        #region Methods

        //
        // GET: /99Bill/
        public static string CerRSASignature(string OriginalString, string prikey_path, string CertificatePW, int SignType)
        {
            byte[] OriginalByte = System.Text.Encoding.UTF8.GetBytes(OriginalString);
            X509Certificate2 x509_Cer1 = new X509Certificate2(prikey_path, CertificatePW);
            RSACryptoServiceProvider rsapri = (RSACryptoServiceProvider)x509_Cer1.PrivateKey;
            RSAPKCS1SignatureFormatter f = new RSAPKCS1SignatureFormatter(rsapri);
            byte[] result;
            switch (SignType)
            {
                case 1:
                    f.SetHashAlgorithm("MD5");//摘要算法MD5
                    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                    result = md5.ComputeHash(OriginalByte);//摘要值
                    break;
                default:
                    f.SetHashAlgorithm("SHA1");//摘要算法SHA1
                    SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
                    result = sha.ComputeHash(OriginalByte);//摘要值
                    break;
            }
            string SignData = System.Convert.ToBase64String(f.CreateSignature(result)).ToString();

            return SignData;
        }
        private string CriptografarReferencia(string referencia, X509Certificate2 certificado)
        {

            RSACryptoServiceProvider rsa = certificado.PrivateKey as RSACryptoServiceProvider;
            byte[] sAssinaturaByte = new ASCIIEncoding().GetBytes(referencia);
            RSAPKCS1SignatureFormatter rsaf = new RSAPKCS1SignatureFormatter(rsa);
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            byte[] hash = sha1.ComputeHash(sAssinaturaByte);

            rsaf.SetHashAlgorithm("SHA1");
            sAssinaturaByte = rsaf.CreateSignature(hash);

            return Convert.ToBase64String(sAssinaturaByte);
        }
Exemple #35
0
 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
 {
     RSACryptoServiceProvider provider1 = new RSACryptoServiceProvider();
     provider1.FromXmlString(p_strKeyPrivate);
     RSAPKCS1SignatureFormatter formatter1 = new RSAPKCS1SignatureFormatter(provider1);
     formatter1.SetHashAlgorithm("MD5");
     EncryptedSignatureData = formatter1.CreateSignature(HashbyteSignature);
     return true;
 }
Exemple #36
0
 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
 {
     byte[] buffer1 = Convert.FromBase64String(m_strHashbyteSignature);
     RSACryptoServiceProvider provider1 = new RSACryptoServiceProvider();
     provider1.FromXmlString(p_strKeyPrivate);
     RSAPKCS1SignatureFormatter formatter1 = new RSAPKCS1SignatureFormatter(provider1);
     formatter1.SetHashAlgorithm("MD5");
     byte[] buffer2 = formatter1.CreateSignature(buffer1);
     m_strEncryptedSignatureData = Convert.ToBase64String(buffer2);
     return true;
 }
Exemple #37
0
 /// <summary>
 /// 对MD5加密后的密文进行签名
 /// </summary>
 /// <param name="p_strKeyPrivate">私钥</param>
 /// <param name="m_strHashbyteSignature">MD5加密后的密文</param>
 /// <returns></returns>
 public string SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature)
 {
     byte[] rgbHash = Convert.FromBase64String(m_strHashbyteSignature);
     RSACryptoServiceProvider key = new RSACryptoServiceProvider();
     key.FromXmlString(p_strKeyPrivate);
     RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key);
     formatter.SetHashAlgorithm("MD5");
     byte[] inArray = formatter.CreateSignature(rgbHash);
     return Convert.ToBase64String(inArray);
 }
 /// <summary>
 /// RSA签名
 /// </summary>
 /// <param name="md5StrSrc">需要签名的密文</param>
 /// <returns>base64格式的签名</returns>
 public static string System_Sign_RSA_en(string md5StrSrc)
 {
     try
     {
         RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
         rsa.FromXmlString(GetKey());
         RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(rsa);
         formatter.SetHashAlgorithm("MD5");
         byte[] hashbytes = MD5Str(md5StrSrc);
         byte[] inArray = formatter.CreateSignature(hashbytes);
         return Convert.ToBase64String(inArray);
     }
     catch (Exception)
     {
         return "";
     }
 }
Exemple #39
0
/// <summary> 
	/// RSA加密解密及RSA签名和验证
	/// </summary> 
public class RSA
{
	#region RSA 加密解密 

	#region RSA 的密钥产生 
	/// <summary>
	/// RSA 的密钥产生 产生私钥 和公钥 
	/// </summary>
	/// <param name="xmlKeys"></param>
	/// <param name="xmlPublicKey"></param>
	public Tuple<string,string> generateKey()
	{
		System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
		string xmlKeys = rsa.ToXmlString(true);
		string xmlPublicKey = rsa.ToXmlString(false);
		return Tuple.Create<string, string>(xmlKeys, xmlPublicKey);
	}
	#endregion

	#region RSA的加密函数 
	//############################################################################## 
	//RSA 方式加密 
	//说明KEY必须是XML的行式,返回的是字符串 
	//在有一点需要说明!!该加密方式有 长度 限制的!! 
	//############################################################################## 

	//RSA的加密函数  string
	public string encrypt(string xmlPublicKey, string m_strEncryptString)
	{

		byte[] PlainTextBArray;
		byte[] CypherTextBArray;
		string Result;
		RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
		rsa.FromXmlString(xmlPublicKey);
		PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString);
		CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
		Result = Convert.ToBase64String(CypherTextBArray);
		return Result;

	}
	//RSA的加密函数 byte[]
	public string encrypt(string xmlPublicKey, byte[] EncryptString)
	{

		byte[] CypherTextBArray;
		string Result;
		RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
		rsa.FromXmlString(xmlPublicKey);
		CypherTextBArray = rsa.Encrypt(EncryptString, false);
		Result = Convert.ToBase64String(CypherTextBArray);
		return Result;

	}
	#endregion

	#region RSA的解密函数 
	//RSA的解密函数  string
	public string decrypt(string xmlPrivateKey, string m_strDecryptString)
	{
		byte[] PlainTextBArray;
		byte[] DypherTextBArray;
		string Result;
		System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
		rsa.FromXmlString(xmlPrivateKey);
		PlainTextBArray = Convert.FromBase64String(m_strDecryptString);
		DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
		Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
		return Result;

	}

	//RSA的解密函数  byte
	public string decrypt(string xmlPrivateKey, byte[] DecryptString)
	{
		byte[] DypherTextBArray;
		string Result;
		System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
		rsa.FromXmlString(xmlPrivateKey);
		DypherTextBArray = rsa.Decrypt(DecryptString, false);
		Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
		return Result;

	}
	#endregion

	#endregion

	#region RSA数字签名 

	#region 获取Hash描述表 
	//获取Hash描述表 
	public bool GetHash(string m_strSource, ref byte[] HashData)
	{
		//从字符串中取得Hash描述 
		byte[] Buffer;
		System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
		Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
		HashData = MD5.ComputeHash(Buffer);

		return true;
	}

	//获取Hash描述表 
	public bool GetHash(string m_strSource, ref string strHashData)
	{

		//从字符串中取得Hash描述 
		byte[] Buffer;
		byte[] HashData;
		System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
		Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
		HashData = MD5.ComputeHash(Buffer);

		strHashData = Convert.ToBase64String(HashData);
		return true;

	}

	//获取Hash描述表 
	public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData)
	{

		//从文件中取得Hash描述 
		System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
		HashData = MD5.ComputeHash(objFile);
		objFile.Close();

		return true;

	}

	//获取Hash描述表 
	public bool GetHash(System.IO.FileStream objFile, ref string strHashData)
	{

		//从文件中取得Hash描述 
		byte[] HashData;
		System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
		HashData = MD5.ComputeHash(objFile);
		objFile.Close();

		strHashData = Convert.ToBase64String(HashData);

		return true;

	}
	#endregion

	#region RSA签名 
	//RSA签名 
	public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
	{

		System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

		RSA.FromXmlString(p_strKeyPrivate);
		System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
		//设置签名的算法为MD5 
		RSAFormatter.SetHashAlgorithm("MD5");
		//执行签名 
		EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);

		return true;

	}

	//RSA签名 
	public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData)
	{

		byte[] EncryptedSignatureData;

		System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

		RSA.FromXmlString(p_strKeyPrivate);
		System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
		//设置签名的算法为MD5 
		RSAFormatter.SetHashAlgorithm("MD5");
		//执行签名 
		EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);

		m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);

		return true;

	}

	//RSA签名 
	public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref byte[] EncryptedSignatureData)
	{

		byte[] HashbyteSignature;

		HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
		System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

		RSA.FromXmlString(p_strKeyPrivate);
		System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
		//设置签名的算法为MD5 
		RSAFormatter.SetHashAlgorithm("MD5");
		//执行签名 
		EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);

		return true;

	}

	//RSA签名 
	public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
	{

		byte[] HashbyteSignature;
		byte[] EncryptedSignatureData;

		HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
		System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

		RSA.FromXmlString(p_strKeyPrivate);
		System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
		//设置签名的算法为MD5 
		RSAFormatter.SetHashAlgorithm("MD5");
		//执行签名 
		EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);

		m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);

		return true;

	}
	#endregion

	#region RSA 签名验证 

	public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData)
	{

		System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

		RSA.FromXmlString(p_strKeyPublic);
		System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
		//指定解密的时候HASH算法为MD5 
		RSADeformatter.SetHashAlgorithm("MD5");

		if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
		{
			return true;
		}
		else
		{
			return false;
		}

	}

	public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, byte[] DeformatterData)
	{

		byte[] HashbyteDeformatter;

		HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);

		System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

		RSA.FromXmlString(p_strKeyPublic);
		System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
		//指定解密的时候HASH算法为MD5 
		RSADeformatter.SetHashAlgorithm("MD5");

		if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
		{
			return true;
		}
		else
		{
			return false;
		}

	}

	public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, string p_strDeformatterData)
	{

		byte[] DeformatterData;

		System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

		RSA.FromXmlString(p_strKeyPublic);
		System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
		//指定解密的时候HASH算法为MD5 
		RSADeformatter.SetHashAlgorithm("MD5");

		DeformatterData = Convert.FromBase64String(p_strDeformatterData);

		if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
		{
			return true;
		}
		else
		{
			return false;
		}

	}

	public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
	{

		byte[] DeformatterData;
		byte[] HashbyteDeformatter;

		HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
		System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

		RSA.FromXmlString(p_strKeyPublic);
		System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
		//指定解密的时候HASH算法为MD5 
		RSADeformatter.SetHashAlgorithm("MD5");

		DeformatterData = Convert.FromBase64String(p_strDeformatterData);

		if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
		{
			return true;
		}
		else
		{
			return false;
		}

	}
}

	#endregion


	#endregion
Exemple #40
0
        //RSAǩ��
        public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
        {
            byte[] HashbyteSignature;
                byte[] EncryptedSignatureData;

                HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
                System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();

                RSA.FromXmlString(p_strKeyPrivate);
                System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
                //����ǩ�����㷨ΪMD5
                RSAFormatter.SetHashAlgorithm("MD5");
                //ִ��ǩ��
                EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);

                m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);

                return true;
        }