Наследование: RSA, ICspAsymmetricAlgorithm
		/// <summary>
		/// Initializes a new instance of the <see cref="AsymmetricCryptoKeyStoreWrapper"/> class.
		/// </summary>
		/// <param name="dataStore">The data store.</param>
		/// <param name="asymmetricCrypto">The asymmetric protection to apply to symmetric keys.  Must include the private key.</param>
		public AsymmetricCryptoKeyStoreWrapper(ICryptoKeyStore dataStore, RSACryptoServiceProvider asymmetricCrypto) {
			Contract.Requires<ArgumentNullException>(dataStore != null);
			Contract.Requires<ArgumentNullException>(asymmetricCrypto != null);
			Contract.Requires<ArgumentException>(!asymmetricCrypto.PublicOnly);
			this.dataStore = dataStore;
			this.asymmetricCrypto = asymmetricCrypto;
		}
Пример #2
0
        public static string Decrypt(this string stringToDecrypt, string key)
        {
            if (string.IsNullOrEmpty(stringToDecrypt))
            {
                throw new ArgumentException("An empty string value cannot be encrypted.");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
            }

            //var cspp = new CspParameters { KeyContainerName = key };
            var cspp = new CspParameters { KeyContainerName = key, Flags = CspProviderFlags.UseMachineKeyStore };

            var rsa = new RSACryptoServiceProvider(cspp) { PersistKeyInCsp = true };

            var decryptArray = stringToDecrypt.Split(new[] { "-" }, StringSplitOptions.None);
            var decryptByteArray = Array.ConvertAll(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));


            byte[] bytes = rsa.Decrypt(decryptByteArray, true);

            string result = System.Text.Encoding.UTF8.GetString(bytes);

            return result;
        }
Пример #3
0
        protected void btnEncrypt_Click(object sender, EventArgs e)
        {
            try
            {
                string dataToEncrypt = "revathis";
               // byte[] inputData = null;
                byte[] encryptedData;

               // inputData= Convert.ToByte(dataToEncrypt);

                using (RSACryptoServiceProvider rsaServiceProvider = new RSACryptoServiceProvider())
                {
                   // dataToEncrypt
                    //inputData = rsaServiceProvider.

                     encryptedData= rsaServiceProvider.Encrypt(Encoding.ASCII.GetBytes(dataToEncrypt), false);
                     Response.Write("Encrypted Data: ");
                     foreach (byte byteItem in encryptedData)
                     {
                         Response.Write(byteItem);
                     }

                }

            }
            catch (Exception)
            {

                throw;
            }
        }
        //static RSACryptoServiceProvider RSA;

        //public static void ExportParameters()
        //{
        //    var publicKey = RSA.ExportParameters(false);

        //    //            +Exponent    { byte[3]}
        //    //+Modulus { byte[256]}


        //}


        public async Task<byte[]> Encrypt(byte[] Exponent, byte[] Modulus)
        {
			// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201503/20150323

			// encrypted state sharing.

			// what about import?

			// http://bouncy-castle.1462172.n4.nabble.com/Interoperability-issue-with-SunJCE-OAEP-td4656157.html

			// http://www.w3.org/TR/WebCryptoAPI/#rsa-oaep
			// RSA/ECB/OAEPWithSHA-1AndMGF1Padding

			// X:\jsc.svn\examples\java\hybrid\JVMCLRCryptoKeyExport\JVMCLRCryptoKeyExport\Program.cs

			//var n = new RSACryptoServiceProvider(2048);
			var n = new RSACryptoServiceProvider();

			// can we import in java android?
            n.ImportParameters(
                new RSAParameters { Exponent = Exponent, Modulus = Modulus }
            );

            // http://stackoverflow.com/questions/9839274/rsa-encryption-by-supplying-modulus-and-exponent

            var value = n.Encrypt(
                Encoding.UTF8.GetBytes("hello from server"), fOAEP: true
            );

            //Array.Reverse(value);

            return value;
        }
Пример #5
0
 protected override void OnConnect()
 {
     base.OnConnect();
     m_rsa = new RSACryptoServiceProvider();
     RSAParameters para = m_rsa.ExportParameters(false);
     SendRSAKey(para.Modulus, para.Exponent);
 }
Пример #6
0
 public ProxyRsaKeyParameters(RSACryptoServiceProvider proxy)
     : base(false, 
         new Math.BigInteger(1, proxy.ExportParameters(false).Modulus),
         new Math.BigInteger(1, proxy.ExportParameters(false).Exponent))
 {
     this.proxy = proxy;
 }
Пример #7
0
        static void EncryptSomeText()
        {
            string dataToBeEncrypted = "My secret text!";
            Console.WriteLine("Original: {0}", dataToBeEncrypted);

            var encryptedData = Encrypt(dataToBeEncrypted);
            Console.WriteLine("Cipher data: {0}", encryptedData.Aggregate<byte, string>("", (s, b) => s += b.ToString()));

            var decryptedString = Decrypt(encryptedData);

            Console.WriteLine("Decrypted:{0}", decryptedString);

            // As you can see, you first need to convert the data you want to encrypt to a byte sequence.
            // To encrypt the data, you need only the public key.
            // You then use the private key to decrypt the data.

            // Because of this, it’s important to store the private key in a secure location.
            // If you would store it in plain text on disk or even in a nonsecure memory location,
            // your private key could be extracted and your security would be compromised.

            // The .NET Framework offers a secure location for storing asymmetric keys in a key container.
            // A key container can be specific to a user or to the whole machine.
            // This example shows how to configure an RSACryptoServiceProvider to use a key container for saving and loading the asymmetric key.

            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] dataToEncrypt = ByteConverter.GetBytes(dataToBeEncrypted);
            string containerName = "SecretContainer";
            CspParameters csp = new CspParameters() { KeyContainerName = containerName };

            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(csp))
            {
                var encryptedByteData = RSA.Encrypt(dataToEncrypt, false);
            }
        }
Пример #8
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);
     }
 }
Пример #9
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);
        }
Пример #10
0
        // Copied from ACS code
        // This method returns an AsymmetricSignatureFormatter capable of supporting Sha256 signatures. 
        private static RSACryptoServiceProvider GetCryptoProviderForSha256(RSACryptoServiceProvider rsaProvider)
        {
            const int PROV_RSA_AES = 24;    // CryptoApi provider type for an RSA provider supporting sha-256 digital signatures
            if (rsaProvider.CspKeyContainerInfo.ProviderType == PROV_RSA_AES)
            {
                return rsaProvider;
            }

            CspParameters csp = new CspParameters
            {
                ProviderType = PROV_RSA_AES,
                KeyContainerName = rsaProvider.CspKeyContainerInfo.KeyContainerName,
                KeyNumber = (int)rsaProvider.CspKeyContainerInfo.KeyNumber
            };

            if (rsaProvider.CspKeyContainerInfo.MachineKeyStore)
            {
                csp.Flags = CspProviderFlags.UseMachineKeyStore;
            }

            //
            // If UseExistingKey is not specified, the CLR will generate a key for a non-existent group.
            // With this flag, a CryptographicException is thrown instead.
            //
            csp.Flags |= CspProviderFlags.UseExistingKey;
            return new RSACryptoServiceProvider(csp);
        }
Пример #11
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;
            }
        }
Пример #12
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);
        }
Пример #13
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);
 }
Пример #14
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);
 }
        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();
            }
        }
Пример #16
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
            });
        }
Пример #17
0
        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();
               }
        }
Пример #18
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
            });
        }
Пример #19
0
		static OAuthServerHelper()
		{
			RSAParameters privateRsaParameters;
			RSAParameters publicRsaParameters;
			using (var rsaKeyGen = new RSACryptoServiceProvider(RsaKeySize))
			{
				privateRsaParameters = rsaKeyGen.ExportParameters(true);
				publicRsaParameters = rsaKeyGen.ExportParameters(false);
			}

			Tuple<byte[], byte[]> aesKeyAndIV;
			using (var aesKeyGen = new AesCryptoServiceProvider())
			{
				aesKeyAndIV = Tuple.Create(aesKeyGen.Key, aesKeyGen.IV);
			}

			rsa = new ThreadLocal<RSACryptoServiceProvider>(() =>
			{
				var result = new RSACryptoServiceProvider();
				result.ImportParameters(privateRsaParameters);
				return result;
			});

			aes = new ThreadLocal<AesCryptoServiceProvider>(() =>
			{
				var result = new AesCryptoServiceProvider();
				result.Key = aesKeyAndIV.Item1;
				result.IV = aesKeyAndIV.Item2;
				return result;
			});

			rsaExponent = OAuthHelper.BytesToString(publicRsaParameters.Exponent);
			rsaModulus = OAuthHelper.BytesToString(publicRsaParameters.Modulus);
		}
        public void AssignNewKey()
        {
            using (var rsa = new RSACryptoServiceProvider(2048))
            {
                rsa.PersistKeyInCsp = false;
                //in memory
                publicKey = rsa.ExportParameters(false);
                privateKey = rsa.ExportParameters(true);
                return;

                //to file
                File.WriteAllText(@"C:\git\CryptographyDemo\CryptographyDemo\bin\Debug\public.txt", rsa.ToXmlString(false));
                File.WriteAllText(@"C:\git\CryptographyDemo\CryptographyDemo\bin\Debug\private.txt", rsa.ToXmlString(true));
            }

            //To key container, stored for windows user
            const int providerRsaFull = 1;
            CspParameters cspParams = new CspParameters(providerRsaFull);
            cspParams.KeyContainerName = "TomsContainer";
            cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
            cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
            var rsa2 = new RSACryptoServiceProvider(cspParams);
            rsa2.PersistKeyInCsp = true;

            // SHOULD THEN DELETE KEY
        }
Пример #21
0
        static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                byte[] decryptedData;
                //Create a new instance of RSACryptoServiceProvider. 
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    //Import the RSA Key information. This needs 
                    //to include the private key information.
                    RSA.ImportParameters(RSAKeyInfo);

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

        }
Пример #22
0
        public void Assign()
        {
            // AssignParameter();
            RSA = new RSACryptoServiceProvider(1024);

            if (File.Exists(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\privatekey.xml") == true)
                File.Delete(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\privatekey.xml");
            if (File.Exists(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\publickey.xml") == true)
                File.Delete(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\publickey.xml");

            //provide public and private RSA params
            FileStream fs = new FileStream(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\privatekey.xml", FileMode.CreateNew, FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(fs);
            string publicPrivateKeyXML = RSA.ToXmlString(true);
            sw.Write(publicPrivateKeyXML);
            sw.Close();
            fs.Close();

            FileStream fs2 = new FileStream(@"C:\Users\Chris\Documents\Cambridge\Part II Project\Code\Encryption Example\EncryptionExample\publickey.xml", FileMode.CreateNew, FileAccess.ReadWrite);
            StreamWriter sw2 = new StreamWriter(fs2);
            string publicOnlyKeyXML = RSA.ToXmlString(false);
            sw2.Write(publicOnlyKeyXML);
            sw2.Close();
            fs2.Close();
        }
Пример #23
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();
        }
Пример #24
0
        public static Boolean Test(int keySize)
        {
            Boolean bRes = true;
            Byte[] abPlain = { 0, 1, 2, 3, 4, 5, 6, 7 };
            Byte[] abCipher = null;
            int kl = keySize;

            try
            {
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(kl))
                {
                    abCipher = rsa.Encrypt(abPlain);
                    Log.Comment("Cipher is : ");
                    PrintByteArray(abCipher);
                    abCipher = rsa.Decrypt(abCipher);
                }
                Log.Comment("Decrypted plaintext is : ");
                PrintByteArray(abCipher);

                if (!Compare(abPlain, abCipher))
                {
                    bRes = false;
                    Log.Comment("Failed to decrypt to the original plaintext");
                }

            }
            catch (Exception e)
            {
                Log.Comment("Exception ocured :\n" + e.ToString());
                bRes = false;
            }

            return bRes;
        }
Пример #25
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;
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="AsymmetricCryptoKeyStoreWrapper"/> class.
		/// </summary>
		/// <param name="dataStore">The data store.</param>
		/// <param name="asymmetricCrypto">The asymmetric protection to apply to symmetric keys.  Must include the private key.</param>
		public AsymmetricCryptoKeyStoreWrapper(ICryptoKeyStore dataStore, RSACryptoServiceProvider asymmetricCrypto) {
			Requires.NotNull(dataStore, "dataStore");
			Requires.NotNull(asymmetricCrypto, "asymmetricCrypto");
			Requires.True(!asymmetricCrypto.PublicOnly, "asymmetricCrypto");
			this.dataStore = dataStore;
			this.asymmetricCrypto = asymmetricCrypto;
		}
Пример #27
0
        public void GeneratedXmlIsSerializableToLicenseDetails()
        {
            // Setup
            var key = new RSACryptoServiceProvider();
            var generator = new LicenseGenerator(key);
            var testLicense = new LicenseDetails
            {
                StartDate = DateTime.Now,
                EndDate = DateTime.Now.AddMonths(1),
                Application = "Test App",
                MinVersion = new SerializableVersion(1, 2, 3, 4),
                MaxVersion = new SerializableVersion(5, 6, 7, 8),
                LicensedUserName = "******",
                LicenseKey = "1234",
                CustomValues = new SerializableDictionary<string, string>
                {
                    {"Key1", "val2"},
                    {"Key2", "Val2"}
                }
            };

            // Test
            var rawXml = generator.GenerateSignedXml(testLicense);

            // Verify
            LicenseDetails verificationLicense;
            Assert.IsNotNullOrEmpty(rawXml, "Null or empty xml returned");

            var deserializer = new XmlSerializer(typeof (LicenseDetails));

            using (TextReader reader = new StringReader(rawXml))
                verificationLicense = (LicenseDetails) deserializer.Deserialize(reader);

            Assert.IsTrue(testLicense.Equals(verificationLicense), "Licenses were not equal");
        }
Пример #28
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();
                }
            }
        }
Пример #29
0
        /// <summary>
        /// Generate keys into specified files.
        /// </summary>
        /// <param name="publicKeyFileName">Name of the file that will contain public key</param>
        /// <param name="privateKeyFileName">Name of the file that will contain private key</param>
        public void GenerateKeys(out byte[] publicKey, out byte[] privateKey)
        {
            // Variables
            CspParameters cspParams = null;
            RSACryptoServiceProvider rsaProvider = null;

            try
            {
                // Create a new key pair on target CSP
                cspParams = new CspParameters()
                {
                    ProviderType = 1,                          // PROV_RSA_FULL
                    Flags = CspProviderFlags.UseArchivableKey, // can be exported
                    KeyNumber = (int)KeyNumber.Exchange        // can be safely stored and exchanged
                };

                rsaProvider = new RSACryptoServiceProvider(cspParams);
                rsaProvider.PersistKeyInCsp = false;

                // Export public key only
                publicKey = rsaProvider.ExportCspBlob(false);
                privateKey = rsaProvider.ExportCspBlob(true);
            }
            catch (Exception ex)
            {
                Debug.Fail(string.Format("Exception occured while generating keys: {0}", ex.Message));
                publicKey = null;
                privateKey = null;
            }
            finally
            {
                if (rsaProvider != null) rsaProvider.PersistKeyInCsp = false;
            }
        }
Пример #30
0
 /// <summary>
 /// RSA签名
 /// </summary>
 /// <param name="strKeyPrivate">私钥</param>
 /// <param name="strHashbyteSignature">待签名Hash描述</param>
 /// <param name="strEncryptedSignatureData">签名后的结果</param>
 /// <returns></returns>
 public bool SignatureFormatter(string strKeyPrivate, string strHashbyteSignature, ref string strEncryptedSignatureData)
 {
     try
     {
         byte[] HashbyteSignature;
         byte[] EncryptedSignatureData;
         HashbyteSignature = Convert.FromBase64String(strHashbyteSignature);
         System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
         RSA.FromXmlString(strKeyPrivate);
         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;
     }
 }
Пример #31
0
        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);
            }
        }
Пример #32
0
        public bool SignatureDeformatter(string pStrKeyPublic, byte[] hashbyteDeformatter, string pStrDeformatterData)
        {
            byte[] deformatterData;

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

            rsa.FromXmlString(pStrKeyPublic);
            var rsaDeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(rsa);

            //指定解密的时候HASH算法为MD5
            rsaDeformatter.SetHashAlgorithm("MD5");

            deformatterData = Convert.FromBase64String(pStrDeformatterData);

            if (rsaDeformatter.VerifySignature(hashbyteDeformatter, deformatterData))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #33
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;
     }
 }
Пример #34
0
        public void GenerateKeys()
        {
            System.Security.Cryptography.CspParameters            cspParams   = null;
            System.Security.Cryptography.RSACryptoServiceProvider rsaProvider = null;

            string publicKey  = "";
            string privateKey = "";

            try
            {
                cspParams = new System.Security.Cryptography.CspParameters();
                cspParams.ProviderType = 1;
                cspParams.Flags        = System.Security.Cryptography.CspProviderFlags.UseArchivableKey;
                cspParams.KeyNumber    = (int)System.Security.Cryptography.KeyNumber.Exchange;
                rsaProvider            = new System.Security.Cryptography.RSACryptoServiceProvider(cspParams);

                publicKey  = rsaProvider.ToXmlString(false);
                privateKey = rsaProvider.ToXmlString(true);
            }
            catch (Exception ex)
            {
                Log(ex.Message);
            }
        }
Пример #35
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);
        }
Пример #36
0
        public static byte[] RSADecrypt(byte[] privateKey, byte[] dataToDecrypt)
        {
            // helper to RSA decrypt a given blob

            // PROV_RSA_AES == 24
            var cspParameters = new System.Security.Cryptography.CspParameters(24);

            using (var rsaProvider = new System.Security.Cryptography.RSACryptoServiceProvider(cspParameters))
            {
                try
                {
                    rsaProvider.PersistKeyInCsp = false;
                    rsaProvider.ImportCspBlob(privateKey);

                    byte[] dataToDecryptRev = new byte[256];

                    Buffer.BlockCopy(dataToDecrypt, 0, dataToDecryptRev, 0, dataToDecrypt.Length); // ... Array.Copy? naw... :(

                    Array.Reverse(dataToDecryptRev);                                               // ... don't ask me how long it took to realize this :(

                    byte[] dec = rsaProvider.Decrypt(dataToDecryptRev, false);                     // no padding
                    return(dec);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error decryption domain key: {0}", e.Message);
                }
                finally
                {
                    rsaProvider.PersistKeyInCsp = false;
                    rsaProvider.Clear();
                }
            }

            return(new byte[0]);
        }
Пример #37
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);
        }
Пример #38
0
        /*
         * converts a bouncy castle private key to a windows private key
         */
        private static sys2.AsymmetricAlgorithm ConvertToSystemKey(RsaPrivateCrtKeyParameters privateKey)
        {
            sys2.CspParameters cspPars = new sys2.CspParameters
            {
                KeyContainerName = Guid.NewGuid().ToString(),
                KeyNumber        = (int)sys2.KeyNumber.Exchange
            };

            sys2.RSACryptoServiceProvider rsaCryptoProvider = new sys2.RSACryptoServiceProvider(cspPars);
            sys2.RSAParameters            rsaParameters     = new sys2.RSAParameters
            {
                Modulus  = privateKey.Modulus.ToByteArrayUnsigned(),
                P        = privateKey.P.ToByteArrayUnsigned(),
                Q        = privateKey.Q.ToByteArrayUnsigned(),
                DP       = privateKey.DP.ToByteArrayUnsigned(),
                DQ       = privateKey.DQ.ToByteArrayUnsigned(),
                InverseQ = privateKey.QInv.ToByteArrayUnsigned(),
                D        = privateKey.Exponent.ToByteArrayUnsigned(),
                Exponent = privateKey.PublicExponent.ToByteArrayUnsigned()
            };

            rsaCryptoProvider.ImportParameters(rsaParameters);
            return(rsaCryptoProvider);
        }
 /// <summary>Verifies that a digital signature is valid by determining the hash value in the signature using the specified hashing algorithm and padding, and comparing it to the provided hash value. </summary>
 /// <param name="hash">The hash value of the signed data. </param>
 /// <param name="signature">The signature data to be verified. </param>
 /// <param name="hashAlgorithm">The hash algorithm name used to create the hash value. </param>
 /// <param name="padding">The padding. </param>
 /// <returns>
 ///     <see langword="true" /> if the signature is valid; otherwise, <see langword="false" />. </returns>
 /// <exception cref="T:System.ArgumentException">
 ///         <paramref name="hashAlgorithm" /> is <see langword="null" /> or <see cref="F:System.String.Empty" />. </exception>
 /// <exception cref="T:System.ArgumentNullException">
 ///         <paramref name="hash" /> is <see langword="null" />. -or-
 ///         <paramref name="padding" /> is <see langword="null" />. </exception>
 /// <exception cref="T:System.Security.Cryptography.CryptographicException">
 ///         <paramref name="padding" /> does not equal <see cref="P:System.Security.Cryptography.RSASignaturePadding.Pkcs1" />. </exception>
 // Token: 0x060022CF RID: 8911 RVA: 0x0007D290 File Offset: 0x0007B490
 public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
 {
     if (hash == null)
     {
         throw new ArgumentNullException("hash");
     }
     if (signature == null)
     {
         throw new ArgumentNullException("signature");
     }
     if (string.IsNullOrEmpty(hashAlgorithm.Name))
     {
         throw RSA.HashAlgorithmNameNullOrEmpty();
     }
     if (padding == null)
     {
         throw new ArgumentNullException("padding");
     }
     if (padding != RSASignaturePadding.Pkcs1)
     {
         throw RSACryptoServiceProvider.PaddingModeNotSupported();
     }
     return(this.VerifyHash(hash, RSACryptoServiceProvider.GetAlgorithmId(hashAlgorithm), signature));
 }
Пример #40
0
        /// <inheritdoc/>
        public ICryptographicKey ImportKeyPair(byte[] keyBlob, CryptographicPrivateKeyBlobType blobType = CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo)
        {
            Requires.NotNull(keyBlob, "keyBlob");

            var parameters = KeyFormatter.GetFormatter(blobType).Read(keyBlob);

            Platform.RSA rsa;
            if (CapiKeyFormatter.IsCapiCompatible(parameters))
            {
                rsa = new Platform.RSACryptoServiceProvider();
            }
            else
            {
#if DESKTOP
                rsa = new RSAManaged();
#else
                CapiKeyFormatter.VerifyCapiCompatibleParameters(parameters);
                throw new NotSupportedException();
#endif
            }

            rsa.ImportParameters(KeyFormatter.ToPlatformParameters(parameters));
            return(new RsaCryptographicKey(rsa, this.algorithm));
        }
Пример #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());
            }
Пример #42
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;
     }
 }
Пример #43
0
 /// <summary>
 /// RSA签名验证
 /// </summary>
 /// <param name="strKeyPublic">公钥</param>
 /// <param name="HashbyteDeformatter">Hash描述</param>
 /// <param name="DeformatterData">签名后的结果</param>
 /// <returns></returns>
 public bool SignatureDeformatter(string strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData)
 {
     try
     {
         System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
         //RSA.FromXmlString(strKeyPublic);
         RSA.ImportCspBlob(Convert.FromBase64String(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;
     }
 }
Пример #44
0
             /// <summary>  
             /// RSA签名  
             /// </summary>  
             /// <param name="strKeyPrivate">私钥</param>  
             /// <param name="strHashbyteSignature">待签名Hash描述</param>  
             /// <param name="strEncryptedSignatureData">签名后的结果</param>  
             /// <returns></returns>  
            public bool SignatureFormatter(string strKeyPrivate,  string strHashbyteSignature,  ref string strEncryptedSignatureData)   
            
        {
              
                    try  
                     {
                  
                            byte[]  HashbyteSignature;   

                                byte[]  EncryptedSignatureData;   
                                HashbyteSignature  =  Convert.FromBase64String(strHashbyteSignature);   
                            System.Security.Cryptography.RSACryptoServiceProvider RSA  =  new System.Security.Cryptography.RSACryptoServiceProvider();   
                            RSA.FromXmlString(strKeyPrivate);   
                            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;   

                            
            }

              
                        
        }
Пример #45
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
Пример #46
0
 public void RSAKey(out string xmlKeys, out string xmlPublicKey)
 {
     System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider();
     xmlKeys      = rSACryptoServiceProvider.ToXmlString(true);
     xmlPublicKey = rSACryptoServiceProvider.ToXmlString(false);
 }
Пример #47
0
        public async Task ValidLocallySignedAccessToken_FromX509Certificate()
        {
#if NETSTANDARD
            const string sPfx = @"
MIIGMQIBAzCCBfcGCSqGSIb3DQEHAaCCBegEggXkMIIF4DCCAt8GCSqGSIb3DQEHBqCCAtAwggLM
AgEAMIICxQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQImgNbotR3pnACAggAgIICmMHYqn7R
91hqe5gpwTGxNHaDmrvaLWfBq17xyVIdboPxzSAX4MoNasJplZgCzlN4vMwsY9CG3aY/AV5b4qF3
GRlkR5Ou3xJ84WJUkKkjVcql7hXZ8Zl8hyMKfQgW7SYpmJK/I4qYPqz5wg2ivZ4YbH4KA+VL9eaX
XR5KKdePWt+P9T3oFD1GYAjdPRTL/phSflvv01v2vkmx6In5hS10w2LjxyOJQtiHocOyEe7XAtor
bjsPi9jzMQmW5OESh9c+LDgEHCQQrccc0kG9j+GYJ65b7qORGq9OzBarVgiK+QGrC6aZhGgXZjMD
2K/efd4igVN/QqbpMHB+BDkZKQDRiEc4ezDqZ1VRP8T6VrYP/C+vhvPjZLgIacsxzxZ3f497OkOQ
pnrdpvBC6vPUxzsBpSTMcYlUGObWu+PNuwbOsQabps55c/jb67g/POKmkAqnJMFPXY45tT0/FrHX
hVK3rsSXQBwxy9/qzzPN+nBF7VlgvSoVzrF384t5Slf2ehwYTw3sgJoUudZ4c12kyE+uLdrOVl3Q
BHKDLfy1hRgxMQS/c3uNKkSgXAH3lk9SqMZ9dBzUoY2hZ45YogsP0dQDvzs3AQEdhGW0ZoGEQjC/
QcTTvp7lg/M9gRoBUp/DegGjf2p0N1OlPhj4m63Q2XEm65AvOkA5xxs5RTZKgcU28BJjkgEUpVNt
1rnp0sBsMABmtZ4FXP1YNcKCBdNkIYw67DOO5MRfAGqaDqosT3CL9EOGna61KLQEmtOS33NAx49y
ZtCeh/N91jnC+AMjjhhqwzRtrXJ6g/MLxEmmIFvNYcEipeYHfPynhuVywVVH/tj0SqmnDP4cQd4t
HvFQL5frBq963Wl0ToPVAC+koMvsplAr0dvJLVfNceIwggL5BgkqhkiG9w0BBwGgggLqBIIC5jCC
AuIwggLeBgsqhkiG9w0BDAoBAqCCAqYwggKiMBwGCiqGSIb3DQEMAQMwDgQINLkrmjjeasQCAggA
BIICgIc2PtM3mraGPkm8MqvJOEj64fTocAnAHzGVJ8BhwBXkQI++2d9eAGlSB7pO0JioT7uMBwCL
i3zVQ6bvDw2tbgVD3Pmc/qY0TpIySptODk6X1Y9fI1Bwrvgi+6cx7PIdFUrypnL/djNTtVIkIfFk
TO48YTlT6Gsn+z2Pe6asI0PSDoLgmw2yPauN7Xz1KkAg0KHDT+vMlSLaAYWF8k3+/jFNgPVUpaMM
t/DzuJti0R5+eVnpAPkMTJhncumvMdBYzg2Wx0URHzU4+24hSXE8/xMBN3pVsj11T7Eu5jPazIKR
qB5a5dn/ICVx/JHzz5dFonHilIvyiMfNE7VKTTerisEhCSdUgqq+sIhlPAlLTBCoyUgcGiCi7dKW
GAT47PJ4rvJsGHSUcaNORF71W1GqQQ5iTsJK5rPmGpMUmGwjsemmWmgp00BeMtmqO19B1yRrjDZO
atDYISR3UkmeI0A9VlXAspZ2ngmbuWvW0M8nrzwvDLIfgJ8rsFwexIVecFO58j2YSKBmVEykUvSd
x+PH3gr8IWAd/Ct0VNLF1Jk2ktOXx1pnM9GWUl8rbvTvM5lNevArHpWp+7vY6JlkM+trdaSE66Lr
cvvI+faKAnj4QtkmkbKPF0qLFsDssFv7AI0l7/65PhRZwJ12WpZEOKsqkUyAUbQI16Cva6cuY38y
XZ++x67rU4ldumq0YKOJPdPbAtptwMdCn7lepDaxT8mwv4SIZSd37hAP8UNvmRdRWL4dYx3m8Y+l
4hnClZt+GbKmMgXu/o4ua37kOlCV1T0VqmuRzpOwnct8HBvtVS6TuScExeiEkNBA4KwSIY04ZSm+
Sell3vQywF3jry7v/FMgPhoxJTAjBgkqhkiG9w0BCRUxFgQU+7ZMLd/K3gq6I9wxj3LcCb2tf5Uw
MTAhMAkGBSsOAwIaBQAEFOM/amdwLHU0WBmyCw96Za0+5Z+PBAgvp7LF+Qwu+AICCAA=";

            var x509Cert = new X509Certificate2(Convert.FromBase64String(sPfx));
#else
            const string sPrivateKey = @"
-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALQoMIfUT93VMvb5
4U5dsJLXD1D6z4o/VuVlNUaf5xH01qAv8Egpxe6f5frLB/p1eNyDjNIZ3QitD6aN
9Vfh4ifg6txBuBJtIMfSDvRJITNZ2SjKJREbflZuBk0HINKYQk2H+3TIzUbE/pN4
Cu6Mids5L/oVOnRWIe3bEC+PHR7ZAgMBAAECgYBI1qrwb+2ukeFeK59lcMnQRLVD
l3RLv9ohOy80E7h38RbJgzhR5NnK5ck1AduC7vXjqihIVf6g4F+ghmq4knI94KPQ
2fOyQGVV6jVeRVqMusx7tP9V1H26yABiK6TPklcCsWwADFmexfOxfIgbBGSmlbAd
N2/ad1Xog1xDebrbEQJBAO+2qSIDX1ahfxUyvvcMaix6Mrh/OYKb5aH1Y/7MfAav
lpbQavQHNvak2147aPNxy0ZvWdJ2HVA7hUMkgysYWSUCQQDAZalkZMSrve+Onh55
U+w5xjLklhh8PhYxx8plT8ae9VG75dGvWSz/W81B3ILg2lrNU6o08NKBJdZsJYmc
BeKlAkBtJh3zF9gEaTqlW1rqwKNjpyyLJ5r3JqczzLmAXnmmzbLi7vmULejP+5bL
XH/YQZtOcgtTMmb8jm2Kegijyc1lAkANGt+e5v4+dIGMxVhuCzlb9hQhXdftHo2E
dodivzxYN32Jvu25c+mMu0QP6GVBy53Dvp8pW/36rgkc9LGa3wvBAkEA7dGAl95T
UeNFVfuzkYNtQppcSgrx1oTcpTHoNgcvk8AgBf4yDdJJyo0IUONmgJCVffc1aTWn
nf/8cW9YC+0icQ==
-----END PRIVATE KEY-----";
            const string sCert       = @"
MIICNDCCAZ2gAwIBAgIJAKl3qU1+NsuuMA0GCSqGSIb3DQEBCwUAMDMxCzAJBgNV
BAYTAkdCMRMwEQYDVQQIDApTb21lLVN0YXRlMQ8wDQYDVQQKDAZHb29nbGUwHhcN
MTYwODEwMTQwOTQ2WhcNNDMxMjI3MTQwOTQ2WjAzMQswCQYDVQQGEwJHQjETMBEG
A1UECAwKU29tZS1TdGF0ZTEPMA0GA1UECgwGR29vZ2xlMIGfMA0GCSqGSIb3DQEB
AQUAA4GNADCBiQKBgQC0KDCH1E/d1TL2+eFOXbCS1w9Q+s+KP1blZTVGn+cR9Nag
L/BIKcXun+X6ywf6dXjcg4zSGd0IrQ+mjfVX4eIn4OrcQbgSbSDH0g70SSEzWdko
yiURG35WbgZNByDSmEJNh/t0yM1GxP6TeArujInbOS/6FTp0ViHt2xAvjx0e2QID
AQABo1AwTjAdBgNVHQ4EFgQUMqzJi099PA8ML5CV1OSiHgiTGoUwHwYDVR0jBBgw
FoAUMqzJi099PA8ML5CV1OSiHgiTGoUwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B
AQsFAAOBgQBQ9cMInb2rEcg8TTYq8MjDEegHWLUI9Dq/IvP/FHyKDczza4eX8m+G
3buutN74pX2/GHRgqvqEvvUUuAQUnZ36k6KjTNxfzNLiSXDPNeYmy6PWsUZy4Rye
/Van/ePiXdipTKMiUyl7V6dTjkE5p/e372wNVXUpcxOMmYdWmzSMvg==";

            var           x509Cert      = new X509Certificate2(Convert.FromBase64String(sCert));
            RSAParameters rsaParameters = Pkcs8.DecodeRsaParameters(sPrivateKey);
            var           privateKey    = new System.Security.Cryptography.RSACryptoServiceProvider();
            privateKey.ImportParameters(rsaParameters);
            x509Cert.PrivateKey = privateKey;
#endif
            Assert.That(x509Cert.HasPrivateKey);

            var initializer = new ServiceAccountCredential.Initializer("some-id")
            {
                Clock = new MockClock {
                    UtcNow = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                }
            };
            var cred = new ServiceAccountCredential(initializer.FromCertificate(x509Cert));

            Assert.That(cred.Scopes?.Any(), Is.False); // HasScopes must be false for the type of access token we want to test.

            string accessToken = await cred.GetAccessTokenForRequestAsync("http://authurl/");

            string expectedToken =
                "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzb21lLWlkIiwic3ViIjoi" +
                "c29tZS1pZCIsImF1ZCI6Imh0dHA6Ly9hdXRodXJsLyIsImV4cCI6MTQ1MTYxMDAwMCwia" +
                "WF0IjoxNDUxNjA2NDAwfQ.GfpDHgrFi4ZlGC5LuJEarLU4_eTrT5PVa-S40YtkdB2E1f3" +
                "4naYG2ItcfBEFg7Gbdkr1cIAyipuhEd2yLfPmWGwhOwVcBRNyK_J5w8RodS44mxNJwau0" +
                "jKy4x1K20ybLqcnNgzE0wag6fi5GHwdNIB0URdHDTiC88CRYdl1CIdk";
            Assert.That(accessToken, Is.EqualTo(expectedToken));
        }
Пример #48
0
 public X509AsymmetricSignatureProvider(System.Security.Cryptography.RSACryptoServiceProvider rsa)
 {
     this.Initialize(rsa);
 }
Пример #49
0
 /// <summary>
 /// 随机生成密钥对
 /// </summary>
 public void Reset(int keySize)
 {
     this.rsa = new RSACryptoServiceProvider(keySize);
 }
Пример #50
0
        public static void VerifySig(XmlDocument sigDoc)
        {
            try
            {
                XmlElement envelope = sigDoc.DocumentElement;

                XmlElement securityElem = LameXpath.SelectSingleNode(sigDoc, Elem.Security);
                if (securityElem != null)
                {
                    XmlAttribute mustUndAtt = securityElem.Attributes[Attrib.mustUnderstand, Ns.soap];
                    if (mustUndAtt != null)
                    {
                        mustUndAtt.Value = "0";
                    }
                }

                XmlElement sigElem = LameXpath.SelectSingleNode(sigDoc, Elem.Signature);
                if (sigElem == null)
                {
                    return;
                }

                XmlElement sigValElem = LameXpath.SelectSingleNode(sigElem, Elem.SignatureValue);
                byte[]     baSigVal   = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(sigValElem.InnerText);

                bool comments  = false;
                bool exclusive = true;
                System.Security.Cryptography.SHA1CryptoServiceProvider shaCsp = new System.Security.Cryptography.SHA1CryptoServiceProvider();

                XmlElement sigMethElem = LameXpath.SelectSingleNode(sigElem, Elem.SignatureMethod);
                string     segMeth     = sigMethElem.Attributes["Algorithm"].Value;

                XmlElement  signedInfoElem = LameXpath.SelectSingleNode(sigElem, Elem.SignedInfo);
                XmlDocument xdSignedInfo   = new XmlDocument();
                xdSignedInfo.LoadXml(signedInfoElem.OuterXml);
                XmlCanonicalizer xc   = new XmlCanonicalizer(comments, exclusive);
                MemoryStream     ms   = (MemoryStream)xc.Canonicalize(xdSignedInfo);
                byte []          baMs = new byte[ms.Length];
                ms.Read(baMs, 0, baMs.Length);

                ArrayList  keyInfoRefElem = LameXpath.SelectChildNodes(sigElem, Elem.SecurityTokenReference, Elem.Reference);
                XmlElement keyInfoRef     = (XmlElement)keyInfoRefElem[0];
                string     secTokUri      = keyInfoRef.Attributes["URI"].Value;
                secTokUri = secTokUri.TrimStart(new char[] { '#' });
                XmlElement secTokElem = LameXpath.SelectSingleNode(secTokUri, sigDoc);

                if (secTokElem.LocalName == Elem.UsernameToken)
                {
                    XmlElement nonce   = LameXpath.SelectSingleNode(secTokElem, Elem.Nonce);
                    XmlElement created = LameXpath.SelectSingleNode(secTokElem, Elem.Created);
                    //DerivedKeyGenerator seems to be off by 1?
                    //byte [] baKey = P_SHA1.DeriveKey(ClearPassword, StrKeyLabel, nonce.InnerText, created.InnerText, NumKeyBytes);
                    byte []  baKey   = P_SHA1.DeriveKey(SigObj.ClearPassword, StrKeyLabel, nonce.InnerText, created.InnerText, NumKeyBytes);
                    HMACSHA1 hmacSha = new HMACSHA1(baKey);
                    byte []  baSig   = hmacSha.ComputeHash(baMs);
                    OpenNETCF.Security.Cryptography.Internal.Format.SameBytes(baSigVal, baSig);
                }
                else if (secTokElem.LocalName == Elem.BinarySecurityToken)
                {
                    byte[]          baCert = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(secTokElem.InnerText);
                    X509Certificate cert   = new X509Certificate(baCert);                   //pub key to verify sig.
                    byte []         exponent;
                    byte []         modulus;
                    DecodeCertKey.GetPublicRsaParams(cert, out exponent, out modulus);
                    System.Security.Cryptography.RSAParameters rsaParam = new System.Security.Cryptography.RSAParameters();
                    rsaParam.Exponent = exponent;
                    rsaParam.Modulus  = modulus;
                    System.Security.Cryptography.RSACryptoServiceProvider rsaCsp = new System.Security.Cryptography.RSACryptoServiceProvider();
                    rsaCsp.ImportParameters(rsaParam);

                    byte [] baUnsigHash = shaCsp.ComputeHash(baMs);
                    bool    valid       = rsaCsp.VerifyHash(baUnsigHash, "SHA", baSigVal);
                    if (valid == false)
                    {
                        throw new Exception("signature is not valid");
                    }
                }
                else if (secTokElem.LocalName == Elem.SecurityContextToken)
                {
                    //TODO how to validate signature?
                }
                else
                {
                    throw new Exception("only support Username, BinarySecurity, and SecurityContext Token signature");
                }

                //verify reference hashes
                string    refdName = String.Empty;
                ArrayList refNodes = LameXpath.SelectChildNodes(sigDoc, Elem.SignedInfo, Elem.Reference);
                foreach (object oXn in refNodes)
                {
                    XmlNode xn    = (XmlNode)oXn;
                    string  uriId = xn.Attributes[Attrib.URI].Value;
                    uriId = uriId.TrimStart(new char[] { '#' });
                    XmlElement digValElem = LameXpath.SelectSingleNode(xn, Elem.DigestValue);
                    byte[]     baDigest   = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(digValElem.InnerText);

                    XmlElement  refdElem   = LameXpath.SelectSingleNode(uriId, sigDoc);
                    XmlDocument xdRefdElem = new XmlDocument();
                    refdName = refdElem.LocalName;                     //for debug visibility
                    xdRefdElem.LoadXml(refdElem.OuterXml);
                    //not reusable
                    xc = new XmlCanonicalizer(comments, exclusive);
                    //MemoryStream ms = (MemoryStream) xc.Canonicalize(refdElem);
                    ms   = (MemoryStream)xc.Canonicalize(xdRefdElem);
                    baMs = new byte[ms.Length];
                    ms.Read(baMs, 0, baMs.Length);
                    byte [] baHash = shaCsp.ComputeHash(baMs);
                    try
                    {
                        OpenNETCF.Security.Cryptography.Internal.Format.SameBytes(baDigest, baHash);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(refdName + ":" + ex.Message, ex);
                    }
                }
            }
            finally
            {
                //ClearPassword = null;
                SigObj = null;
            }
        }
Пример #51
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);
    }
Пример #52
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));
            }
        }
Пример #53
0
        internal static bool Pkcs1VerifyData(RSA rsa, byte[] data, byte[] signature, string hashAlgorithmName)
        {
            // Because RSACryptoServiceProvider existed in 4.5, but RSACng didn't, and RSA's SignData
            // method requires types that aren't in 4.5, try RSACryptoServiceProvider's way first.
            RSACryptoServiceProvider rsaCsp = rsa as RSACryptoServiceProvider;

            if (rsaCsp != null)
            {
                return(rsaCsp.VerifyData(data, hashAlgorithmName, signature));
            }

            if (s_rsaPkcs1VerifyMethod == null)
            {
                // [X] VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding)
                // [ ] VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding)
                // [ ] VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithmName, RSASignaturePadding padding)

                Debug.Assert(s_hashAlgorithmNameType != null);
                Debug.Assert(s_rsaSignaturePaddingType != null);
                Debug.Assert(s_pkcs1SignaturePadding != null);
                Type[] signatureTypes = { typeof(byte[]), typeof(byte[]), s_hashAlgorithmNameType, s_rsaSignaturePaddingType };

                MethodInfo verifyDataMethod = typeof(RSA).GetMethod(
                    "VerifyData",
                    BindingFlags.Public | BindingFlags.Instance,
                    null,
                    signatureTypes,
                    null);

                Debug.Assert(
                    verifyDataMethod != null,
                    "Cannot find RSA.VerifyData(byte[], byte[], HashAlgorithmName, RSASignaturePadding)");

                // Because the HashAlgorithmName and RSASignaturePadding types aren't guaranteed available at
                // assembly time (though they really need to be if the runtime makes it here...) the delegate binding
                // is a bit harder than normal.
                Type delegateType = typeof(Func <, , , , ,>).MakeGenericType(
                    typeof(RSA),
                    typeof(byte[]),
                    typeof(byte[]),
                    s_hashAlgorithmNameType,
                    s_rsaSignaturePaddingType,
                    typeof(bool));

                Delegate openDelegate = Delegate.CreateDelegate(delegateType, verifyDataMethod);

                s_rsaPkcs1VerifyMethod =
                    (delegateRsa, delegateData, delegateSignature, delegateAlgorithm) =>
                {
                    object hashAlgorithmNameObject = Activator.CreateInstance(s_hashAlgorithmNameType, delegateAlgorithm);

                    object[] args =
                    {
                        delegateRsa,
                        delegateData,
                        delegateSignature,
                        hashAlgorithmNameObject,
                        s_pkcs1SignaturePadding
                    };

                    return((bool)openDelegate.DynamicInvoke(args));
                };
            }

            Debug.Assert(s_rsaPkcs1VerifyMethod != null);
            return(s_rsaPkcs1VerifyMethod(rsa, data, signature, hashAlgorithmName));
        }
Пример #54
0
        private static System.Security.Cryptography.RSACryptoServiceProvider DecodePrivateKeyInfo(byte[] pkcs8)
        {
            byte[] b = new byte[]
            {
                48,
                13,
                6,
                9,
                42,
                134,
                72,
                134,
                247,
                13,
                1,
                1,
                1,
                5,
                0
            };
            byte[] a = new byte[15];
            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(pkcs8);
            int num = (int)memoryStream.Length;

            System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(memoryStream);
            System.Security.Cryptography.RSACryptoServiceProvider result;
            try
            {
                ushort num2 = binaryReader.ReadUInt16();
                if (num2 == 33072)
                {
                    binaryReader.ReadByte();
                }
                else
                {
                    if (num2 != 33328)
                    {
                        result = null;
                        return(result);
                    }
                    binaryReader.ReadInt16();
                }
                byte b2 = binaryReader.ReadByte();
                if (b2 != 2)
                {
                    result = null;
                }
                else
                {
                    num2 = binaryReader.ReadUInt16();
                    if (num2 != 1)
                    {
                        result = null;
                    }
                    else
                    {
                        a = binaryReader.ReadBytes(15);
                        if (!RSAFromPkcs8.CompareBytearrays(a, b))
                        {
                            result = null;
                        }
                        else
                        {
                            b2 = binaryReader.ReadByte();
                            if (b2 != 4)
                            {
                                result = null;
                            }
                            else
                            {
                                b2 = binaryReader.ReadByte();
                                if (b2 == 129)
                                {
                                    binaryReader.ReadByte();
                                }
                                else
                                {
                                    if (b2 == 130)
                                    {
                                        binaryReader.ReadUInt16();
                                    }
                                }
                                byte[] privkey = binaryReader.ReadBytes((int)((long)num - memoryStream.Position));
                                System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = RSAFromPkcs8.DecodeRSAPrivateKey(privkey);
                                result = rSACryptoServiceProvider;
                            }
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                result = null;
            }
            finally
            {
                binaryReader.Close();
            }
            return(result);
        }
Пример #55
0
 private static byte[] decrypt(byte[] data, string privateKey, string input_charset)
 {
     System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = RSAFromPkcs8.DecodePemPrivateKey(privateKey);
     new System.Security.Cryptography.SHA1CryptoServiceProvider();
     return(rSACryptoServiceProvider.Decrypt(data, false));
 }
Пример #56
0
            /// <summary>
            /// RSAPkcs8Util
            /// </summary>
            /// <param name="dataEncoding"></param>
            /// <param name="publicKey"></param>
            /// <param name="privateKey"></param>
            /// <param name="keySize"></param>
            public RsaPkcs8Util(Encoding dataEncoding, string publicKey, string privateKey = null, int keySize = 2048)
            {
                if (string.IsNullOrEmpty(privateKey) && string.IsNullOrEmpty(publicKey))
                {
                    throw new Exception("Public and private keys must not be empty at the same time");
                }

                if (!string.IsNullOrEmpty(privateKey))
                {
#if NET451 || NET452
                    PrivateRsa = new MsRSA {
                        KeySize = keySize
                    };
#else
                    PrivateRsa         = MsRSA.Create();
                    PrivateRsa.KeySize = keySize;
#endif
                    PrivateRsa.TouchFromPrivateKeyInPkcs8(privateKey, out var priRsap);

#if NET451 || NET452
                    PrivateRsaKeyParameter = GetPrivateKeyParameter(privateKey);
#endif

                    if (string.IsNullOrEmpty(publicKey))
                    {
#if NET451 || NET452
                        PublicRsa = new MsRSA {
                            KeySize = keySize
                        };
#else
                        PublicRsa         = MsRSA.Create();
                        PublicRsa.KeySize = keySize;
#endif
                        var pubRsap = new RSAParameters
                        {
                            Modulus  = priRsap.Modulus,
                            Exponent = priRsap.Exponent
                        };
                        PublicRsa.ImportParameters(pubRsap);

#if NET451 || NET452
                        PublicRsaKeyParameter = GetPublicKeyParameter(publicKey);
#endif
                    }
                }

                if (!string.IsNullOrEmpty(publicKey))
                {
#if NET451 || NET452
                    PublicRsa = new MsRSA {
                        KeySize = keySize
                    };
#else
                    PublicRsa         = MsRSA.Create();
                    PublicRsa.KeySize = keySize;
#endif
                    PublicRsa.TouchFromPublicKeyInPkcs8(publicKey, out _);

#if NET451 || NET452
                    PublicRsaKeyParameter = GetPublicKeyParameter(publicKey);
#endif
                }

                DataEncoding = dataEncoding.SafeEncodingValue();
            }
Пример #57
0
        static void Main()
        {
            //lets take a new CSP with a new 2048 bit rsa key pair
            var csp = new System.Security.Cryptography.RSACryptoServiceProvider(2048);

            //how to get the private key
            var privKey = csp.ExportParameters(true);

            //and the public key ...
            var pubKey = csp.ExportParameters(false);

            //converting the public key into a string representation
            string pubKeyString = "";

            {
                //we need some buffer
                var sw = new System.IO.StringWriter();
                //we need a serializer
                var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                //serialize the key into the stream
                xs.Serialize(sw, pubKey);
                //get the string from the stream
                pubKeyString = sw.ToString();
            }

            //converting it back
            {
                //get a stream from the string
                var sr = new System.IO.StringReader(pubKeyString);
                //we need a deserializer
                var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                //get the object back from the stream
                pubKey = (RSAParameters)xs.Deserialize(sr);
            }

            //conversion for the private key is no black magic either ... omitted

            //we have a public key ... let's get a new csp and load that key
            csp = new RSACryptoServiceProvider();
            csp.ImportParameters(pubKey);

            //we need some data to encrypt
            var plainTextData = "foobar";

            //for encryption, always handle bytes...
            var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData);

            //apply pkcs#1.5 padding and encrypt our data
            var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);

            //we might want a string representation of our cypher text... base64 will do
            var cypherText = Convert.ToBase64String(bytesCypherText);


            /*
             * some transmission / storage / retrieval
             *
             * and we want to decrypt our cypherText
             */

            //first, get our bytes back from the base64 string ...
            bytesCypherText = Convert.FromBase64String(cypherText);

            //we want to decrypt, therefore we need a csp and load our private key
            csp = new RSACryptoServiceProvider();
            csp.ImportParameters(privKey);

            //decrypt and strip pkcs#1.5 padding
            bytesPlainTextData = csp.Decrypt(bytesCypherText, false);

            //get our original plainText back...
            plainTextData = System.Text.Encoding.Unicode.GetString(bytesPlainTextData);
        }
Пример #58
0
        public async void StartMQTT(string clientid, string cafile, string clientcertfile, string clientprivate, string clientprivatepassword = "")
        {
            var ca = new X509Certificate(cafile, "");

            var reader     = new PemReader(File.OpenText(clientprivate));
            var privatekey = (AsymmetricCipherKeyPair)reader.ReadObject();
            var pkinfo     = (Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)privatekey.Private;

            var ce1 = new X509Certificate2(File.ReadAllBytes(clientcertfile), clientprivatepassword,
                                           X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            CspParameters parms = new CspParameters();

            parms.Flags            = CspProviderFlags.NoFlags;
            parms.KeyContainerName = Guid.NewGuid().ToString().ToUpperInvariant();
            parms.ProviderType     = ((Environment.OSVersion.Version.Major > 5) || ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1))) ? 0x18 : 1;

            System.Security.Cryptography.RSACryptoServiceProvider rcsp =
                new System.Security.Cryptography.RSACryptoServiceProvider(parms)
            {
                PersistKeyInCsp = true
            };

            rcsp.ImportParameters(DotNetUtilities.ToRSAParameters(pkinfo));
            ce1.PrivateKey = rcsp;

            //var clientcert = CertificatesToDBandBack.Certificate.GetCertificateFromPEMstring(File.ReadAllText(clientcertfile), File.ReadAllText(clientprivate), clientprivatepassword);

            MQTTClient = new MqttFactory().CreateMqttClient();
            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer(mqtt_host, mqtt_port).WithClientId(clientid).WithTls(new MqttClientOptionsBuilderTlsParameters
            {
                AllowUntrustedCertificates        = false,
                IgnoreCertificateChainErrors      = false,
                IgnoreCertificateRevocationErrors = false,
                UseTls       = true,
                SslProtocol  = System.Security.Authentication.SslProtocols.Tls12,
                Certificates = new List <byte[]>
                {
                    ca.Export(X509ContentType.SerializedCert),
                    ce1.Export(X509ContentType.SerializedCert)
                },
                CertificateValidationCallback = (X509Certificate x, X509Chain y, SslPolicyErrors z, IMqttClientOptions o) =>
                {
                    return(true);
                }
            }).Build();

            MQTTClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();
            });
            MQTTClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(async a =>
            {
                Console.WriteLine("### CONNECTED WITH SERVER ###");
                await MQTTClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build());
            });
            MQTTClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async a =>
            {
                Console.WriteLine("### DISCONNECTED FROM SERVER ###");
            });

            var connect = await MQTTClient.ConnectAsync(options);

            var sub = MQTTClient.SubscribeAsync(new TopicFilter
            {
                Topic = "test", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce
            });
        }
Пример #59
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);
        }
Пример #60
-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);
 }