Example #1
0
        private static void client_OnSymmetricAuthenticate(ISocketConnection connection, out System.Security.Cryptography.RSACryptoServiceProvider serverKey)
        {
            //----- Using string!

            //----- You must get the public key xml from the ALAZ certificate in you server machine.
            //----- Uncomment the following lines to get the public key from certificate.

            //---- Get certificate!
            // X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            // store.Open(OpenFlags.ReadOnly);
            // X509Certificate2 certificate = store.Certificates.Find(X509FindType.FindBySubjectName, "ALAZ Library", true)[0];

            //---- Get public key string!
            // string publicKey = certificate.PrivateKey.ToXmlString(false);

            serverKey = new RSACryptoServiceProvider();

            //----- Using string!
            if (connection.Context.Host.Context.HostType == HostType.htClient)
            {
                serverKey.FromXmlString("<RSAKeyValue><Modulus>z2ksxSTLHSBjY4+IEz7TZU5EclOql5pphA9+xyNQ6c1rYW6VPAmXmiXZKmsza8N++YVLAGnzR95iYyr4oL+mBz8lbhjDH2iqyQL7utbW1s87WaDC2o+82dLnLvwEqBhWpnz4tC0v0kCKayH6Jj+30l3xLdgDwReWF7YEvp6yq6nGxHOeSiioPpTtJzNhWjKGnK6oSZqthfWHewlRl2hVIrewD+JbP5JYTp/7iYptOiCwNAUZEBxODR2743D56J1AeHNc8VpZNvE3ZozIoRFhnxZw0ZpvMbgPliKPyjPeOvOFeqZUJ2zkQ7sH+gnqt67QzkOzznfuFPmTpBo0tMheyw==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");
            }
            else
            {
                serverKey.FromXmlString("<RSAKeyValue><Modulus>z2ksxSTLHSBjY4+IEz7TZU5EclOql5pphA9+xyNQ6c1rYW6VPAmXmiXZKmsza8N++YVLAGnzR95iYyr4oL+mBz8lbhjDH2iqyQL7utbW1s87WaDC2o+82dLnLvwEqBhWpnz4tC0v0kCKayH6Jj+30l3xLdgDwReWF7YEvp6yq6nGxHOeSiioPpTtJzNhWjKGnK6oSZqthfWHewlRl2hVIrewD+JbP5JYTp/7iYptOiCwNAUZEBxODR2743D56J1AeHNc8VpZNvE3ZozIoRFhnxZw0ZpvMbgPliKPyjPeOvOFeqZUJ2zkQ7sH+gnqt67QzkOzznfuFPmTpBo0tMheyw==</Modulus><Exponent>AQAB</Exponent><P>7IhXSag5zlV+Ary/KDsMinK2Jah/WdTov6Z2XAAPHB4zOGEbhCXdgTEkIrOJNpyobF6L7mR9sTnuV5pr+vWklKkYMbxUEK+KRYo4knUvxx5ED4lFE3KUGeVz6jJ1LY5FqmQT4RTtfwZa6dxRPSgn19/k6sOqyPnnalPz30CYFAk=</P><Q>4Hs/u3UIH+CB3yf2gpupXw5yxl82YX/GuB+ZIAYopM65UlukzFl8eW1iEu42gG/UOpjfmDje+wEvIZ5gcKGjGdDgRmEbAYKNt7X6LqkhIMQqUHt0vAsNrYDXgRFVHdd8YisZ62DzAyMM9nu6v0jPTmhlJSDJwpH3s9XbVy0rmTM=</Q><DP>IF7UW087ggJvOV6tZosWP0hNpz+1Fg0uQTQ91H9pkfaMGfYoNuCbvNeF033wlFnCLvqNefWkwgFknfaTOogtmu69UektNA9iA/xTm6+P91csB1hI7M1seVLOl0mKgc6LuDL0CYS8r/qlrIWrVIxPT5rjkEFw+QpCYmnU4UPMzEk=</DP><DQ>jy7OBfmuBvcin35UBBbZv6Htn45Xl3TzAbpV51FGV2jsWBXQVe+2L5WPeteqt92clwuvgt6zi5LDx0PH68+NwweyJfIGUb4+OrG+NEj4snetLcyxNsguHz8RNmghzHkIA23OiI48MwIGYKmnAh+k6zQ3X6k8R/jm8DQ2RbKwHnU=</DQ><InverseQ>Jrbm5MzTpYI9f0jQKBFzdEdI4DeUFou4BrFpJaheh/+jhzogia+0VsK1CfuXbXgFLPV2aXpQeZYZTX/ANJEymJsp9kAELknq8O+qz6QFyfY0F4Q5H6SVuI/U40XlstYZ2ZEvjGMhXpSAnQUIZ8HJQf8nFOSoAK+HyDwPdvn5RlE=</InverseQ><D>L5hkBK1nyrxG8m7afAgbvJCUVmPqrrVpZzujDRGGnNBdxtL4ffl5h48N4ZUODLmk5p920ZZ+lExs6XLP8Rtpfxo3fadDB28eWdhMadipHkwZw3yHml4HqTijgn2kl+pV4Ainjbkc0zOqT+FRJPvUM/sIwEtkuSevcqt7NT73ozp9roswv0QHBrclCVIN0uiCqPEsfTaLeVEpg48dOh8as6l1XDlgnDGTFjkj2AgFfD27POPE3n4pJSaYJc5zNijbwrjyz8qa1nr+xBQ+yvteNDOg/1LAczP1xrypDgsl/bRHmkljYhPj40SXwK2jwyicgfgCbE3wi6O9t52D8koacQ==</D></RSAKeyValue>");
            }
        }
        /// <summary>
        /// Metoda za verifikaciju ispravnosti digitalnog potpisa dokumenta
        /// </summary>
        /// <param name="file"></param>
        public void VerifyDigitalSignature(string file)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            StreamReader streamReader = new StreamReader("javni_kljuc.txt");
            string publicKey = streamReader.ReadToEnd();
            rsa.FromXmlString(publicKey);
            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);
            string nameP = file + ".dp";

            TextReader streamreader = new StreamReader(nameP);
            string sign = streamreader.ReadLine();
            streamreader.Close();
            streamreader.Dispose();

            if (rsa.VerifyData(data, "SHA1", Convert.FromBase64String(sign)))
            {
                MessageBox.Show("Datoteka je ispravno potpisana", "My Application",
                MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
                MessageBox.Show("Datoteka nije ispravno potpisana", "My Application", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            binReader.Close();
            binReader.Dispose();
            dat.Close();
            dat.Dispose();
        }
Example #3
0
        public static string Text_Decryption(string text, int bits, string encryption_key)
        {
            string result = String.Empty;
            ArrayList list = new ArrayList();

            try
            {
                RSACryptoServiceProvider rsacsp = new RSACryptoServiceProvider(bits);
                rsacsp.FromXmlString(encryption_key);
                int blockSizeBase64 = (bits / 8 % 3 != 0) ?  (((bits / 8) / 3) * 4) + 4 : ((bits / 8) / 3) * 4;
                int iterations = text.Length / blockSizeBase64;

                for (int i = 0; i < iterations; i++)
                {
                    Byte[] encrypted_bytes = Convert.FromBase64String(text.Substring(blockSizeBase64 * i, blockSizeBase64));
                    Array.Reverse(encrypted_bytes);
                    list.AddRange(rsacsp.Decrypt(encrypted_bytes, true));
                }

            }
            catch (Exception e)
            {
                result = "<Error>" + e.Message + "</Error>";
            }

            result = Encoding.UTF32.GetString((Byte[])list.ToArray(typeof(Byte)));

            return result;
        }
Example #4
0
 public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
 {
     RSACryptoServiceProvider provider1 = new RSACryptoServiceProvider();
     provider1.FromXmlString(xmlPublicKey);
     byte[] buffer1 = provider1.Encrypt(EncryptString, false);
     return Convert.ToBase64String(buffer1);
 }
Example #5
0
        /// <summary>
        /// decrypts a string with a key inside the xmlstring
        /// </summary>
        /// <param name="DataToDecrypt">data to decrypt</param>
        /// <param name="xml">xmlstring taken from an RSACryptoServiceProvider object</param>
        /// <returns>decrypted string</returns>
        public static string RSADecrypt(string DataToDecrypt, string xml)
        {
            try
            {
                byte[] decryptedData;
                //Create a new instance of RSACryptoServiceProvider.
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    RSA.FromXmlString(xml);

                    //Decrypt the passed byte array and specify OAEP padding.
                    //OAEP padding is only available on Microsoft Windows XP or
                    //later.
                    decryptedData = RSA.Decrypt(Convert.FromBase64String(DataToDecrypt), false);
                }
                return Encoding.UTF8.GetString(decryptedData);
            }
            //Catch and display a CryptographicException
            //to the console.
            catch (CryptographicException e)
            {
                Console.WriteLine(e.ToString());

                return null;
            }
        }
Example #6
0
        public IHttpActionResult DecodeToken(string access_token)
        {
            var tokenReceived = new JwtSecurityToken(access_token);

            var publicOnly = new RSACryptoServiceProvider();
            publicOnly.FromXmlString(_configuration.PublicKey.FromBase64String());
            var validationParameters = new TokenValidationParameters
            {
                ValidIssuer = _configuration.Issuer
               ,ValidAudience = "http://mysite.com"
               ,IssuerSigningToken = new RsaSecurityToken(publicOnly)
               ,ValidateLifetime = true
            };

            var recipientTokenHandler = new JwtSecurityTokenHandler();
            SecurityToken securityToken;
            var claimsPrincipal = recipientTokenHandler.ValidateToken(access_token, validationParameters, out securityToken);

            var currentTime = (long) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;

            if (tokenReceived.Payload.Exp < currentTime)
            {
                throw new SecurityTokenValidationException(string.Format("Lifetime validation failed. The token is expired. ValidTo: '{0}' Current time: '{1}'.", tokenReceived.ValidTo, DateTime.UtcNow));
            }
          
            return Ok(new
            {
                header = tokenReceived.Header,
                payload = tokenReceived.Payload,
                current = currentTime
            });
        }
        /// <summary>
        /// Generates a new floating license.
        /// </summary>
        /// <param name="name">Name of the license holder</param>
        /// <param name="publicKey">public key of the license server</param>
        /// <returns>license content</returns>
        public string GenerateFloatingLicense(string name, string publicKey)
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(privateKey);
                var doc = new XmlDocument();
                var license = doc.CreateElement("floating-license");
                doc.AppendChild(license);

                var publicKeyEl = doc.CreateElement("license-server-public-key");
                license.AppendChild(publicKeyEl);
                publicKeyEl.InnerText = publicKey;
                
                var nameEl = doc.CreateElement("name");
                license.AppendChild(nameEl);
                nameEl.InnerText = name;

                var signature = GetXmlDigitalSignature(doc, rsa);
                doc.FirstChild.AppendChild(doc.ImportNode(signature, true));

                var ms = new MemoryStream();
                var writer = XmlWriter.Create(ms, new XmlWriterSettings
                {
                    Indent = true,
                    Encoding = Encoding.UTF8
                });
                doc.Save(writer);
                ms.Position = 0;
                return new StreamReader(ms).ReadToEnd();
            }
        }
        public static string Encrypt(string data)
        {
            try
               {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(_publicKey);
            var dataToEncrypt = _encoder.GetBytes(data);
            var encryptedByteArray = rsa.Encrypt(dataToEncrypt, false).ToArray();
            var length = encryptedByteArray.Count();
            var item = 0;
            var sb = new StringBuilder();
            foreach (var x in encryptedByteArray)
            {
             item++;
             sb.Append(x);

             if (item < length)
              sb.Append(",");
            }

            return sb.ToString();

               }
               catch (Exception)
               {
            throw new RSAException();
               }
        }
Example #9
0
        /// <summary>
        /// Floating 라이선스를 생성합니다.
        /// 참고 : http://en.wikipedia.org/wiki/Floating_licensing
        /// </summary>
        /// <param name="privateKey">제품의 Private Key</param>
        /// <param name="name">라이선스 명</param>
        /// <param name="publicKey">제품의 Public Key</param>
        /// <returns>Floating License의 XML 문자열</returns>
        public static string GenerateFloatingLicense(string privateKey, string name, string publicKey) {
            if(IsDebugEnabled)
                log.Debug("Floating License를 생성합니다... privateKey=[{0}], name=[{1}], publicKey=[{2}]", privateKey, name, publicKey);

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

                var doc = new XmlDocument();
                var licenseElement = doc.CreateElement(LicensingSR.FloatingLicense);
                doc.AppendChild(licenseElement);

                var publicKeyElement = doc.CreateElement(LicensingSR.LicenseServerPublicKey);
                licenseElement.AppendChild(publicKeyElement);
                publicKeyElement.InnerText = publicKey;

                var nameElement = doc.CreateElement(LicensingSR.LicenseName);
                licenseElement.AppendChild(nameElement);
                nameElement.InnerText = name;

                var signatureElement = GetXmlDigitalSignature(doc, rsa);
                doc.FirstChild.AppendChild(doc.ImportNode(signatureElement, true));

                using(var ms = new MemoryStream())
                using(var xw = XmlWriter.Create(ms, new XmlWriterSettings
                                                    {
                                                        Indent = true,
                                                        Encoding = Encoding.UTF8
                                                    })) {
                    doc.Save(xw);
                    ms.Position = 0;
                    return new StreamReader(ms).ReadToEnd();
                }
            }
        }
Example #10
0
 public static string RSAEncrypt(string source, string xmlKey) {
     using (var rsa = new RSACryptoServiceProvider(1024)) {
         rsa.FromXmlString(xmlKey);
         var encrypted = rsa.Encrypt(Encoding.UTF8.GetBytes(source), false);
         return BytesToHex(encrypted);
     }
 }
Example #11
0
        public static string Text_Encryption(string text, int bits, string encryption_key)
        {
            StringBuilder result = new StringBuilder("");

            try
            {
                RSACryptoServiceProvider rsacsp = new RSACryptoServiceProvider(bits);
                rsacsp.FromXmlString(encryption_key);
                int key = bits / 8;
                Byte[] bites = Encoding.UTF32.GetBytes(text);
                int max_length = key - 42;
                int data_length = bites.Length;
                int iterations = data_length / max_length;

                for (int i = 0; i <= iterations; i++)
                {
                    int total_bytes = (data_length - max_length * i > max_length) ? max_length : data_length - max_length * i;
                    Byte[] temp_bytes = new Byte[total_bytes];
                    Buffer.BlockCopy(bites, max_length * i, temp_bytes, 0, temp_bytes.Length);
                    Byte[] encrypted_bytes = rsacsp.Encrypt(temp_bytes, true);
                    Array.Reverse(encrypted_bytes);
                    result.Append(Convert.ToBase64String(encrypted_bytes));
                }

            }
            catch (Exception e)
            {
                result.Append("<Error>" + e.Message + "</Error>");
            }
            return result.ToString();
        }
 public string EncryptString( string inputString, int dwKeySize, string xmlString )
 {
     // TODO: Add Proper Exception Handlers
     RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider( dwKeySize );
     rsaCryptoServiceProvider.FromXmlString( xmlString );
     int keySize = dwKeySize / 8;
     byte[] bytes = Encoding.UTF32.GetBytes( inputString );
     // The hash function in use by the .NET RSACryptoServiceProvider here is SHA1
     // int maxLength = ( keySize ) - 2 - ( 2 * SHA1.Create().ComputeHash( rawBytes ).Length );
     int maxLength = keySize - 42;
     int dataLength = bytes.Length;
     int iterations = dataLength / maxLength;
     StringBuilder stringBuilder = new StringBuilder();
     for( int i = 0; i <= iterations; i++ )
     {
         byte[] tempBytes = new byte[ ( dataLength - maxLength * i > maxLength ) ? maxLength : dataLength - maxLength * i ];
         Buffer.BlockCopy( bytes, maxLength * i, tempBytes, 0, tempBytes.Length );
         byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt( tempBytes, true );
         // Be aware the RSACryptoServiceProvider reverses the order of encrypted bytes after encryption and before decryption.
         // If you do not require compatibility with Microsoft Cryptographic API (CAPI) and/or other vendors.
         // Comment out the next line and the corresponding one in the DecryptString function.
         Array.Reverse( encryptedBytes );
         // Why convert to base 64?
         // Because it is the largest power-of-two base printable using only ASCII characters
         stringBuilder.Append( Convert.ToBase64String( encryptedBytes ) );
     }
     return stringBuilder.ToString();
 }
Example #13
0
 public string EncryptData(string data2Encrypt, string strPublicKey)
 {
     RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
     provider.FromXmlString(strPublicKey);
     byte[] bytes = Encoding.UTF8.GetBytes(data2Encrypt);
     return Convert.ToBase64String(provider.Encrypt(bytes, false));
 }
        /// <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();
        }
        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 #16
0
 /// <summary>
 /// Getting public key
 /// </summary>
 /// <param name="strPrivateKey"></param>
 /// <returns>Return Pubic Key</returns>
 public static String GetPublicKey(String strPrivateKey)
 {
     //Extract the public key from the public/private key pair
     RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
     rsa.FromXmlString(strPrivateKey);
     return rsa.ToXmlString(false);
 }
Example #17
0
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="base64code">传入加密数据</param>
        /// <returns>返回解密数据</returns>
        static public string Decrypt(string base64code)
        {

            var a = new FileInfo("E:/100115_SignKey.pub").OpenRead();
            var b = new BufferedStream(a);
            //string c = 
            try
            {
                UnicodeEncoding ByteConverter = new UnicodeEncoding();

                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSA.FromXmlString("");

                RSAParameters rsaParameters = new RSAParameters();

                rsaParameters.Exponent = Convert.FromBase64String("AQAB");
                rsaParameters.Modulus =
                    Convert.FromBase64String(
                        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyq3xJ3jtuWSWk4nCCgysplqV3DyFGaF7iP7PO2vEUsgEq+vqKr+frlwji2n7A1TbpV7KhEGJIT9LW/9WCdBhlu6gnBdErtAA4Or43ol2K1BnY6VBcLWccloMd3YFHG8gOohCVIDbw863Wg0FNS27SM25U+XQfrNFaqBIa093WgAbwRIK06uzC01sW+soutvk+yAYBtbH7I7/1/dFixHKS2KN/7y3pvmXYBIRuBvn35IqwY3Gk0duEfbEr9F6wm2VKhS1zQG760FrHfhbXR+IN5nSTQBHBkw4QukLLvUqueKYfVdp2/2RCnY/At0bbOcA2tAPohDAfUDRdOZsFiTIMQID");

                byte[] encryptedData;
                byte[] decryptedData;

                encryptedData = Convert.FromBase64String(base64code);

                decryptedData = RSADeCrtypto(encryptedData, rsaParameters, true);
                return ByteConverter.GetString(decryptedData);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }
        }
	public RSACryptoServiceProviderTest () 
	{
		sha1OID = CryptoConfig.MapNameToOID ("SHA1");
		disposed = new RSACryptoServiceProvider (minKeySize);
		disposed.FromXmlString ("<RSAKeyValue><Modulus>vtXAf62+o50prNCTiVGTMzdhm4sMjK0QVDkKQLFGu2fJQCULt9NZBab14PiWfG1t</Modulus><Exponent>AQAB</Exponent><P>5y2AHOzIhTChIFzLsgZQAGfy3U8OPwFh</P><Q>01NUVJJv+hhIsnbFiSi24FLRrfr/qYuN</Q><DP>HKLAOdUCyazKaK3V9Yleo448wTkntJpB</DP><DQ>AH5MTxo8arAN02TVlzliG+n1lVtlp2at</DQ><InverseQ>ZpgJwTxSYpT81sQCuVUvX0AYrvSziNIw</InverseQ><D>CStiJYBmsZvincAj5qw5w3M8yGmE/9ls4yv7wenozzC4kZshpI2MuON0d2Z8f4aB</D></RSAKeyValue>");
		disposed.Clear ();
	}
        public void Run()
        {
            var _exportKey = new RSACryptoServiceProvider();
            string publicKeyXML = _exportKey.ToXmlString(false);
            string privateKeyXML = _exportKey.ToXmlString(true);

            var ByteConverter = new UnicodeEncoding();
            byte[] dataToEncrypt = ByteConverter.GetBytes("My Secret Data!");

            byte[] encryptedData;
            using (var RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(publicKeyXML);
                encryptedData = RSA.Encrypt(dataToEncrypt, false);
            }

            byte[] decryptedData;
            using (var RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(privateKeyXML);
                decryptedData = RSA.Decrypt(encryptedData, false);
            }

            string decryptedString = ByteConverter.GetString(decryptedData);
            Console.WriteLine(decryptedString); // Displays: My Secret Data!        }
        }
Example #20
0
        // Decrypt method
        public string Decrypt( string b64String )
        {
            try
            {
                byte[] ciphertext = Convert.FromBase64String(b64String);

                CspParameters RSAParams = new CspParameters();
                RSAParams.Flags = CspProviderFlags.UseMachineKeyStore;
                //create new instance of  RSACryptoServiceProvider
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(RSAParams);

                //import public and private RSA parameters from Xml file
                //StreamReader reader = new StreamReader("PublicPrivateKey.xml");
                //string publicPrivateKeyXml = reader.ReadToEnd();
                //reader.Close();
                rsa.FromXmlString(this.publicPrivateKeyXml);

                //read ciphertext, decrypt it to plaintext
                byte[] plainbytes = rsa.Decrypt( ciphertext, false); //fOAEP needs high encryption pack
                return Encoding.ASCII.GetString(plainbytes) ;
            }
            catch ( CryptographicException cx )
            {
                throw new CryptographicException( cx.Message) ;
            }
        }
Example #21
0
        public async Task<IHttpActionResult> CreateToken(Token token)
        {
            var publicAndPrivate = new RSACryptoServiceProvider();
            
            publicAndPrivate.FromXmlString(_configuration.PrivateKey.FromBase64String());
            var jwtToken = new JwtSecurityToken(
                                issuer: _configuration.Issuer, 
                                audience: "http://mysite.com"
                                , claims: new List<Claim>() { new Claim(ClaimTypes.Name, token.username) }
                                , notBefore: DateTime.UtcNow
                                , expires: DateTime.UtcNow.AddMinutes(1)
                                , signingCredentials: new SigningCredentials(
                                    new RsaSecurityKey(publicAndPrivate)
                                       ,SecurityAlgorithms.RsaSha256Signature
                                       ,SecurityAlgorithms.Sha256Digest)
                           );

            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenString = tokenHandler.WriteToken(jwtToken);

            return Ok(new
            {
                access_token = tokenString,
                expires_in = new TimeSpan(0,0, 1,0).TotalSeconds,
                expires_on = (long)(DateTime.UtcNow.AddMinutes(1) - new DateTime(1970, 1, 1)).TotalSeconds
            });
        }
            public void VerifyXml(string xml)
            {
                var doc = LoadXmlDoc(xml);

                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.FromXmlString(publicKey);

                    var nsMgr = new XmlNamespaceManager(doc.NameTable);
                    nsMgr.AddNamespace("sig", "http://www.w3.org/2000/09/xmldsig#");

                    var signedXml = new SignedXml(doc);
                    var signature = (XmlElement)doc.SelectSingleNode("//sig:Signature", nsMgr);
                    if (signature == null)
                    {
                        throw new Exception("Xml is invalid as it has no XML signature");
                    }
                    signedXml.LoadXml(signature);

                    if (!signedXml.CheckSignature(rsa))
                    {
                        throw new Exception("Xml is invalid as it failed signature check.");
                    }
                }
            }
Example #23
0
        public static string Decrypt(string encryptedText)
        {
            StringBuilder stringBuilder = new StringBuilder();

            RSACryptoServiceProvider.UseMachineKeyStore = true;

            using (RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider())
            {
                mojoEncryptionConfiguration config = mojoEncryptionConfiguration.GetConfig();
                if (config.RsaKey.Length == 0)
                {
                    log.Error("CryptoHelper.LoadRsaKey failed to load key from config, key was an empty string.");
                    throw new ArgumentException("CryptoHelper.LoadRsaKey failed to load key from config, key was an empty string.");
                }

                rsaProvider.FromXmlString(config.RsaKey);

                byte[] decryptedStr = rsaProvider.Decrypt(StringToByteArray(encryptedText.Trim()), false);

                for (int i = 0; i <= decryptedStr.Length - 1; i++)
                {
                    stringBuilder.Append(Convert.ToChar(decryptedStr[i]));
                }
            }

            return stringBuilder.ToString();
        }
Example #24
0
 /// <summary>
 /// 公钥加密
 /// </summary>
 /// <param name="publichKey"></param>
 /// <param name="strData"></param>
 public static string EncryptRSA(string publicKey, string strData)
 {
     RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
     rsa.FromXmlString(publicKey);
     byte[] dataRSAed = rsa.Encrypt(Encoding.UTF8.GetBytes(strData), false);
     return CommonHelper.ByteArrayToString(dataRSAed);
 }
Example #25
0
 public static string DecryptString(string inputString, int dwKeySize,
                              string xmlString)
 {
     // TODO: Add Proper Exception Handlers
     RSACryptoServiceProvider rsaCryptoServiceProvider
                              = new RSACryptoServiceProvider(dwKeySize);
     rsaCryptoServiceProvider.FromXmlString(xmlString);
     int base64BlockSize = ((dwKeySize / 8) % 3 != 0) ?
       (((dwKeySize / 8) / 3) * 4) + 4 : ((dwKeySize / 8) / 3) * 4;
     int iterations = inputString.Length / base64BlockSize;
     ArrayList arrayList = new ArrayList();
     for (int i = 0; i < iterations; i++)
     {
         byte[] encryptedBytes = Convert.FromBase64String(
              inputString.Substring(base64BlockSize * i, base64BlockSize));
         // Be aware the RSACryptoServiceProvider reverses the order of
         // encrypted bytes after encryption and before decryption.
         // If you do not require compatibility with Microsoft Cryptographic
         // API (CAPI) and/or other vendors.
         // Comment out the next line and the corresponding one in the
         // EncryptString function.
         Array.Reverse(encryptedBytes);
         arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(
                             encryptedBytes, true));
     }
     return Encoding.UTF32.GetString(arrayList.ToArray(
                               Type.GetType("System.Byte")) as byte[]);
 }
Example #26
0
        /// <summary>
        /// Genera _bytEncriptado: Es unByte[] con el contenido de llavePublica RSA encriptada (bytes) y contenido Encriptado Simetrico 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAsimEncriptar_Click(object sender, EventArgs e)
        {
            byte[] _bytEncriptado = null;
            System.Security.Cryptography.CspParameters csp = new CspParameters();
            csp.KeyContainerName = "pepe";
            //Creamos una instancia del encritador publico 
            RSACryptoServiceProvider _objEncriptadorPublicoRSA = new RSACryptoServiceProvider(csp);
            //Le asignamos la llave genarada 
            _objEncriptadorPublicoRSA.FromXmlString(this.txtAsimLlavePublica.Text);

            if (this.chkSimetrica.Checked)
            {
                //Se declara la memoria para almacenar la llave utilizada por nuestro Rijndael personalizado 
                byte[] _bytKey = (Rijndael.Create()).Key;

                //Se encripta el texto y se obtiene la llave que se utilizó para la encriptación 
                byte[] _contenidoEncriptadoSimetrico = MiRijndael.Encriptar(this.txtAsimAEncriptar.Text, _bytKey);

                //Se encripta la llave con el algoritmo RSA 
                byte[] llaveEncriptadaRSA = _objEncriptadorPublicoRSA.Encrypt(_bytKey, false);

                #region Se copia en un vector la llave encriptada y el contenido encriptado Simetrico (Rijndael)
                _bytEncriptado = new byte[llaveEncriptadaRSA.Length + _contenidoEncriptadoSimetrico.Length];
                llaveEncriptadaRSA.CopyTo(_bytEncriptado, 0);
                _contenidoEncriptadoSimetrico.CopyTo(_bytEncriptado, llaveEncriptadaRSA.Length);
                #endregion

            }
            else
            {
                _bytEncriptado = _objEncriptadorPublicoRSA.Encrypt(System.Text.Encoding.UTF8.GetBytes(this.txtAsimAEncriptar.Text), false);
            }
            this.txtAsimEncriptado.Text = Convert.ToBase64String(_bytEncriptado);

        }
Example #27
0
        public static void EncryptSomeText()
        {
            //Init keys
            GeneratePublicAndPrivateKeys();

            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] dataToEncrypt = ByteConverter.GetBytes("My ultra secret message!");

            byte[] encryptedData;
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(publicKeyXML);
                encryptedData = RSA.Encrypt(dataToEncrypt, false);
            }

            byte[] decryptedData;
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(privateKeyXML);
                decryptedData = RSA.Decrypt(encryptedData, false);
            }

            string decryptedString = ByteConverter.GetString(decryptedData);
            Console.WriteLine(decryptedString);
        }
Example #28
0
        public static bool CompareCode(string regcode)
        {
            if (regcode == null || regcode == "")
            {
                return false;
            }
            try
            {
                string toolcode = GetDiskVolumeSerialNumber() + GetCpuSerialNumber();
                string pubkey = "<RSAKeyValue><Modulus>xe3teTUwLgmbiwFJwWEQnshhKxgcasglGsfNVFTk0hdqKc9i7wb+gG7HOdPZLh65QyBcFfzdlrawwVkiPEL5kNTX1q3JW5J49mTVZqWd3w49reaLd8StHRYJdyGAL4ZovBhSTThETi+zYvgQ5SvCGkM6/xXOz+lkMaEgeFcjQQs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
                string prikey = "<RSAKeyValue><Modulus>xe3teTUwLgmbiwFJwWEQnshhKxgcasglGsfNVFTk0hdqKc9i7wb+gG7HOdPZLh65QyBcFfzdlrawwVkiPEL5kNTX1q3JW5J49mTVZqWd3w49reaLd8StHRYJdyGAL4ZovBhSTThETi+zYvgQ5SvCGkM6/xXOz+lkMaEgeFcjQQs=</Modulus><Exponent>AQAB</Exponent><P>5flMAd7IrUTx92yomBdJBPDzp1Kclpaw4uXB1Ht+YXqwLW/9icI6mcv7d2O0kuVLSWj8DPZJol9V8AtvHkC3oQ==</P><Q>3FRA9UWcFrVPvGR5bewcL7YqkCMZlybV/t6nCH+gyMfbEvgk+p04F+j8WiHDykWj+BahjScjwyF5SGADbrfJKw==</Q><DP>b4WOU1XbERNfF3JM67xW/5ttPNX185zN2Ko8bbMZXWImr1IgrD5RNqXRo1rphVbGRKoxmIOSv7flr8uLrisKIQ==</DP><DQ>otSZlSq2qomgvgg7PaOLSS+F0TQ/i1emO0/tffhkqT4ah7BgE97xP6puJWZivjAteAGxrxHH+kPY0EY1AzRMNQ==</DQ><InverseQ>Sxyz0fEf5m7GrzAngLDRP/i+QDikJFfM6qPyr3Ub6Y5RRsFbeOWY1tX3jmV31zv4cgJ6donH7W2dSBPi67sSsw==</InverseQ><D>nVqofsIgSZltxTcC8fA/DFz1kxMaFHKFvSK3RKIxQC1JQ3ASkUEYN/baAElB0f6u/oTNcNWVPOqE31IDe7ErQelVc4D26RgFd5V7dSsF3nVz00s4mq1qUBnCBLPIrdb0rcQZ8FUQTsd96qW8Foave4tm8vspbM65iVUBBVdSYYE=</D></RSAKeyValue>";

                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {

                    rsa.FromXmlString(pubkey);

                    RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsa);

                    f.SetHashAlgorithm("SHA1");

                    SHA1Managed sha = new SHA1Managed();

                    byte[] name = sha.ComputeHash(ASCIIEncoding.ASCII.GetBytes(toolcode));
                    byte[] key = Convert.FromBase64String(regcode);

                    return f.VerifySignature(name, key);
                }
            }
            catch
            {
                return false;
            }
        }
Example #29
0
 public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
 {
     RSACryptoServiceProvider provider1 = new RSACryptoServiceProvider();
     provider1.FromXmlString(xmlPrivateKey);
     byte[] buffer1 = provider1.Decrypt(DecryptString, false);
     return new UnicodeEncoding().GetString(buffer1);
 }
Example #30
0
        public string UseSystemRsaDataEncrypt(string needEncryptContent)
        {
            #region Use System Default Encrypt Mether Handler Data
            RSAParameters rsaDefineRap = ConvertPublicKeyToRsaInfo();
            string        modulus      = Convert.ToBase64String(rsaDefineRap.Modulus);
            string        exponent     = Convert.ToBase64String(rsaDefineRap.Exponent);

            string publickey = @"<RSAKeyValue><Modulus>" + modulus + "</Modulus><Exponent>" + exponent + "</Exponent></RSAKeyValue>";
            RSACryptoServiceProvider rsaCrypt = new System.Security.Cryptography.RSACryptoServiceProvider();
            rsaCrypt.FromXmlString(publickey);

            byte[] contentBytes = System.Text.Encoding.UTF8.GetBytes(needEncryptContent);
            int    maxBlockSize = rsaCrypt.KeySize / 8 - 11;

            if (contentBytes.Length <= maxBlockSize)
            {
                return(Convert.ToBase64String(rsaCrypt.Encrypt(contentBytes, false)));
            }

            using (MemoryStream PlaiStream = new MemoryStream(contentBytes))
                using (MemoryStream CrypStream = new MemoryStream())
                {
                    Byte[] Buffer    = new Byte[maxBlockSize];
                    int    BlockSize = PlaiStream.Read(Buffer, 0, maxBlockSize);

                    while (BlockSize > 0)
                    {
                        #region Merge Spilt More Part About Rsa Encrypt String
                        Byte[] ToEncrypt = new Byte[BlockSize];
                        Array.Copy(Buffer, 0, ToEncrypt, 0, BlockSize);

                        Byte[] Cryptograph = DataEncryptWithRsa(ToEncrypt);
                        CrypStream.Write(Cryptograph, 0, Cryptograph.Length);
                        BlockSize = PlaiStream.Read(Buffer, 0, maxBlockSize);
                        #endregion
                    }

                    byte[] encryBytes = rsaCrypt.Encrypt(System.Text.Encoding.UTF8.GetBytes("Hello World"), false);
                    return(Convert.ToBase64String(encryBytes));
                }
            #endregion
        }
Example #31
0
 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);
     }
 }
Example #32
0
        /// <summary>
        /// RSA签名
        /// </summary>
        /// <param name="strKeyPrivate">私钥</param>
        /// <param name="HashbyteSignature">待签名Hash描述</param>
        /// <param name="EncryptedSignatureData">签名后的结果</param>
        /// <returns></returns>
        public static bool SignatureFormatter(string strKeyPrivate, byte[] HashbyteSignature, out byte[] EncryptedSignatureData)
        {
            try
            {
                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);
                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #33
0
 /// <summary>
 /// RSA签名
 /// </summary>
 /// <param name="HashbyteSignature">待签名Hash描述</param>
 /// <param name="strKeyPrivate">私钥</param>
 /// <param name="m_strEncryptedSignatureData">签名后的结果</param>
 /// <returns></returns>
 public static bool SignatureFormatter(this byte[] HashbyteSignature, string strKeyPrivate, ref string strEncryptedSignatureData)
 {
     try
     {
         byte[] EncryptedSignatureData;
         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);
         strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
         return(true);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #34
0
        //RSA签名
        public bool SignatureFormatter(string pStrKeyPrivate, string mStrHashbyteSignature, ref string mStrEncryptedSignatureData)
        {
            byte[] hashbyteSignature;
            byte[] encryptedSignatureData;

            hashbyteSignature = Convert.FromBase64String(mStrHashbyteSignature);
            var rsa = new System.Security.Cryptography.RSACryptoServiceProvider();

            rsa.FromXmlString(pStrKeyPrivate);
            var rsaFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(rsa);

            //设置签名的算法为MD5
            rsaFormatter.SetHashAlgorithm("MD5");
            //执行签名
            encryptedSignatureData = rsaFormatter.CreateSignature(hashbyteSignature);

            mStrEncryptedSignatureData = Convert.ToBase64String(encryptedSignatureData);

            return(true);
        }
Example #35
0
        /// <summary>
        /// RSA签名
        /// </summary>
        /// <param name="p_strKeyPrivate"></param>
        /// <param name="HashbyteSignature"></param>
        /// <param name="EncryptedSignatureData"></param>
        /// <returns></returns>

        public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
        {
            try
            {
                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);
            }
            catch
            {
                throw;
            }
        }
Example #36
0
        public bool SignatureDeformatter(string pStrKeyPublic, byte[] hashbyteDeformatter, string pStrDeformatterData)
        {
            System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();

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

            var deformatterData = Convert.FromBase64String(pStrDeformatterData);

            if (rsaDeformatter.VerifySignature(hashbyteDeformatter, deformatterData))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #37
0
        public void PostData(DataType key, string value)
        {
            var r = new KeyValueList();

            r.SetValue("ErrorCode", 0);
            r.SetValue("ErrorMessage", "");
            r.SetValue("DataType", Convert.ToInt32(key));
            switch (key)
            {
            case DataType.GetRsaKey:
                // Tell IIS to use Machine Key store or creation of RSA service provider will fail.
                var cspParams = new CspParameters();
                cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
                // Create a new instance of RSACryptoServiceProvider.
                var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(1024, cspParams);
                // Import parameters from xml.
                rsa.FromXmlString(xmlParams);
                // Export RSA key to RSAParameters and include:
                //    false - Only public key required for encryption.
                //    true  - Private key required for decryption.
                var rsaPublicKey = rsa.ToXmlString(false);
                r.SetValue("RsaPublicKey", rsaPublicKey);
                break;

            case DataType.SendProfile:
                r.Load(value, true);
                var profile = r.GetValue <UserProfile>("UserProfile");
                var card    = r.GetValue <Card>("Card");
                // Get password from RSA encrypted data.
                var password = Helper.RsaDecrypt(card.EncryptedPass, xmlParams);
                var s        = Helper.AesDecrypt(password, card.EncryptedData);
                card = Helper.DeSerialize <Card>(s);
                r.SetValue("Message", string.Format("Server decrypted '{0}' card with number: {1}", card.Name, card.Number));
                break;

            default:
                break;
            }
            Helper.ResponseScript(r, true);
        }
Example #38
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;   

                            
            }

              
                        
        }
Example #39
0
 /// <summary>
 /// RSA签名验证
 /// </summary>
 /// <param name="HashbyteDeformatter">Hash描述</param>
 /// <param name="strKeyPublic">公钥</param>
 /// <param name="DeformatterData">签名后的结果</param>
 /// <returns></returns>
 public static bool SignatureDeformatter(this byte[] HashbyteDeformatter, string strKeyPublic, byte[] DeformatterData)
 {
     try
     {
         System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
         RSA.FromXmlString(strKeyPublic);
         System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
         //指定解密的时候HASH算法为MD5
         RSADeformatter.SetHashAlgorithm("MD5");
         if (RSADeformatter.VerifySignature(MD5.Create().ComputeHash(HashbyteDeformatter), MD5.Create().ComputeHash(DeformatterData)))
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #40
0
 /// <summary>
 /// RSA签名验证
 /// </summary>
 /// <param name="strKeyPublic">公钥</param>
 /// <param name="HashbyteDeformatter">Hash描述</param>
 /// <param name="DeformatterData">签名后的结果</param>
 /// <returns></returns>
 public static bool SignatureDeformatter(string strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData)
 {
     try
     {
         System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
         strKeyPublic = regBitStrength.Replace(strKeyPublic, "");
         RSA.FromXmlString(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);
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #41
0
            /// <summary>
            /// Create a signature xml element for the specified xml document and private key
            /// </summary>
            /// <param name="xmlToSign"></param>
            /// <param name="keyPubPri">Private+public key</param>
            /// <returns></returns>
            public static System.Xml.XmlElement CreateSignature(System.Xml.XmlDocument xmlToSign, string keyPubPri)
            {
                System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                rsa.FromXmlString(keyPubPri);

                System.Security.Cryptography.Xml.SignedXml sx = new System.Security.Cryptography.Xml.SignedXml(xmlToSign);
                sx.SigningKey = rsa;

                // Create a reference to be signed
                System.Security.Cryptography.Xml.Reference reference = new System.Security.Cryptography.Xml.Reference("");

                // Set the canonicalization method for the document.
                sx.SignedInfo.CanonicalizationMethod = System.Security.Cryptography.Xml.SignedXml.XmlDsigCanonicalizationUrl; // No comments.

                // Add an enveloped transformation to the reference.
                System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform env = new System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform(false);
                reference.AddTransform(env);

                sx.AddReference(reference);

                sx.ComputeSignature();

                return(sx.GetXml());
            }
Example #42
0
        /// <summary>
        /// 秘密鍵を使って文字列を復号化する
        /// </summary>
        /// <param name="str">Encryptメソッドにより暗号化された文字列</param>
        /// <returns>復号化された文字列</returns>
        public static string ClientDecrypt(string str)
        {
            try
            {
                //RSACryptoServiceProviderオブジェクトの作成
                var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(KeySize);

                //秘密鍵を指定
                rsa.FromXmlString(clientPrivateKey);

                //復号化する文字列をバイト配列に
                byte[] data = System.Convert.FromBase64String(str);
                //復号化する
                byte[] decryptedData = rsa.Decrypt(data, false);

                //結果を文字列に変換
                return(System.Text.Encoding.UTF8.GetString(decryptedData));
            }
            catch (Exception)
            {
            }

            return(null);
        }
Example #43
0
        public string Encrypt(string publicKey, string plainText)
        {
            System.Security.Cryptography.CspParameters            cspParams   = null;
            System.Security.Cryptography.RSACryptoServiceProvider rsaProvider = null;
            byte[] plainBytes     = null;
            byte[] encryptedBytes = null;

            string result = "";

            try
            {
                cspParams = new System.Security.Cryptography.CspParameters();
                cspParams.ProviderType = 1;
                rsaProvider            = new System.Security.Cryptography.RSACryptoServiceProvider(cspParams);

                rsaProvider.FromXmlString(publicKey);

                plainBytes     = System.Text.Encoding.UTF8.GetBytes(plainText);
                encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
                result         = Convert.ToBase64String(encryptedBytes);
            }
            catch (Exception ex) { Log(ex.Message); }
            return(result);
        }
Example #44
0
    //===============================================================================
    // Name: Function IALUGenerator_GenKey
    // Input:
    //   ByRef Lic As ActiveLock3.ProductLicense - Product license
    //   ByVal InstCode As String - Installation Code sent by the user
    //   ByVal RegisteredLevel As String - Registration Level for the license. Default is "0"
    // Output:
    //   String - Liberation key for the license
    // Purpose: Given the Installation Code, generates an Activelock license liberation key.
    // Remarks: None
    //===============================================================================
    private string IALUGenerator_GenKey(ref ActiveLock3_6NET.ProductLicense Lic, string InstCode, [System.Runtime.InteropServices.OptionalAttribute, System.Runtime.InteropServices.DefaultParameterValueAttribute("0")]      // ERROR: Optional parameters aren't supported in C#
                                        string RegisteredLevel)
    {
        // Take request code and decrypt it.
        string strReq = null;

        // 05.13.05 - ialkan Modified to merge DLLs into one
        strReq = modBase64.Base64_Decode(ref InstCode);

        // strReq now contains the {LockCode + vbLf + User} string
        string strLock = string.Empty;
        string strUser = string.Empty;

        GetLockAndUserFromInstallCode(strReq, ref strLock, ref strUser);

        Lic.Licensee = strUser;
        // registration date
        string strRegDate = null;

        // registered level
        Lic.RegisteredLevel = RegisteredLevel;
        strRegDate          = Lic.RegisteredDate;

        string strEncrypted = null;

        // @todo Rethink this bit about encrypting the dates.
        // We need to keep in mind that the app does not have access to the private key, so and any decryption that requires private key
        // would not be possible.
        // Perhaps instead of encrypting, we could do MD5 hash of (regdate+lockcode)?
        //ActiveLockEventSink_ValidateValue strRegDate, strEncrypted
        // hash it
        //strEncrypted = ActiveLock3.MD5Hash(strEncrypted)
        strEncrypted = strRegDate;

        // get software codes
        ProductInfo ProdInfo = null;

        ProdInfo       = IALUGenerator_RetrieveProduct(Lic.ProductName, Lic.ProductVer);
        Lic.ProductKey = ProdInfo.VCode;

        string strLic = null;

        strLic = Lic.ToString_Renamed() + Constants.vbLf + strLock;
        System.Diagnostics.Debug.WriteLine("strLic: " + Constants.vbCrLf + strLic);

        if (modALUGEN.strLeft(ProdInfo.VCode, 3) != "RSA")
        {
            // sign it
            string strSig = null;
            strSig = new string(Strings.Chr(0), 1024);
            // 05.13.05 - ialkan Modified to merge DLLs into one. Moved RSASign into a module
            strSig = modActiveLock.RSASign(ProdInfo.VCode, ProdInfo.GCode, strLic);

            // Create liberation key.  This will be a base-64 encoded string of the whole license.
            string strLicKey = null;
            // 05.13.05 - ialkan Modified to merge DLLs into one
            strLicKey = modBase64.Base64_Encode(ref strSig);
            // update Lic with license key
            Lic.LicenseKey = strLicKey;
            // Print some info for debugging purposes
            System.Diagnostics.Debug.WriteLine("VCode: " + ProdInfo.VCode);
            System.Diagnostics.Debug.WriteLine("Lic: " + strLic);
            System.Diagnostics.Debug.WriteLine("Lic hash: " + modMD5.Hash(ref strLic));
            System.Diagnostics.Debug.WriteLine("LicKey: " + strLicKey);
            System.Diagnostics.Debug.WriteLine("Sig: " + strSig);
            System.Diagnostics.Debug.WriteLine("Verify: " + modActiveLock.RSAVerify(ProdInfo.VCode, strLic, modBase64.Base64_Decode(ref strLicKey)));
            System.Diagnostics.Debug.WriteLine("====================================================");
        }

        else
        {
            try {
                System.Security.Cryptography.RSACryptoServiceProvider rsaCSP = new System.Security.Cryptography.RSACryptoServiceProvider();
                string strPublicBlob  = null;
                string strPrivateBlob = null;

                strPublicBlob  = ProdInfo.VCode;
                strPrivateBlob = ProdInfo.GCode;

                if (modALUGEN.strLeft(ProdInfo.GCode, 6) == "RSA512")
                {
                    strPrivateBlob = modALUGEN.strRight(ProdInfo.GCode, Strings.Len(ProdInfo.GCode) - 6);
                }
                else
                {
                    strPrivateBlob = modALUGEN.strRight(ProdInfo.GCode, Strings.Len(ProdInfo.GCode) - 7);
                }
                // import private key params into instance of RSACryptoServiceProvider
                rsaCSP.FromXmlString(strPrivateBlob);
                RSAParameters rsaPrivateParams = default(RSAParameters);
                //stores private key
                rsaPrivateParams = rsaCSP.ExportParameters(true);
                rsaCSP.ImportParameters(rsaPrivateParams);

                byte[] userData = Encoding.UTF8.GetBytes(strLic);

                AsymmetricSignatureFormatter asf = new RSAPKCS1SignatureFormatter(rsaCSP);
                HashAlgorithm algorithm          = new SHA1Managed();
                asf.SetHashAlgorithm(algorithm.ToString());
                byte[] myhashedData = null;
                // a byte array to store hash value
                string myhashedDataString = null;
                myhashedData       = algorithm.ComputeHash(userData);
                myhashedDataString = BitConverter.ToString(myhashedData).Replace("-", string.Empty);
                byte[] mysignature = null;
                // holds signatures
                mysignature = asf.CreateSignature(algorithm);
                string mySignatureBlock = null;
                mySignatureBlock = Convert.ToBase64String(mysignature);
                Lic.LicenseKey   = mySignatureBlock;
            }
            catch (Exception ex) {
                modActiveLock.Set_Locale(modActiveLock.regionalSymbol);
                Err().Raise(AlugenGlobals.alugenErrCodeConstants.alugenProdInvalid, modTrial.ACTIVELOCKSTRING, ex.Message);
            }
        }

        // Serialize it into a formatted string
        string strLibKey = string.Empty;

        Lic.Save(ref strLibKey);
        return(strLibKey);
    }
Example #45
0
        public static Claim DeserializeClaim(XmlDictionaryReader reader, SctClaimDictionary dictionary, XmlObjectSerializer serializer)
        {
            if (reader.IsStartElement(dictionary.NullValue, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return(null);
            }
            else if (reader.IsStartElement(dictionary.WindowsSidClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                byte[] sidBytes = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return(new Claim(ClaimTypes.Sid, new SecurityIdentifier(sidBytes, 0), right));
            }
            else if (reader.IsStartElement(dictionary.DenyOnlySidClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                byte[] sidBytes = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return(new Claim(ClaimTypes.DenyOnlySid, new SecurityIdentifier(sidBytes, 0), right));
            }
            else if (reader.IsStartElement(dictionary.X500DistinguishedNameClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                byte[] rawData = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return(new Claim(ClaimTypes.X500DistinguishedName, new X500DistinguishedName(rawData), right));
            }
            else if (reader.IsStartElement(dictionary.X509ThumbprintClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                byte[] thumbprint = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return(new Claim(ClaimTypes.Thumbprint, thumbprint, right));
            }
            else if (reader.IsStartElement(dictionary.NameClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string name = reader.ReadString();
                reader.ReadEndElement();
                return(new Claim(ClaimTypes.Name, name, right));
            }
            else if (reader.IsStartElement(dictionary.DnsClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string dns = reader.ReadString();
                reader.ReadEndElement();
                return(new Claim(ClaimTypes.Dns, dns, right));
            }
            else if (reader.IsStartElement(dictionary.RsaClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string rsaXml = reader.ReadString();
                reader.ReadEndElement();

                System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
                rsa.FromXmlString(rsaXml);
                return(new Claim(ClaimTypes.Rsa, rsa, right));
            }
            else if (reader.IsStartElement(dictionary.MailAddressClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string address = reader.ReadString();
                reader.ReadEndElement();
                return(new Claim(ClaimTypes.Email, new System.Net.Mail.MailAddress(address), right));
            }
            else if (reader.IsStartElement(dictionary.SystemClaim, dictionary.EmptyString))
            {
                reader.ReadElementString();
                return(Claim.System);
            }
            else if (reader.IsStartElement(dictionary.HashClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                byte[] hash = reader.ReadContentAsBase64();
                reader.ReadEndElement();
                return(new Claim(ClaimTypes.Hash, hash, right));
            }
            else if (reader.IsStartElement(dictionary.SpnClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string spn = reader.ReadString();
                reader.ReadEndElement();
                return(new Claim(ClaimTypes.Spn, spn, right));
            }
            else if (reader.IsStartElement(dictionary.UpnClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string upn = reader.ReadString();
                reader.ReadEndElement();
                return(new Claim(ClaimTypes.Upn, upn, right));
            }
            else if (reader.IsStartElement(dictionary.UrlClaim, dictionary.EmptyString))
            {
                string right = ReadRightAttribute(reader, dictionary);
                reader.ReadStartElement();
                string url = reader.ReadString();
                reader.ReadEndElement();
                return(new Claim(ClaimTypes.Uri, new Uri(url), right));
            }
            else
            {
                return((Claim)serializer.ReadObject(reader));
            }
        }
Example #46
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
Example #47
-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);
 }