SignData() public method

Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
public SignData ( Stream inputStream, Object halg ) : byte[]
inputStream System.IO.Stream The input data for which to compute the hash
halg Object The hash algorithm to use to create the hash value.
return byte[]
Example #1
0
        public string SignAuthCookieV1(string cookie)
        {
            byte[] privateKey = this.GetPrivateKey(KeyType.AuthCookieV1);

            //// The array to store the signed message in bytes
            byte[] signedBytes;
            using (var rsa = new RSACryptoServiceProvider())
            {
                // Write the message to a byte array using UTF8 as the encoding.

                byte[] originalData = System.Text.Encoding.UTF8.GetBytes(cookie);

                try
                {
                    // Import the private key used for signing the message
                    rsa.ImportParameters(SecureSigningService.FromBinaryToRSAParameters(privateKey));

                    signedBytes = rsa.SignData(originalData, CryptoConfig.MapNameToOID("SHA512"));
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                    return null;
                }
                finally
                {
                    //// Set the keycontainer to be cleared when rsa is garbage collected.
                    rsa.PersistKeyInCsp = false;
                }
            }

            // Convert the a base64 string before returning
            return Convert.ToBase64String(signedBytes);
        }
Example #2
0
        /// <summary>
        /// 证书方式签名(多证书时使用),指定证书路径。
        /// </summary>
        /// <param name="reqData">请求的数据源</param>
        /// <param name="certRawData">证书数据</param>
        /// <param name="certPwd">证书密码</param>
        /// <param name="encoding">编码方式</param>
        public static void SignByCertInfo(Dictionary <string, string> reqData, byte[] certRawData, string certPwd, Encoding encoding)
        {
            var cert = new X509Certificate2(certRawData, certPwd, X509KeyStorageFlags.Exportable);

            reqData["certId"] = new System.Numerics.BigInteger(cert.GetSerialNumber()).ToString();

            //将Dictionary信息转换成key1=value1&key2=value2的形式
            string stringData = SDKUtil.CreateLinkString(reqData, true, false, encoding);

            byte[] signDigest       = System.Security.Cryptography.SHA256.Create().ComputeHash(encoding.GetBytes(stringData));
            string stringSignDigest = SDKUtil.ByteArray2HexString(signDigest);

            //bug 修复,类型对不上, 直接继承公共的基类,避免类型错误。
            var rsa = cert.PrivateKey as System.Security.Cryptography.RSA;

            // Create a new RSACryptoServiceProvider
            var rsaClear = new System.Security.Cryptography.RSACryptoServiceProvider();

            // Export RSA parameters from 'rsa' and import them into 'rsaClear'
            rsaClear.ImportParameters(rsa.ExportParameters(true));
            byte[] byteSign = rsaClear.SignData(encoding.GetBytes(stringSignDigest), System.Security.Cryptography.SHA256.Create());

            string stringSign = Convert.ToBase64String(byteSign);

            //设置签名域值
            reqData["signature"] = stringSign;
        }
        static void Main(string[] args)
        {
            // Create digital signature algortihm object
            // This will generate private/public key pair
            RSACryptoServiceProvider signer = new RSACryptoServiceProvider();

            // array to hold signature - will be shared
            byte[] signature = null;
            // string to hold public key - will be shared
            string publicKey = null;

            using(FileStream file = new FileStream(@"info.txt", FileMode.Open,
                FileAccess.Read))
            {
                // read file to be used to create signature into a byte array
                BinaryReader reader = new BinaryReader(file);
                byte[] data = reader.ReadBytes((int)file.Length);

                // create signature by signing data - generates a digital signature by first
                // generating the hash the data and then generate a signature based on the
                // hash and the private key
                // file, signature and public key are then shared with the recipient
                signature = signer.SignData(data,new SHA1CryptoServiceProvider());

                // export public key
                publicKey = signer.ToXmlString(false);

                reader.Close();
                file.Close();
            }

            // Create digital signature algortihm object
            // which will use the public key exported by the signer
            RSACryptoServiceProvider verifier = new RSACryptoServiceProvider();
            verifier.FromXmlString(publicKey);

            using (FileStream file2 = new FileStream(@"info.txt", FileMode.Open,
                FileAccess.Read))
            {
                // read file to be used to verify the signature into a byte array
                BinaryReader reader2 = new BinaryReader(file2);
                byte[] data2 = reader2.ReadBytes((int)file2.Length);

                // verify the signature based on the contents of the file
                // verification will only succeed if the signature was generated from this
                // file using the correct private key, thus confirming the identity of the
                // signer
                if (verifier.VerifyData(data2, new SHA1CryptoServiceProvider(), signature))
                {
                    Console.WriteLine("Verified");
                }
                else
                {
                    Console.WriteLine("NOT verified");
                }

                reader2.Close();
                file2.Close();
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            RSACryptoServiceProvider signer = new RSACryptoServiceProvider();

            FileStream file = new FileStream(args[0], FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(file);
            byte[] data = reader.ReadBytes((int)file.Length);

            byte[] signature = signer.SignData(data, new SHA256CryptoServiceProvider());

            string publicKey = signer.ToXmlString(false);

            Console.WriteLine("Signature: " + Convert.ToBase64String(signature));
            reader.Close();
            file.Close();

            RSACryptoServiceProvider verifier = new RSACryptoServiceProvider();

            verifier.FromXmlString(publicKey);

            FileStream file2 = new FileStream(args[0], FileMode.Open, FileAccess.Read);
            BinaryReader reader2 = new BinaryReader(file2);
            byte[] data2 = reader2.ReadBytes((int)file2.Length);

            if (verifier.VerifyData(data2, new SHA256CryptoServiceProvider(), signature))
                Console.WriteLine("Signature verified");
            else 
                Console.WriteLine("Signature NOT verified");
            reader2.Close();
            file2.Close();
        }
Example #5
0
        public static string SignData(string originalMessage, RSAParameters Parameters)
        {
            string success = "";
            var encoder = new UTF8Encoding();
            byte[] bytesToSign = encoder.GetBytes(originalMessage);

            RSAParameters parameters = Parameters;

            using (var rsa = new RSACryptoServiceProvider())
            {
                try
                {
                    rsa.ImportParameters(parameters);
                    SHA256Managed Hash = new SHA256Managed();

                    byte[] hashedData = Hash.ComputeHash(bytesToSign);
                    success = Convert.ToBase64String(rsa.SignData(hashedData, CryptoConfig.MapNameToOID("SHA256")));
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
            return success;
        }
        /// <summary>
        /// Metoda za digitalno potpisivanje dokumenta
        /// </summary>
        /// <param name="file"></param>
        public void MakeDigitalSignature(string file)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            StreamReader streamReader = new StreamReader("privatni_kljuc.txt");
            string publicOnlyKeyXml = streamReader.ReadToEnd();
            rsa.FromXmlString(publicOnlyKeyXml);

            streamReader.Close();
            streamReader.Dispose();

            FileStream dat = new FileStream(file, FileMode.Open, FileAccess.Read);

            BinaryReader binReader = new BinaryReader(dat);
            byte[] data = binReader.ReadBytes((int)dat.Length);
            byte[] sign = rsa.SignData(data, "SHA1");

            binReader.Close();
            binReader.Dispose();
            dat.Close();
            dat.Dispose();

            string datName = file + ".dp";

            TextWriter tw = new StreamWriter(datName);
            tw.WriteLine(Convert.ToBase64String(sign));
            tw.Close();
            tw.Dispose();
        }
Example #7
0
        static void Main(string[] args)
        {
            // Create message and signature on your end
            string message = "Here is the license message";
            var secret = "wangchunlei";
            var converter = new ASCIIEncoding();
            byte[] plainText = converter.GetBytes(secret);

            var rsaWrite = new RSACryptoServiceProvider();
            var privateParams = rsaWrite.ExportParameters(true);

            // Generate the public key / these can be sent to the user.
            var publicParams = rsaWrite.ExportParameters(false);

            byte[] signature =
                rsaWrite.SignData(plainText, new SHA1CryptoServiceProvider());

            // Verify from the user's side. Note that only the public parameters
            // are needed.
            var rsaRead = new RSACryptoServiceProvider();
            rsaRead.ImportParameters(publicParams);
            if (rsaRead.VerifyData(plainText,
                                new SHA1CryptoServiceProvider(),
                                signature))
            {
                Console.WriteLine("Verified!");
            }
            else
            {
                Console.WriteLine("NOT verified!");
            }
        }
Example #8
0
        public string Calculate(string input, RSACryptoServiceProvider provider)
        {
            byte[] podatki = Encoding.ASCII.GetBytes(input);
              byte[] signature = provider.SignData(podatki, CryptoConfig.MapNameToOID("SHA256"));

              return this.CalculateMD5Hash(signature);
        }
Example #9
0
        public static string SignData(byte[] message, RSAParameters privateKey)
        {
            //// The array to store the signed message in bytes
            byte[] signedBytes;
            using (var rsa = new RSACryptoServiceProvider())
            {
                byte[] originalData = message;

                try
                {
                    //// Import the private key used for signing the message
                    rsa.ImportParameters(privateKey);

                    //// Sign the data, using SHA512 as the hashing algorithm
                    signedBytes = rsa.SignData(originalData, CryptoConfig.MapNameToOID("SHA512"));
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                    return null;
                }
                finally
                {
                    //// Set the keycontainer to be cleared when rsa is garbage collected.
                    rsa.PersistKeyInCsp = false;
                }
            }
            //// Convert the a base64 string before returning
            return Convert.ToBase64String(signedBytes);
        }
Example #10
0
        static void Main(string[] args)
        {
            // To idendify the Smart Card CryptoGraphic Providers on your
            // computer, use the Microsoft Registry Editor (Regedit.exe).
            // The available Smart Card CryptoGraphic Providers are listed
            // in HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider.

            // Create a new CspParameters object that identifies a
            // Smart Card CryptoGraphic Provider.
            // The 1st parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider Types.
            // The 2nd parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider.
            CspParameters csp = new CspParameters(1);
            csp.KeyContainerName = "MyKeyContainer ya!!";
            csp.Flags = CspProviderFlags.UseDefaultKeyContainer;

            // Initialize an RSACryptoServiceProvider object using
            // the CspParameters object.
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);
            Console.WriteLine("KeyName:{0}", rsa.ToXmlString(true));

            // Create some data to sign.
            byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };

            Console.WriteLine("Data			: " + BitConverter.ToString(data, 0, data.Length));

            // Sign the data using the Smart Card CryptoGraphic Provider.
            byte[] signData = rsa.SignData(data, "SHA1");

            Console.WriteLine("Signature:" + BitConverter.ToString(signData));

            bool verify = rsa.VerifyData(data, "SHA1", signData);//原始資料和sign過的資料作SHA1比對
            Console.WriteLine("驗證資料:" + verify);

            Console.ReadKey();
        }
Example #11
0
        public virtual System.Web.Mvc.ActionResult BankGateway(float totalPrice, int totalCount)
        {
            System.Guid userId    = Infrastructure.Sessions.AuthenticatedUser.Id;
            var         varOrders = UnitOfWork.OrdersRepository.Get()
                                    .Include(p => p.Products)
                                    .Where(current => current.userId == userId)
                                    .Where(current => current.IsActive == true)
                                    .Where(current => current.Products.IsActive == true).ToList();



            System.Random oRandom = new System.Random();
            oRandom.Next(1093250, 10000000); // minimum = 0, maximum = 1000


            Models.PayOnline oPayOnline = new Models.PayOnline
            {
                Id        = new System.Guid(),
                userId    = Infrastructure.Sessions.AuthenticatedUser.Id,
                OrderNo   = totalCount.ToString(),
                ReceiptNo = oRandom.ToString(),
                Payment   = totalPrice
            };

            //var varCustomersProfile = UnitOfWork.CustomersProfileRepository.Get()
            //    .Include(u => u.User)
            //    .Where(current => current.UserId == userId).ToList();

            if (varOrders.Count > 0)
            {
                RSACryptoServiceProvider.UseMachineKeyStore = true;
                string merchantCode = "321008";              //کد پذيرنده  //
                string terminalCode = "325160";              //کد ترمينال //
                string amount       = totalPrice.ToString(); // مبلغ فاکتور //
                //BankGatewayRedirect();
                // :  آدرس سايتی که مشتری پس از انجام تراکنش بايد به آن فرستاده شود //
                string redirectAddress = "http://amad-co.ir/BankGateway.cshtml";
                string timeStamp       = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                string invoiceNumber   = "515";                                               // شماره فاکتور //
                string invoiceDate     = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); //تاريخ فاکتور //
                string action          = "1003";                                              // براي درخوايت خريد : 1003
                // براي درخواست برگشت خريد : 1004
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                string primarykey = "<RSAKeyValue><Modulus>vGNaMAZxRvUPDHqPLkqteTxwRBuc19PceD6W21IB4pSSmck4t32gwTJvudZJsEWiRIAw+rVYmxBQNJaloVPwf60SBpp3seCfopV0B+Lnmsm6wZLcuNNLEmRFKE0Zp5HH7jomLUgtAy53xZnqfXz6aLx0YsVbaWalHj8cJ6TH/0k=</Modulus><Exponent>AQAB</Exponent><P>7tthrumhDGrGINXlyW/bIPUWZFKZcrzbB1geLT9TlslizvuZll29CH6HuAPO8mDGdM4CKut/pmM2G7DnUJAnRQ==</P><Q>yeivbHYSb8tRcR2QCfa9gc98Gi/iB8KcuFb4O5y6kF/X3S3tDU5aSr1l2TUKWZMoRQs9GHoZcmeYpWbWwRdGNQ==</Q><DP>Pnu1OgRz1MO5wK0zx1YzhJOYn/XbnmA5C9rJShzeyPs1ld/LdcJfyPEQn9qfMFiQkc2yU3f3lJcveF72o+SR4Q==</DP><DQ>cE/dnOCE2ujnEZvXLqOwwI+QweRWv+hSUvwVsts4r+yQX/kW/qrR8Pcvu0YUzsTbxqQ8xOvOUeQsdf0hgmEW7Q==</DQ><InverseQ>pnrwkhSLvarhfGxTkqr2pkLJr6usPDVsu5qXw2imQqao87iEPalEJndnNqQ50uNY5bPJPBzDi96U6FwUsbmEuQ==</InverseQ><D>B0NrxlvZOwhW+WVlGj6ccm1kHrW51fbZknR6hVMKHSq0fePTB5Z7MwSEAXRDokPTcWfhe498yEdYVrUgObIhnMzLwxVdXw+PPWIRlcNHRBMtSe9mjOSP8d+hCzUmzHPeuCmKfjPr5iwTu8z9NfycTupezn9D2cr51p35nMbX0KE=</D></RSAKeyValue>";  //کليد خصوصي فروشنده//
                rsa.FromXmlString(primarykey);
                string data = "#" + merchantCode + "#" + terminalCode + "#"
                              + invoiceNumber + "#" + invoiceDate + "#" + amount + "#" + redirectAddress
                              + "#" + action + "#" + timeStamp + "#";
                byte[] signMain = rsa.SignData(System.Text.Encoding.UTF8.GetBytes(data), new
                                               System.Security.Cryptography.SHA1CryptoServiceProvider());
                string sign = System.Convert.ToBase64String(signMain);


                Models.Gateway getway = UnitOfWork.PayOnlineRepository.Gateway(invoiceNumber, invoiceDate, amount, terminalCode, merchantCode,
                                                                               redirectAddress, timeStamp, action, sign);
                return(View(getway));
            }
            return(View());
        }
Example #12
0
 /// <summary>
 /// Sign data by PrivateKey
 /// </summary>
 /// <param name="dataBytes">Need to sign data</param>
 /// <param name="hashAlgorithmName">Signed hash algorithm name</param>
 /// <returns></returns>
 public byte[] SignByPrivateKey(byte[] dataBytes, HashAlgorithmName hashAlgorithmName)
 {
     if (PrivateRsa is null)
     {
         throw new ArgumentException("private key can not null");
     }
     return(PrivateRsa.SignData(dataBytes, hashAlgorithmName.Name));
 }
Example #13
0
 private static byte[] ComputeSignature(string outputFileName, RSACryptoServiceProvider cryptoServiceProvider)
 {
     byte[] signature;
     using( var packageFileStream = new FileStream(outputFileName, FileMode.Open))
     {
         signature = cryptoServiceProvider.SignData(packageFileStream, CreateHashAlgorithm());
     }
     return signature;
 }
        public static byte[] AsymmetricSign(byte[] Data, string xmlPrivateKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xmlPrivateKey);

            byte[] signData = rsa.SignData(Data, new SHA1CryptoServiceProvider());

            return signData;
        }
Example #15
0
 public static string sign(string content, string privateKey, string input_charset)
 {
     System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(input_charset);
     byte[] bytes = encoding.GetBytes(content);
     System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = RSAFromPkcs8.DecodePemPrivateKey(privateKey);
     System.Security.Cryptography.SHA1 halg = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     byte[] inArray = rSACryptoServiceProvider.SignData(bytes, halg);
     return(System.Convert.ToBase64String(inArray));
 }
Example #16
0
        public MFTestResults RsaTest_ExportImportTest()
        {
            bool testResult = true;

            try
            {
                using (Session session = new Session("", MechanismType.RSA_PKCS))
                using (CryptoKey privateKey = CryptoKey.LoadKey(session, m_importKeyPrivate))
                {
                    string dataToSign = "This is a simple message to be encrypted";

                    byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(dataToSign);

                    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(privateKey))
                    {
                        RSAParameters kp1 = rsa.ExportParameters(true);

                        byte[] sig = rsa.SignData(data);

                        rsa.ImportParameters(kp1);

                        RSAParameters kp2 = rsa.ExportParameters(true);

                        testResult &= CompareByteArray(kp1.D, kp2.D);
                        testResult &= CompareByteArray(kp1.DP, kp2.DP);
                        testResult &= CompareByteArray(kp1.DQ, kp2.DQ);
                        testResult &= CompareByteArray(kp1.Exponent, kp2.Exponent);
                        testResult &= CompareByteArray(kp1.InverseQ, kp2.InverseQ);
                        testResult &= CompareByteArray(kp1.Modulus, kp2.Modulus);
                        testResult &= CompareByteArray(kp1.P, kp2.P);
                        testResult &= CompareByteArray(kp1.Q, kp2.Q);

                        testResult &= CompareByteArray(m_importKeyPrivate[2].Value, kp1.Modulus);
                        testResult &= CompareByteArray(m_importKeyPrivate[3].Value, kp1.Exponent);
                        testResult &= CompareByteArray(m_importKeyPrivate[4].Value, kp1.D);
                        testResult &= CompareByteArray(m_importKeyPrivate[5].Value, kp1.P);
                        testResult &= CompareByteArray(m_importKeyPrivate[6].Value, kp1.Q);
                        testResult &= CompareByteArray(m_importKeyPrivate[7].Value, kp1.DP);
                        testResult &= CompareByteArray(m_importKeyPrivate[8].Value, kp1.DQ);
                        testResult &= CompareByteArray(m_importKeyPrivate[9].Value, kp1.InverseQ);


                        testResult &= rsa.VerifyData(data, sig);
                    }
                }

            }
            catch (Exception ex)
            {
                Log.Exception("Unexpected Exception", ex);
                testResult = false;
            }

            return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
        }
Example #17
0
        /// <summary>
        /// Computes a hash value of the string, and signs the resulting hash value with the RSA private key supplied.
        /// </summary>
        /// <param name="plaintext">The plaintext.</param>
        /// <param name="rsaKey">The RSA private key.</param>
        /// <returns>The base64 encoded signed hash string.</returns>
        public static string RSASign(this string plaintext, RSAParameters rsaKey)
        {
            if (string.IsNullOrEmpty(plaintext))
                throw new ArgumentNullException("plaintext", "Cannot sign an empty string.");

            byte[] plainTextBuffer = UTF8Encoding.UTF8.GetBytes(plaintext);
            var rsaProvider = new RSACryptoServiceProvider();
            rsaProvider.ImportParameters(rsaKey);
            byte[] signedHashBuffer = rsaProvider.SignData(plainTextBuffer, new SHA1CryptoServiceProvider());
            rsaProvider.Clear();
            return Convert.ToBase64String(signedHashBuffer);
        }
Example #18
0
        /// <summary>
        /// Create a crytographic signature for a block of data.
        /// </summary>
        /// <param name="data">The data to be signed.</param>
        /// <param name="rsa">The Crypto Service Provider to be used.</param>
        /// <returns>The signature string for the data block.</returns>
        public static string SignData(this byte[] data, RSACryptoServiceProvider rsa)
        {
            if(data == null) {
                throw new ArgumentNullException("data");
            }
            if(rsa == null) {
                throw new ArgumentNullException("rsa");
            }

            // sign data and prepend signature type
            return "rsa-sha1:" + Convert.ToBase64String(rsa.SignData(data, "SHA1"));
        }
Example #19
0
        private static string SignLicense(string privateKeyFile, string licenseFile)
        {
            string keyXml = GetKeyXml(privateKeyFile);

            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
            provider.FromXmlString(keyXml);
            using (FileStream stream = File.OpenRead(licenseFile))
            {
                string signature = EncodeToBase64(provider.SignData(stream, new SHA1CryptoServiceProvider()));
                return signature;
            }
        }
Example #20
0
        public static string CreateSignature(string text, string my_private_key)
        {
            RSACryptoServiceProvider rsacp = new RSACryptoServiceProvider(2048);
            rsacp.FromXmlString(my_private_key);

            ASCIIEncoding ByteConverter = new ASCIIEncoding();
            byte[] sign_this = ByteConverter.GetBytes(text);
            byte[] signature = rsacp.SignData(sign_this, new SHA1CryptoServiceProvider());
            string base64_string = Convert.ToBase64String(signature);

            return base64_string;
        }
Example #21
0
        /// <summary>
        /// RSA签名,默认SHA256
        /// </summary>
        /// <param name="privateKey">私钥</param>
        /// <param name="HashbyteSignature"></param>
        /// <param name="EncryptedSignatureData"></param>
        /// <returns></returns>
        public static bool Sign(string privateKey, byte[] HashbyteSignature, out byte[] EncryptedSignatureData)
        {
            System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
            LoadPrivateKey(RSA, privateKey);

            SHA256 sh = new SHA256CryptoServiceProvider();

            EncryptedSignatureData = RSA.SignData(HashbyteSignature, sh);
            sh.Dispose();
            RSA.Dispose();
            return(true);
        }
Example #22
0
        /// <summary>
        /// Computes the hash value of the specified byte array using SHA512Managed algorithm, and signs the resulting hash value.
        /// </summary>
        /// <param name="source">The input data for which to compute the hash and to be signed.</param>
        /// <param name="privateKey">The private key for System.Security.Cryptography.RSA.</param>
        /// <returns>The System.Security.Cryptography.RSA signature for the specified data.</returns>
        public static byte[] SignDataRSA(this byte[] source, RSAParameters privateKey)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(privateKey);

                using (SHA512Managed sha = new SHA512Managed())
                {
                    return rsa.SignData(source, sha);
                }
            }
        }
Example #23
0
 public string GetSignature(string OriginalString, string PrivateKey)
 {
     if (string.IsNullOrEmpty(OriginalString))
     {
         throw new ArgumentNullException();
     }
     RSACryptoServiceProvider _rsaCrypto = new RSACryptoServiceProvider();
     _rsaCrypto.FromXmlString(PrivateKey);
     byte[] originalData = Encoding.GetEncoding("utf-8").GetBytes(OriginalString);
     byte[] singData = _rsaCrypto.SignData(originalData, new SHA1CryptoServiceProvider());
     var SignatureString = Convert.ToBase64String(singData);
     return SignatureString;
 }
Example #24
0
    public static NCryptoParms EncryptCode(string decData, string spKey) {
      NCryptoParms parms = new NCryptoParms();
      ICryptoTransform encryptor;
      CryptoStream cStream;
      MemoryStream mStream = new MemoryStream();

      try {
        // Generate a new RSA public/private key pair
        // This key will be used to signature the DES IV and Key.
        RSACryptoServiceProvider jRsa = new RSACryptoServiceProvider();

        byte[] signature = jRsa.SignData(sign, new MD5CryptoServiceProvider());

        parms.jpbkey =
          Convert.ToBase64String(Encoding.ASCII.GetBytes(jRsa.ToXmlString(false)));
        parms.jprkey =
          Convert.ToBase64String(Encoding.ASCII.GetBytes(jRsa.ToXmlString(true)));
        parms.signature = Convert.ToBase64String(signature);
        jRsa.Clear();

        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        rsa.FromXmlString(
          Encoding.ASCII.GetString(Convert.FromBase64String(spKey)));

        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        des.GenerateIV();
        des.GenerateKey();

        parms.key = Convert.ToBase64String(rsa.Encrypt(des.Key, false));
        parms.iv = Convert.ToBase64String(rsa.Encrypt(des.IV, false));

        encryptor = des.CreateEncryptor(des.Key, des.IV);
        cStream = new CryptoStream(mStream, encryptor, CryptoStreamMode.Write);

        byte[] bytesIn = Encoding.ASCII.GetBytes(decData);

        cStream.Write(bytesIn, 0, bytesIn.Length);
        cStream.FlushFinalBlock();
        cStream.Close();

        byte[] bytesOut = mStream.ToArray();
        mStream.Close();

        parms.enc = Convert.ToBase64String(bytesOut);
      } catch {
        mStream.Close();
      }
      return parms;
    }
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
                rsa.FromXmlString(textBox5.Text);
                byte[] data = Encoding.UTF8.GetBytes(textBox3.Text);
                var encryptedData = rsa.SignData(data, new SHA256CryptoServiceProvider());
                textBox4.Text = Convert.ToBase64String(encryptedData);
            }
            catch (Exception exception)
            {

            }
        }
Example #26
0
 /// <summary>
 /// 软签名
 /// </summary>
 /// <param name="provider"></param>
 /// <param name="data"></param>
 /// <returns></returns>
 public static byte[] SignBySoft(RSACryptoServiceProvider provider, byte[] data)
 {
     byte[] res = null;
     try
     {
         HashAlgorithm hashalg = new SHA1CryptoServiceProvider();
         res = provider.SignData(data, hashalg);
     }
     catch (Exception e)
     {
         throw e;
     }
     if (null == res) { return null; }
     return res;
 }
Example #27
0
        public static void Main(string[] args)
        {
            // Store Key Example
            //----------------------------------------------------------------------------------------------------------
            // Creates the CspParameters object and sets the key container name used to store the RSA key pair
            CspParameters cp = new CspParameters();
            cp.KeyContainerName = "DonalKeyContainerName";

            // Instantiates the Rsa instance accessing the key container DonalKeyContainerName
            RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(cp);
            // add the below line to delete the key entry in DonalKeyContainerName
            rsa1.PersistKeyInCsp = false;

            // writes out the current key pair used in the rsa instance
            Console.WriteLine("Key is: \n" + rsa1.ToXmlString(true) + "\n\n\n");
            //----------------------------------------------------------------------------------------------------------


            // Smart Card Sign Example
            //----------------------------------------------------------------------------------------------------------
            // To identify the Smart Card Cryptographic Providers on your computer, use the Microsoft Registry Editor (Regedit.exe).
            // The available Smart Card Cryptographic Providers are listed in HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider.

            // Create a new CspParameters object that identifies a Smart Card Cryptographic Provider.
            // The 1st parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider Types.
            // The 2nd parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider.
            CspParameters csp = new CspParameters(24, "Microsoft Enhanced RSA and AES Cryptographic Provider");
            csp.Flags = CspProviderFlags.UseDefaultKeyContainer;

            // Initialize an RSACryptoServiceProvider object using the CspParameters object.
            RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider(csp);

            // Create some data to sign.
            byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 };

            Console.WriteLine("Data                  : " + BitConverter.ToString(data));

            // Sign the data using the Smart Card Cryptographics Provider.
            byte[] sig = rsa2.SignData(data, "SHA1");

            Console.WriteLine("Signature             : " + BitConverter.ToString(sig));

            // Verify the data using the Smart Card Cryptographic Provider.
            bool verified = rsa2.VerifyData(data, "SHA1", sig);

            Console.WriteLine("Verified              : " + verified);
            //----------------------------------------------------------------------------------------------------------
        }
        /// <summary>
        /// RSAs the sign create.
        /// </summary>
        /// <param name="privateCertificate">The private certificate.</param>
        /// <param name="inputCharset">The input charset.</param>
        /// <param name="signcontent">The signcontent.</param>
        /// <returns></returns>
        public static string RsaSignCreate(string privateCertificate, string inputCharset, string signcontent)
        {
            if (!_rsaprivateParameters.HasValue)
            {
                _rsaprivateParameters = RsaParametersRead.RsaParasPrivateKey(privateCertificate);
            }

            string encodestr;
            using (var oRsa1 = new RSACryptoServiceProvider())
            {
                oRsa1.ImportParameters(_rsaprivateParameters.Value);
                var dataBytes = Encoding.GetEncoding(inputCharset).GetBytes(signcontent);
                var signatureBytes = oRsa1.SignData(dataBytes, "SHA1");
                encodestr = Convert.ToBase64String(signatureBytes);
            }
            return encodestr;
        }
Example #29
0
        public static string RSASign(string signStr, string privateKey)
        {
            string result;

            try
            {
                System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider();
                rSACryptoServiceProvider.FromXmlString(privateKey);
                byte[] inArray = rSACryptoServiceProvider.SignData(System.Text.Encoding.UTF8.GetBytes(signStr), "md5");
                result = System.Convert.ToBase64String(inArray);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            return(result);
        }
Example #30
0
        /// <summary>
        /// ǩ���û���Ϣ
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string SignatueData(string data)
        {
            try
            {
                UnicodeEncoding ByteConverter = new UnicodeEncoding();

                byte[] dataToSignatue = ByteConverter.GetBytes(data);

                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(512);
                RSA.FromXmlString(PrivateKey);

                string SignadString = Convert.ToBase64String(RSA.SignData(dataToSignatue, new SHA1CryptoServiceProvider()));
                return SignadString;
            }
            catch
            {
                return string.Empty;
            }
        }
Example #31
0
        public byte[] CalculateSignature(byte[] data)
        {
            try
            {
                var csp = (RSACryptoServiceProvider)_certificate.PrivateKey;
                return csp.SignData(data, CryptoConfig.MapNameToOID("SHA256"));
            }
            catch (CryptographicException ce)
            {
                //if its an algorithm exception then it should relate to a wrongs csp being loaded. Try again with the right csp(that supports sha256)
                X509Certificate2 cert = new X509Certificate2(ConfigurationManager.AppSettings["pfxFile"], ConfigurationManager.AppSettings["pfxPassword"], X509KeyStorageFlags.Exportable);
                RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;
                byte[] privateKeyBlob = rsa.ExportCspBlob(true);
                RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider();
                rsa2.ImportCspBlob(privateKeyBlob);
                return rsa2.SignData(data, "SHA256");

            }
        }
        /// <summary>
        /// Hash the data and generate signature
        /// </summary>
        /// <param name="dataToSign"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static byte[] HashAndSignBytes(byte[] dataToSign, RSAParameters key)
        {
            try
            {
                // Create a new instance of RSACryptoServiceProvider using the
                // key from RSAParameters.
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

                RSA.ImportParameters(key);

                // Hash and sign the data. Pass a new instance of SHA1CryptoServiceProvider
                // to specify the use of SHA1 for hashing.
                return RSA.SignData(dataToSign, new SHA1CryptoServiceProvider());
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);

                return null;
            }
        }
        public void Der()
        {
            if (Environment.OSVersion.Platform == PlatformID.Unix)
                return; // No DLLs on Unix
            // TODO: Conditional compilation for mono compability

            byte[] publicKeyDER = Resources.GetResource("RSACryptoServiceProviderExtensionPublicKey.der");
            byte[] privateKeyDER = Resources.GetResource("RSACryptoServiceProviderExtensionPrivateKey.der");

            Console.WriteLine("Public key:\n{0}\n", BitConverter.ToString(publicKeyDER).Replace("-", ""));
            Console.WriteLine("Private key:\n{0}\n", BitConverter.ToString(privateKeyDER).Replace("-", ""));

            byte[] signature;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.PersistKeyInCsp = false;
                rsa.ImportPrivateKeyDer(privateKeyDER);
                using (var sha1 = new SHA1CryptoServiceProvider())
                    signature = rsa.SignData(DataToSign, sha1);
            }

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.PersistKeyInCsp = false;
                rsa.ImportPublicKeyDer(publicKeyDER);

                bool isValidSignature;
                using (var sha1 = new SHA1CryptoServiceProvider())
                    isValidSignature = rsa.VerifyData(DataToSign, sha1, signature);
                Assert.IsTrue(isValidSignature);

                // invalidate signature so the next check must fail
                signature[signature.Length - 1] ^= 0xFF;
                using (var sha1 = new SHA1CryptoServiceProvider())
                    isValidSignature = rsa.VerifyData(DataToSign, sha1, signature);
                Assert.IsFalse(isValidSignature);
            }
        }
Example #34
0
        private static void AsymmetricEncryption()
        {
            byte[] signature;
            byte[] publicAndPrivateKey;
            byte[] publicKeyOnly;
            var hashImplementation = SHA1.Create();

            // create a signature, create our public and private keys - we could save these out as XML, etc.
            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                signature = rsaProvider.SignData(dataToProtectAsArray, hashImplementation);
                publicAndPrivateKey = rsaProvider.ExportCspBlob(true);
                publicKeyOnly = rsaProvider.ExportCspBlob(false);
            }

            // create a new RSA
            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                // import our public key
                rsaProvider.ImportCspBlob(publicKeyOnly);

                // has it been tampered with?
                if (!rsaProvider.VerifyData(dataToProtectAsArray, hashImplementation, signature))
                {
                    Console.WriteLine("Data has been tampered with");
                }

                // now let's tamper with our data

                dataToProtectAsArray[5] = 255;
                if (!rsaProvider.VerifyData(dataToProtectAsArray, hashImplementation, signature))
                {
                    Console.WriteLine("Data has been tampered with");
                }
            }

            hashImplementation.Dispose();
        }
Example #35
0
        public string NewLicence(string emailAddress, int quantity, string[] modules)
        {
            var licence = new Licence
            {
                LicenceId = Guid.NewGuid(),
                LicenseeEmailAddress = emailAddress,
                NumberOfLicences = quantity,
                ValidModules = modules
            };

            var licencePackage = new LicencePackage();

            var toSign = licence.ToJson().Select(c => (byte)c).ToArray();

            var crypto = new RSACryptoServiceProvider();
            crypto.ImportParameters(_keys);

            licencePackage.Signature = crypto.SignData(toSign, new SHA1CryptoServiceProvider());

            var licencePackageBytes = licencePackage.ToJson().Select(c => (byte)c).ToArray();

            return Convert.ToBase64String(licencePackageBytes);
        }
Example #36
0
        public void TestRfc7515Example_A_2_1()
        {
            string protectedSample = // From the RFC example
                                     "{\"alg\":\"RS256\"}";

            byte[] protectedBytesExpected = // From the RFC example
            {
                123, 34, 97, 108, 103, 34, 58, 34, 82, 83, 50, 53, 54, 34, 125
            };
            byte[] protectedBytesActual = Encoding.UTF8.GetBytes(protectedSample);
            CollectionAssert.AreEqual(protectedBytesExpected, protectedBytesActual);

            string protectedB64uExpected = "eyJhbGciOiJSUzI1NiJ9"; // From the RFC example
            string protectedB64uActual   = CryptoHelper.Base64.UrlEncode(protectedBytesActual);

            Assert.AreEqual(protectedB64uExpected, protectedB64uActual);

            string payloadSample = // From the RFC example
                                   "{\"iss\":\"joe\",\r\n" +
                                   " \"exp\":1300819380,\r\n" +
                                   " \"http://example.com/is_root\":true}";

            byte[] payloadBytesActual = Encoding.UTF8.GetBytes(payloadSample);
            string payloadB64uActual  = CryptoHelper.Base64.UrlEncode(payloadBytesActual);
            string signingInput       = $"{protectedB64uActual}.{payloadB64uActual}";

            byte[] signingBytesExpected = // From the RFC example
            {
                101, 121,  74, 104,  98,  71,  99, 105,  79, 105,  74, 83,  85, 122,  73,
                49,   78, 105,  74,  57,  46, 101, 121,  74, 112,  99, 51,  77, 105,  79,105,
                74,  113,  98,  50,  85, 105,  76,  65,  48,  75,  73, 67,  74, 108, 101, 72,
                65,  105,  79, 106,  69, 122,  77,  68,  65,  52,  77, 84, 107, 122,  79, 68,
                65,  115,  68,  81, 111, 103,  73, 109, 104,  48, 100, 72,  65,  54,  76,
                121,  57, 108, 101,  71,  70, 116,  99,  71, 120, 108, 76, 109,  78, 118,
                98,   83,  57, 112,  99,  49,  57, 121,  98,  50,  57, 48,  73, 106, 112, 48,
                99,  110,  86, 108, 102, 81
            };
            byte[] signingBytesActual = Encoding.ASCII.GetBytes(signingInput);
            CollectionAssert.AreEqual(signingBytesExpected, signingBytesActual);


            byte[] sigExpected = // From the RFC example
            {
                112,  46,  33, 137,  67, 232, 143, 209,  30, 181, 216,  45, 191, 120,  69,
                243,  65,   6, 174,  27, 129, 255, 247, 115,  17,  22, 173, 209, 113, 125,
                131, 101, 109,  66,  10, 253,  60, 150, 238, 221, 115, 162, 102,  62,  81,
                102, 104, 123,   0,  11, 135,  34, 110,   1, 135, 237,  16, 115, 249,  69,
                229, 130, 173, 252, 239,  22, 216,  90, 121, 142, 232, 198, 109, 219,
                61,  184, 151,  91,  23, 208, 148,   2, 190, 237, 213, 217, 217, 112,   7,
                16,  141, 178, 129,  96, 213, 248,   4,  12, 167,  68,  87,  98, 184,  31,
                190, 127, 249, 217,  46,  10, 231, 111,  36, 242,  91,  51, 187, 230, 244,
                74,  230,  30, 177,   4,  10, 203,  32,   4,  77,  62, 249,  18, 142, 212,1,
                48,  121,  91, 212, 189,  59,  65, 238, 202, 208, 102, 171, 101,  25, 129,
                253, 228, 141, 247, 127,  55,  45, 195, 139, 159, 175, 221,  59, 239,
                177, 139,  93, 163, 204,  60,  46, 176,  47, 158,  58,  65, 214,  18, 202,
                173,  21, 145,  18, 115, 160,  95,  35, 185, 232,  56, 250, 175, 132, 157,
                105, 132,  41, 239,  90,  30, 136, 121, 130,  54, 195, 212,  14,  96,  69,
                34,  165,  68, 200, 242, 122, 122,  45, 184,   6,  99, 209, 108, 247, 202,
                234,  86, 222,  64,  92, 178,  33,  90,  69, 178, 194,  85, 102, 181,  90,
                193, 167,  72, 160, 112, 223, 200, 163,  42,  70, 149,  67, 208,  25, 238,
                251, 71
            };
            byte[] sigActual = null;
            using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider())
            {
                rsa.ImportParameters(GetRsaParamsForRfc7515Example_A_2_1());
                using (var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider())
                {
                    sigActual = rsa.SignData(signingBytesExpected, sha256);
                }
            }
            CollectionAssert.AreEqual(sigExpected, sigActual);

            string sigB64uExpected = // From the RFC example
                                     "cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7" +
                                     "AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4" +
                                     "BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K" +
                                     "0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqv" +
                                     "hJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrB" +
                                     "p0igcN_IoypGlUPQGe77Rw";
            string sigB64uActual = CryptoHelper.Base64.UrlEncode(sigActual);

            Assert.AreEqual(sigB64uExpected, sigB64uActual);
        }
Example #37
-1
 public static string SignDownload(string updateFile)
 {
     RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
     provider.FromXmlString(File.ReadAllText("private.key"));
     byte[] signedBytes = provider.SignData(File.ReadAllBytes(updateFile), "SHA256");
     return Convert.ToBase64String(signedBytes);
 }