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

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

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

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

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

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

                using(var ms = new MemoryStream())
                using(var xw = XmlWriter.Create(ms, new XmlWriterSettings
                                                    {
                                                        Indent = true,
                                                        Encoding = Encoding.UTF8
                                                    })) {
                    doc.Save(xw);
                    ms.Position = 0;
                    return new StreamReader(ms).ReadToEnd();
                }
            }
        }
Example #11
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;
 }
		/// <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;
		}
Example #13
0
 protected override void OnConnect()
 {
     base.OnConnect();
     m_rsa = new RSACryptoServiceProvider();
     RSAParameters para = m_rsa.ExportParameters(false);
     SendRSAKey(para.Modulus, para.Exponent);
 }
Example #14
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;
        }
Example #15
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);
     }
 }
        //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;
        }
Example #17
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();
        }
Example #18
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();
            }
        }
Example #20
0
        public static bool CompareCode(string regcode)
        {
            if (regcode == null || regcode == "")
            {
                return false;
            }
            try
            {
                string toolcode = GetDiskVolumeSerialNumber() + GetCpuSerialNumber();
                string pubkey = "<RSAKeyValue><Modulus>xe3teTUwLgmbiwFJwWEQnshhKxgcasglGsfNVFTk0hdqKc9i7wb+gG7HOdPZLh65QyBcFfzdlrawwVkiPEL5kNTX1q3JW5J49mTVZqWd3w49reaLd8StHRYJdyGAL4ZovBhSTThETi+zYvgQ5SvCGkM6/xXOz+lkMaEgeFcjQQs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
                string prikey = "<RSAKeyValue><Modulus>xe3teTUwLgmbiwFJwWEQnshhKxgcasglGsfNVFTk0hdqKc9i7wb+gG7HOdPZLh65QyBcFfzdlrawwVkiPEL5kNTX1q3JW5J49mTVZqWd3w49reaLd8StHRYJdyGAL4ZovBhSTThETi+zYvgQ5SvCGkM6/xXOz+lkMaEgeFcjQQs=</Modulus><Exponent>AQAB</Exponent><P>5flMAd7IrUTx92yomBdJBPDzp1Kclpaw4uXB1Ht+YXqwLW/9icI6mcv7d2O0kuVLSWj8DPZJol9V8AtvHkC3oQ==</P><Q>3FRA9UWcFrVPvGR5bewcL7YqkCMZlybV/t6nCH+gyMfbEvgk+p04F+j8WiHDykWj+BahjScjwyF5SGADbrfJKw==</Q><DP>b4WOU1XbERNfF3JM67xW/5ttPNX185zN2Ko8bbMZXWImr1IgrD5RNqXRo1rphVbGRKoxmIOSv7flr8uLrisKIQ==</DP><DQ>otSZlSq2qomgvgg7PaOLSS+F0TQ/i1emO0/tffhkqT4ah7BgE97xP6puJWZivjAteAGxrxHH+kPY0EY1AzRMNQ==</DQ><InverseQ>Sxyz0fEf5m7GrzAngLDRP/i+QDikJFfM6qPyr3Ub6Y5RRsFbeOWY1tX3jmV31zv4cgJ6donH7W2dSBPi67sSsw==</InverseQ><D>nVqofsIgSZltxTcC8fA/DFz1kxMaFHKFvSK3RKIxQC1JQ3ASkUEYN/baAElB0f6u/oTNcNWVPOqE31IDe7ErQelVc4D26RgFd5V7dSsF3nVz00s4mq1qUBnCBLPIrdb0rcQZ8FUQTsd96qW8Foave4tm8vspbM65iVUBBVdSYYE=</D></RSAKeyValue>";

                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {

                    rsa.FromXmlString(pubkey);

                    RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsa);

                    f.SetHashAlgorithm("SHA1");

                    SHA1Managed sha = new SHA1Managed();

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

                    return f.VerifySignature(name, key);
                }
            }
            catch
            {
                return false;
            }
        }
Example #21
0
 public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
 {
     RSACryptoServiceProvider provider1 = new RSACryptoServiceProvider();
     provider1.FromXmlString(xmlPrivateKey);
     byte[] buffer1 = provider1.Decrypt(DecryptString, false);
     return new UnicodeEncoding().GetString(buffer1);
 }
Example #22
0
        public string Calculate(string input, RSACryptoServiceProvider provider)
        {
            byte[] podatki = Encoding.ASCII.GetBytes(input);
              byte[] signature = provider.SignData(podatki, CryptoConfig.MapNameToOID("SHA256"));

              return this.CalculateMD5Hash(signature);
        }
Example #23
0
        public static void EncryptSomeText()
        {
            //Init keys
            GeneratePublicAndPrivateKeys();

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

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

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

            string decryptedString = ByteConverter.GetString(decryptedData);
            Console.WriteLine(decryptedString);
        }
Example #24
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 static string Encrypt(string data)
        {
            try
               {
            var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(_publicKey);
            var dataToEncrypt = _encoder.GetBytes(data);
            var encryptedByteArray = rsa.Encrypt(dataToEncrypt, false).ToArray();
            var length = encryptedByteArray.Count();
            var item = 0;
            var sb = new StringBuilder();
            foreach (var x in encryptedByteArray)
            {
             item++;
             sb.Append(x);

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

            return sb.ToString();

               }
               catch (Exception)
               {
            throw new RSAException();
               }
        }
Example #26
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;
            }

        }
Example #27
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();
        }
Example #28
0
        public static string Text_Decryption(string text, int bits, string encryption_key)
        {
            string result = String.Empty;
            ArrayList list = new ArrayList();

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

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

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

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

            return result;
        }
Example #29
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 = "me",
                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");
        }
Example #30
-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);
 }