Ejemplo n.º 1
1
        static async Task MainAsync(string[] args)
        {
            var keyClient = new KeyVaultClient((authority, resource, scope) =>
            {
                var adCredential = new ClientCredential(applicationId, applicationSecret);
                var authenticationContext = new AuthenticationContext(authority, null);
                return authenticationContext.AcquireToken(resource, adCredential).AccessToken;
            });

            // Get the key details
            var keyIdentifier = "https://testvaultrahul.vault.azure.net/keys/rahulkey/0f653b06c1d94159bc7090596bbf7784";
            var key = await keyClient.GetKeyAsync(keyIdentifier);
            var publicKey = Convert.ToBase64String(key.Key.N);

            using (var rsa = new RSACryptoServiceProvider())
            {
                var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E };
                rsa.ImportParameters(p);
                var byteData = Encoding.Unicode.GetBytes(textToEncrypt);
                
                // Encrypt and Decrypt
                var encryptedText = rsa.Encrypt(byteData, true);
                var decryptedData = await keyClient.DecryptDataAsync(keyIdentifier, "RSA_OAEP", encryptedText);
                var decryptedText = Encoding.Unicode.GetString(decryptedData.Result);

                // Sign and Verify
                var hasher = new SHA256CryptoServiceProvider();
                var digest = hasher.ComputeHash(byteData);
                var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest);
                var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result);
            }
        }
		public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                byte[] decryptedData;
                //Create a new instance of RSACryptoServiceProvider.
                //using ()
                {
                    //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;
            }
        }
    /// <summary> Send a packet to endpoint </summary>
    /// <param name="action">Packet ID</param>
    /// <param name="packetData">Packet content</param>
    /// <param name="udp">UDP Enabled</param>
    /// <param name="useEncrypt">Use RSA/SHA256 encryption</param>
    public static void SendPacket(ClientPacket action, Dictionary <string, object> packetData, bool udp = false, bool useEncrypt = true)
    {
        string clientHash = Client.instance.loginHash;

        System.Security.Cryptography.RSAParameters clientKey = Client.instance.serverKey;

        using (Packet packet = new Packet((int)ClientPackets.welcomeReceived))
        {
            // SEND: Encryption enabled / packet ID.
            packet.Write(useEncrypt);
            packet.Write(action.ToString());

            // SEND: Data count & data converted in string format.
            packet.Write(packetData.Count());
            foreach (KeyValuePair <string, object> pair in packetData)
            {
                string packet_line = string.Join("|", new string[3] {
                    pair.Key, ParseSendObject(pair.Value), pair.Value.GetType().ToString()
                });
                Debug.Log(packet_line);
                packet.Write(!useEncrypt ? packet_line : Cryptograph.Encrypt(clientKey, Cryptograph.SHA256Encrypt(packet_line, clientHash)));
            }

            // SEND: With UDP style traffic if boolean "udp" is true, otherwise TCP.
            if (udp)
            {
                SendUDPData(packet);
            }
            else
            {
                SendTCPData(packet);
            }
        }
    }
		/// <summary>
		/// Constructs a new <see cref="RsaJsonWebKey"/> instance
		/// </summary>
		/// <param name="id">The key id (kid)</param>
		/// <param name="expiresAt">When the key expires</param>
		/// <param name="rsaParameters">The parameters needed to by the RSA algorithm</param>
		public RsaJsonWebKey(
			Guid id,
			DateTime expiresAt,
			RSAParameters rsaParameters
		) : base( id, expiresAt ) {
			m_parameters = rsaParameters;
		}
        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
        }
Ejemplo n.º 6
0
        private void Init()
        {
            string KeyFile = TAppSettingsManager.GetValue("Server.ChannelEncryption.PrivateKeyfile");

            // read the encryption key from the specified file
            FileInfo fi = new FileInfo(KeyFile);

            if (!fi.Exists)
            {
                throw new RemotingException(
                    String.Format("Specified keyfile {0} does not exist", KeyFile));
            }

            XmlDocument doc = new XmlDocument();
            doc.Load(KeyFile);

            FPrivateKey = new RSAParameters();

            try
            {
                FPrivateKey.D = Convert.FromBase64String(TXMLParser.GetChild(doc.FirstChild, "D").InnerText);
                FPrivateKey.P = Convert.FromBase64String(TXMLParser.GetChild(doc.FirstChild, "P").InnerText);
                FPrivateKey.Q = Convert.FromBase64String(TXMLParser.GetChild(doc.FirstChild, "Q").InnerText);
                FPrivateKey.DP = Convert.FromBase64String(TXMLParser.GetChild(doc.FirstChild, "DP").InnerText);
                FPrivateKey.DQ = Convert.FromBase64String(TXMLParser.GetChild(doc.FirstChild, "DQ").InnerText);
                FPrivateKey.InverseQ = Convert.FromBase64String(TXMLParser.GetChild(doc.FirstChild, "InverseQ").InnerText);
                FPrivateKey.Modulus = Convert.FromBase64String(TXMLParser.GetChild(doc.FirstChild, "Modulus").InnerText);
                FPrivateKey.Exponent = Convert.FromBase64String(TXMLParser.GetChild(doc.FirstChild, "Exponent").InnerText);
            }
            catch (Exception)
            {
                throw new RemotingException(
                    String.Format("Problems reading the keyfile {0}. Cannot find all attributes of the key.", KeyFile));
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Decrypts a byte array (previously encrypted with the Encrypt method)
 /// </summary>
 /// <param name="cipher">The encrypted byte array</param>
 /// <param name="privateKey">The private key used to decrypt the data</param>
 /// <returns>A byte array containing the decrypted value</returns>
 public byte[] Decrypt(byte[] cipher, System.Security.Cryptography.RSAParameters privateKey)
 {
     byte[] result = null;
     try
     {
         _rsa.ImportParameters(privateKey);
         int base64BlockSize = (256 % 3 != 0) ? ((256 / 3) * 4) + 4 : (256 / 3) * 4;
         int iterations      = cipher.Length / base64BlockSize;
         int l         = 0;
         var fullbytes = new byte[0];
         var encBytes  = new byte[base64BlockSize];// {} cipher.Substring(base64BlockSize * i, base64BlockSize));
         for (int i = 0; i < iterations; i++)
         {
             Array.Copy(cipher, base64BlockSize * i, encBytes, 0, base64BlockSize);
             byte[] bytes = _rsa.Decrypt(encBytes, System.Security.Cryptography.RSAEncryptionPadding.Pkcs1);
             Array.Resize(ref fullbytes, fullbytes.Length + bytes.Length);
             foreach (byte t in bytes)
             {
                 fullbytes[l] = t;
                 l++;
             }
         }
         result = fullbytes;// Encoding.UTF32.GetString(fullbytes);
     }
     catch (Exception e)
     {
         Log.e(e);
     }
     return(result);
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Decrypts a string (previously encrypted with the Encrypt method)
        /// </summary>
        /// <param name="base64String">The encrypted string</param>
        /// <param name="privateKey">The private key used to decrypt the string</param>
        /// <returns>A string containing the decrypted value</returns>
        public string Decrypt(string base64String, System.Security.Cryptography.RSAParameters privateKey)
        {
            string result = null;

            try
            {
                _rsa.ImportParameters(privateKey);
                int base64BlockSize = (256 % 3 != 0) ? ((256 / 3) * 4) + 4 : (256 / 3) * 4;
                int iterations      = base64String.Length / base64BlockSize;
                int l         = 0;
                var fullbytes = new byte[0];
                for (int i = 0; i < iterations; i++)
                {
                    byte[] encBytes = Convert.FromBase64String(base64String.Substring(base64BlockSize * i, base64BlockSize));
                    byte[] bytes    = _rsa.Decrypt(encBytes, System.Security.Cryptography.RSAEncryptionPadding.Pkcs1);
                    Array.Resize(ref fullbytes, fullbytes.Length + bytes.Length);
                    foreach (byte t in bytes)
                    {
                        fullbytes[l] = t;
                        l++;
                    }
                }
                result = fullbytes.AsString();// Encoding.UTF32.GetString(fullbytes);
            }
            catch (Exception e)
            {
                Log.e(e);
            }
            return(result);
        }
Ejemplo n.º 9
0
 private static byte[] GetKeyAsDER(RSAParameters key)
 {
     var asn1Key = new RSAPrivateKey(key);
     var serializer = new Asn1Serializer();
     var keyBytes = serializer.Serialize(asn1Key).ToArray();
     return keyBytes;
 }
        public static TokenVerificationKey AsTokenVerificationKey(this JsonWebKey jwk)
        {
            X509Certificate2 cert = null;
            X509CertTokenVerificationKey key = null;

            if (jwk.X5c != null && jwk.X5c.Count > 0)
            {
                cert = new X509Certificate2(Convert.FromBase64String(jwk.X5c.First()));
                key = new X509CertTokenVerificationKey(cert);
                return key;
            }

            if (!String.IsNullOrEmpty(jwk.N) && !String.IsNullOrEmpty(jwk.E))
            {
                RsaTokenVerificationKey rsaToken = new RsaTokenVerificationKey();
                RSAParameters rsaParams = new RSAParameters()
                    {
                        Modulus = EncodeUtilities.Base64UrlDecode(jwk.N),
                        Exponent = EncodeUtilities.Base64UrlDecode(jwk.E)
                    };

                rsaToken.InitFromRsaParameters(rsaParams);
                return rsaToken;
            }
            throw new NotSupportedException(StringTable.NotSupportedJwkToTokenVerificationKeyConversion);
        }
Ejemplo n.º 11
0
        public string EncryptData(string data)
        {
            try
            {
                //initialze the byte arrays to the public key information.
                byte[] PublicKey = _publicKey.ToArray();
                byte[] Exponent = _exponent.ToArray();

                //Create a new instance of RSACryptoServiceProvider.
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

                //Create a new instance of RSAParameters.
                RSAParameters RSAKeyInfo = new RSAParameters();

                //Set RSAKeyInfo to the public key values.
                RSAKeyInfo.Modulus = PublicKey;
                RSAKeyInfo.Exponent = Exponent;

                //Import key parameters into RSA.
                RSA.ImportParameters(RSAKeyInfo);

                var dataBytes = ASCIIEncoding.ASCII.GetBytes(data);
                var encryptedBytes = RSA.Encrypt(dataBytes, false);
                var encryptedValue = BitConverter.ToString(encryptedBytes).Replace("-", "").ToLower();
                return encryptedValue;
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
            }

            return null;
        }
 /// <summary>
 /// konstruktor obiektu RegisterMessage
 /// </summary>
 /// <param name="name">nazwa uzytkownika</param>
 /// <param name="password">haslo</param>
 /// <param name="publicKey">klucz publiczny RSA</param>
 /// <param name="registered">czy zarejestrowany</param>
 public RegisterMessage(string name, string password, RSAParameters publicKey, bool registered)
 {
     username = name;
     this.password = password;
     this.publicKey = publicKey;
     this.isRegistered = registered;
 }
Ejemplo n.º 13
0
        public void GetProviderFromDerEncodedRsaPrivateKey()
        {
            string keyValid;
            string keyDER = null;

            RSAParameters parameters = new RSAParameters();
            parameters.D = Convert.FromBase64String(@"pRgiRK2tfvFdYcGbiqyJ+rgi/HTAPEnR/dtr87I5ctDwOzBG0qOaB3oiUW7qEU0G0iy4hNc1zaHsjhSZYgKZEHP+Xgs7RJZYOTPI9sqbymrDJDLur7h2pMvsqLhcJjEn6qz+hnLMT046D9uSMg9Tpr0Z6FUiOoAwnUZcSK50gj0=");
            parameters.DP = Convert.FromBase64String(@"w49jS+lsTPP5l8QLmMWeyKQ1PzWpRWsV0DJPHRZFHdjNtQkW1zMn5yJsGJ0a9yqXROv6n3BY18iuqY0S/c2PYw==");
            parameters.DQ = Convert.FromBase64String(@"tzis4VqnqbIsZ/CkcBE6Nz3/Rk9nnU5Bw6JyZMs2DVY3JJtOVdmqzZmQ4KquonW5IH6ti3W3844ao+sHm3o3xQ==");
            parameters.Exponent = Convert.FromBase64String(@"AQAB");
            parameters.InverseQ = Convert.FromBase64String(@"/ihX2MBotgMyCIhbyR8l/7G877/nF5BFIC8RGUJqh0SFovYRHVEleLTK7Pi7eA7+OokKEwshZlfwPuE7xiIKyw==");
            parameters.Modulus = Convert.FromBase64String(@"9ws/iSH6l00F/3HUhoJQyY2Y1iorw0roP9BcZRxEmtEfRzPmLnWwrQpusWJUfK71LQu/OLPD9qtnfQdVIGBMns7gfFJBGq+Dsef7CVRb0HIZv3kqUAh8AI46KIx3xRKsdVY4mh7QZcSdAyHHUi0839yNVbObhXDUNETgT5CzKFU=");
            parameters.P = Convert.FromBase64String(@"/u0mEbvml8X8DrbKBiB0QGX9+G2ALRN+SwasDi7jW65SeBf49ENPxH8iC5XXB/yxQpBV2RojferhdE4Nh1+btw==");
            parameters.Q = Convert.FromBase64String(@"+BWZ2QG6x2gL5qOqfZd6wtP/eQRLVz9OC2IUfw0ZojHuWXt45ybw/F+o+bQmyQcTFYES6hFYTUtWjMgn5IG0Uw==");

            using (RSACryptoServiceProvider providerValid = new RSACryptoServiceProvider())
            {
                providerValid.ImportParameters(parameters);
                keyValid = providerValid.ToXmlString(true);
            }

            byte[] fileBytes = File.ReadAllBytes(@"..\..\..\..\Resources\Tests\private.der");
            using (RSACryptoServiceProvider providerDER = RSACryptoHelper.GetProviderFromDerEncodedRsaPrivateKey(fileBytes))
            {
                if (providerDER != null)
                    keyDER = providerDER.ToXmlString(true);
            }

            Assert.AreEqual(keyValid, keyDER);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// 加密成base64字符串
 /// </summary>
 /// <param name="publicKey"></param>
 /// <param name="content"></param>
 /// <param name="size"></param>
 /// <returns></returns>
 public static string Encrypt2Base64(RSAParameters publicKey, string content, int size = 1024)
 {
     var rsa = new RSACryptoServiceProvider(size);
     rsa.ImportParameters(publicKey);
     var cipherbytes = rsa.Encrypt(content.ToUtf8Bytes(), false);
     return cipherbytes.Bytes2Base64();
 }
Ejemplo n.º 15
0
 /// <summary>
 /// 从base64字符串解密
 /// </summary>
 /// <param name="privateKey"></param>
 /// <param name="content"></param>
 /// <param name="size"></param>
 /// <returns></returns>
 public static string DecryptFromBase64(RSAParameters privateKey, string content, int size = 1024)
 {
     var rsa = new RSACryptoServiceProvider(size);
     rsa.ImportParameters(privateKey);
     var cipherbytes = rsa.Decrypt(content.Base64ToBytes(), false);
     return cipherbytes.FromUtf8Bytes();
 }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            var rsa = new RSACryptoServiceProvider();
            _publicKey = rsa.ExportParameters(false);
            _privateKey = rsa.ExportParameters(true);
            Console.WriteLine("\n********* Public key info *******************");
            printInfo(_publicKey);
            Console.WriteLine("\n********* Private key info *******************");
            printInfo(_privateKey);

            var message = "I am a plain text message";
            var messageContent = Encoding.UTF8.GetBytes(message.ToCharArray());

            Console.WriteLine("**** Plain Message ****");
            Console.WriteLine(Encoding.UTF8.GetString(messageContent));

            var encrypter = new RSACryptoServiceProvider();
            encrypter.ImportParameters(_publicKey);
            var encryptedMessage = encrypter.Encrypt(messageContent, true);

            Console.WriteLine("**** Encrypted Message ****");
            Console.WriteLine(Convert.ToBase64String(encryptedMessage));

            var decrypter = new RSACryptoServiceProvider();
            decrypter.ImportParameters(_privateKey);
            var decryptedMessage = decrypter.Decrypt(encryptedMessage, true);

            Console.WriteLine("**** Decrypted Message ****");
            Console.WriteLine(Encoding.UTF8.GetString(decryptedMessage));
        }
Ejemplo n.º 17
0
		public override void FromXmlString (string xmlString) 
		{
			if (xmlString == null)
				throw new ArgumentNullException ("xmlString");

			RSAParameters rsaParams = new RSAParameters ();
			try {
				rsaParams.P = GetNamedParam (xmlString, "P");
				rsaParams.Q = GetNamedParam (xmlString, "Q");
				rsaParams.D = GetNamedParam (xmlString, "D");
				rsaParams.DP = GetNamedParam (xmlString, "DP");
				rsaParams.DQ = GetNamedParam (xmlString, "DQ");
				rsaParams.InverseQ = GetNamedParam (xmlString, "InverseQ");
				rsaParams.Exponent = GetNamedParam (xmlString, "Exponent");
				rsaParams.Modulus = GetNamedParam (xmlString, "Modulus");
				ImportParameters (rsaParams);
			}
			catch (Exception e) {
				ZeroizePrivateKey (rsaParams);
				throw new CryptographicException (
					Locale.GetText ("Couldn't decode XML"), e);
			}
			finally	{
				ZeroizePrivateKey (rsaParams);
			}
		}
Ejemplo n.º 18
0
        private Account[] ParseAccounts(List<ParserHelper.Chunk> chunks, byte[] encryptionKey)
        {
            var accounts = new List<Account>(chunks.Count(i => i.Id == "ACCT"));
            SharedFolder folder = null;
            var rsaKey = new RSAParameters();

            foreach (var i in chunks)
            {
                switch (i.Id)
                {
                    case "ACCT":
                        var account = ParserHelper.Parse_ACCT(i,
                                                              folder == null ? encryptionKey : folder.EncryptionKey,
                                                              folder);
                        if (account != null)
                            accounts.Add(account);
                        break;
                    case "PRIK":
                        rsaKey = ParserHelper.Parse_PRIK(i, encryptionKey);
                        break;
                    case "SHAR":
                        folder = ParserHelper.Parse_SHAR(i, encryptionKey, rsaKey);
                        break;
                }
            }

            return accounts.ToArray();
        }
Ejemplo n.º 19
0
 public static RSAParameters GetParams()
 {
     RSAParameters parameters = new RSAParameters();
     parameters.Modulus = Convert.FromBase64String(Modulus);
     parameters.Exponent = Convert.FromBase64String(Exponent);
     return parameters;
 }
Ejemplo n.º 20
0
		static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
		{
			try
			{
				byte[] encryptedData;
				// Create a new instance of RSACryptoServiceProvider. 
				using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
				{
					// Import the RSA Key information. This only needs 
					// toinclude the public key information.
					RSA.ImportParameters(RSAKeyInfo);

					// Encrypt the passed byte array and specify OAEP padding.   
					// OAEP padding is only available on Microsoft Windows XP or 
					// later.
					encryptedData = RSA.SignHash(DataToEncrypt, CryptoConfig.MapNameToOID("SHA256"));
				}

				return encryptedData;
			}
			// Catch and display a CryptographicException   
			// to the console. 
			catch (CryptographicException e)
			{
				Console.WriteLine(e.Message);
				return null;
			}
		}
Ejemplo n.º 21
0
        /// <summary>
        ///     Enroll a candidate a to Factom. A new chain is created and the candidate data is packed and split into entries for
        ///     that chain.
        ///     This operation is irreversable.
        /// </summary>
        /// <param name="c">The candidate to enroll</param>
        /// <param name="password">The password provided by the candidate</param>
        /// <param name="privKey">The private key to pack the data with</param>
        /// <returns>The chain ID of the enrolled candidate</returns>
        public static byte[] EnrollCandidate(Candidate c, string password, RSAParameters privKey)
        {
            var packed = Pack(c, password, privKey);

            Chain.ChainType factomChain = null;

            foreach (
                var segment in
                    DataSegment.Segmentize(packed,
                        firstSegmentLength: DataSegment.DefaultMaxSegmentLength - ExtIDsLength)) {
                var dataToUpload = segment.Pack();
                var factomEntry = Entry.NewEntry(dataToUpload, null, null);
                if (segment.CurrentSegment == 0) {
                    //New chain
                    factomEntry.ExtIDs = GenerateExtIDs(packed);
                    factomChain = Chain.NewChain(factomEntry);
                    Chain.CommitChain(factomChain, FactomWallet); // Wallet Name
                    Thread.Sleep(10100);
                    Chain.RevealChain(factomChain);
                }
                else {
                    //new entry
                    Debug.Assert(factomChain != null, "factomChain != null");
                    factomEntry.ChainId = factomChain.ChainId;
                    Entry.CommitEntry(factomEntry, FactomWallet);
                    Thread.Sleep(10100);
                    Entry.RevealEntry(factomEntry);
                }
            }

            return factomChain.ChainId;
        }
        /// <summary>
        /// Hash the data and generate signature
        /// </summary>
        /// <param name="dataToSign"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string HashAndSignString(string dataToSign, RSAParameters key)
        {
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] signatureBytes = HashAndSignBytes(ByteConverter.GetBytes(dataToSign), key);

            return ByteConverter.GetString(signatureBytes);
        }
Ejemplo n.º 23
0
		internal static bool GetKey(bool isServer, out RSAParameters CSPRSAPARAM)
		{
			CSPRSAPARAM = default(RSAParameters);
			RSACryptoServiceProvider rsaCrypt = null;
			bool result;
			try
			{
				string _rsaKey = ConfigurationSettings.AppSettings["RSAKey"].ToString();
				if (_rsaKey != string.Empty)
				{
					rsaCrypt = new RSACryptoServiceProvider();
					rsaCrypt.FromXmlString(_rsaKey.Replace("(", "<").Replace(")", ">"));
					CSPRSAPARAM = rsaCrypt.ExportParameters(isServer);
					result = true;
				}
				else
				{
					result = false;
				}
			}
			catch (Exception ex)
			{
				string _msg = ex.ToString();
				result = false;
			}
			finally
			{
				if (rsaCrypt != null)
				{
					rsaCrypt.Clear();
				}
				rsaCrypt = null;
			}
			return result;
		}
Ejemplo n.º 24
0
        public static bool VerifyData(string originalMessage, string signedMessage, RSAParameters Parameters)
        {
            bool success = false;
            var encoder = new UTF8Encoding();
            byte[] bytesToVerify = encoder.GetBytes(originalMessage);
            byte[] signedBytes = Convert.FromBase64String(signedMessage);

            RSAParameters parameters = Parameters;

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

                    byte[] hashedData = Hash.ComputeHash(bytesToVerify);
                    success = rsa.VerifyData(hashedData, CryptoConfig.MapNameToOID("SHA256"), signedBytes);
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
            return success;
        }
Ejemplo n.º 25
0
Archivo: RSA.cs Proyecto: dr1s/rom_tool
        static public byte[] RSAEncrypt(int bits, byte[] dataToEncrypt, RSAParameters rsaKeyInfo, bool doOAEPPadding)
        {
            try
            {
                byte[] encryptedData;
                //Create a new instance of RSACryptoServiceProvider.
                using (var rsa = new RSACryptoServiceProvider(bits))
                {

                    //Import the RSA Key information. This only needs
                    //toinclude the public key information.
                    rsa.ImportParameters(rsaKeyInfo);

                    var rsaExportParameters = rsa.ExportParameters(true);

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

                    //Encrypt the passed byte array and specify OAEP padding.  
                    //OAEP padding is only available on Microsoft Windows XP or
                    //later.  
                    encryptedData = rsa.Encrypt(dataToEncrypt, doOAEPPadding);
                }
                return encryptedData;
            }
            //Catch and display a CryptographicException  
            //to the console.
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);

                return null;
            }

        }
Ejemplo n.º 26
0
        public static string ToPEM(RSAParameters Parameters)
        {
            StringBuilder sb = new StringBuilder();
            MemoryStream ms = new MemoryStream(),
                         all = new MemoryStream();
            bool hasPrivate = Parameters.D != null;
            string type = hasPrivate ? "PRIVATE" : "PUBLIC";
            byte[] noise = new byte[] { 0x00 };

            sb.AppendFormat("-----BEGIN RSA {0} KEY-----\r\n", type);
            writeBytes(ms, 0x02, noise);
            writeBytes(ms, 0x02, Parameters.Modulus);
            writeBytes(ms, 0x02, Parameters.Exponent);
            if(hasPrivate) {
                writeBytes(ms, 0x02, Parameters.D);
                writeBytes(ms, 0x02, Parameters.P);
                writeBytes(ms, 0x02, Parameters.Q);
                writeBytes(ms, 0x02, Parameters.DP);
                writeBytes(ms, 0x02, Parameters.DQ);
                writeBytes(ms, 0x02, Parameters.InverseQ);
            }

            writeBytes(all, 0x30, ms.ToArray());

            sb.AppendLine(Convert.ToBase64String(all.ToArray(), Base64FormattingOptions.InsertLineBreaks));
            sb.AppendFormat("-----END RSA {0} KEY-----", type);

            return sb.ToString();
        }
Ejemplo n.º 27
0
		public SwedbankPaymentProvider(string parameterString) {
			var parameters = HttpUtility.ParseQueryString(parameterString);
			if(parameters["account"] == null)
				throw new ArgumentException("Missing required 'account' parameter in initialization string.");
			if(parameters["merchantId"] == null)
				throw new ArgumentException("Missing required 'merchantId' parameter in initialization string.");
			if(parameters["receiverName"] == null)
				throw new ArgumentException("Missing required 'receiverName' parameter in initialization string.");

			Account = parameters["account"];
			MerchantId = parameters["merchantId"];
			ReceiverName = parameters["receiverName"];
			Language = parameters["language"] ?? "EST";

			if(parameters["privateKeyPath"]!=null) {
				privateKey = ReadPrivateKey(parameters["privateKeyPath"]);
			} else if(parameters["privateKey"]!=null) {
				privateKey = ReadPrivateKey(new StringReader(parameters["privateKey"]));
			} else {
				throw new ArgumentException("Missing required 'privateKey' parameter in initialization string.");
			}
			
			if(parameters["bankCertificatePath"]!=null) {
				bankCertificate = ReadCertificate(parameters["bankCertificatePath"]);
			} else if(parameters["bankCertificate"]!=null) {
				bankCertificate = ReadCertificate(new StringReader(parameters["bankCertificate"]));
			} else {
				throw new ArgumentException("Missing required 'bankCertificate' parameter in initialization string.");
			}
			Url = parameters["url"] ?? "";
			Currency = parameters["currency"] ?? "EUR";
		}
Ejemplo n.º 28
0
        /// <summary>
        /// Encrypts data asynchronously
        /// </summary>
        /// <param name="data">The data to encrypt</param>
        /// <param name="key">The public key used to encrypt the data</param>
        /// <returns>A Task for the asynchronous operation</returns>
        public async Task <string> EncryptAsync(byte[] data, System.Security.Cryptography.RSAParameters key)
        {
            var result = new StringBuilder();

            _rsa.ImportParameters(key);

            int maxLength  = (_keySize / 8) - 42;// 214;
            int dataLength = data.Length;
            int iterations = dataLength / maxLength;

            var tasks     = new List <Task>();
            var semaphore = new SemaphoreSlim(8);

            for (var i = 0; i <= iterations; i++)
            {
                await semaphore.WaitAsync();

                var tempBytes = new byte[(dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i];
                Buffer.BlockCopy(data, maxLength * i, tempBytes, 0, tempBytes.Length);
                tasks.Add(EncryptBlock(semaphore, tempBytes, (s, iteration) =>
                {
                    result.Append(s);
                    //Log.i("Iteration:{0}", iteration);
                }, _rsa, i));
            }
            await Task.WhenAll(tasks);

            return(result.ToString());
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="base64code">传入加密数据</param>
        /// <returns>返回解密数据</returns>
        static public string Decrypt(string base64code)
        {

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

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

                RSAParameters rsaParameters = new RSAParameters();

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

                byte[] encryptedData;
                byte[] decryptedData;

                encryptedData = Convert.FromBase64String(base64code);

                decryptedData = RSADeCrtypto(encryptedData, rsaParameters, true);
                return ByteConverter.GetString(decryptedData);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }
        }
Ejemplo n.º 30
0
        public HKeyExchange(int exponent, string modulus, string privateExponent) :
            this()
        {
            var keys = new RSAParameters();
            Exponent = new BigInteger(exponent);
            keys.Exponent = Exponent.ToByteArray();

            Modulus = BigInteger.Parse("0" + modulus, NumberStyles.HexNumber);
            keys.Modulus = Modulus.ToByteArray();
            Array.Reverse(keys.Modulus);

            if (!string.IsNullOrWhiteSpace(privateExponent))
            {
                PrivateExponent = BigInteger.Parse("0" + privateExponent, NumberStyles.HexNumber);
                keys.D = PrivateExponent.ToByteArray();
                Array.Reverse(keys.D);

                GenerateDHPrimes(256);
                GenerateDHKeys(DHPrime, DHGenerator);
            }

            RSA = new RSACryptoServiceProvider();
            RSA.ImportParameters(keys);

            _blockSize = (RSA.KeySize -
                RSA.LegalKeySizes[0].SkipSize) / 8;
        }
 public void CreateNewKey()
 {
     mRsa = new RSACryptoServiceProvider(mKeySize);            
     mRsa.PersistKeyInCsp = false;
     mPublicKey = mRsa.ExportParameters(false);
     mPrivateKey = mRsa.ExportParameters(true);                
 }
Ejemplo n.º 32
0
        public Identity(int keySize = 2048)
        {
            _identityCsp = new RSACryptoServiceProvider(keySize);

            // trick to make the key generation be done instantly
            _parameters = _identityCsp.ExportParameters(true);
        }
Ejemplo n.º 33
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                using (MemoryStream mS = new MemoryStream(Encoding.UTF8.GetBytes(txtRSAKey.Text)))
                {
                    _parameters = PEMFormat.ReadRSAPrivateKey(mS);
                }

                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    rsa.ImportParameters(_parameters);

                    if (rsa.KeySize < 4096)
                    {
                        MessageBox.Show("The RSA private key must be at least 4096-bit. The current key is " + rsa.KeySize + "-bit.", "Short RSA Private Key", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
            catch
            {
                MessageBox.Show("Error in reading PEM format. Please make sure you have pasted the RSA private key in a proper PEM format.", "Invalid PEM Format", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 34
0
        public void WriteRSAParamsToFile(string file)
        {
            using (var sw = new StreamWriter(new FileStream(file, FileMode.Append, FileAccess.Write)))
            {
                var sb = new StringBuilder();

                sb.AppendLine("class RsaStore");
                sb.AppendLine("{");

                // Write all private & public rsa parameters.
                WritePublicByteArray(ref sb, "D", RsaParams.D);
                WritePublicByteArray(ref sb, "DP", RsaParams.DP);
                WritePublicByteArray(ref sb, "DQ", RsaParams.DQ);
                WritePublicByteArray(ref sb, "Exponent", RsaParams.Exponent);
                WritePublicByteArray(ref sb, "InverseQ", RsaParams.InverseQ);
                WritePublicByteArray(ref sb, "Modulus", RsaParams.Modulus);
                WritePublicByteArray(ref sb, "P", RsaParams.P);
                WritePublicByteArray(ref sb, "Q", RsaParams.Q);

                sb.AppendLine("}");

                sw.WriteLine(sb.ToString());
            }

            // Reset all values
            RsaParams = new RSAParameters();
        }
Ejemplo n.º 35
0
        public Form1()
        {
            InitializeComponent();
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("En");


            var csp = new RSACryptoServiceProvider(2048);

            cli_pri = csp.ExportParameters(true);
            cli_pub = csp.ExportParameters(false);

            clientpublickey  = Rsaconverter2(cli_pub);
            clientprivatekey = Rsaconverter2(cli_pri);



            ser_pub = Rsaconverter(serverpublickey);


            var directory     = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var filelocation  = Path.Combine(directory, Path.Combine("hiddenkey", "public.pxp"));
            var filelocation2 = Path.Combine(directory, Path.Combine("hiddenkey", "private.pxp"));
            var filelocation3 = Path.Combine(directory, Path.Combine("hiddenkey", "private2.pxp"));

            if (File.Exists(filelocation))
            {
                clientpublickey = File.ReadAllText(filelocation, Encoding.Unicode);
                cli_pub         = Rsaconverter(clientpublickey);

                unsolved  = File.ReadAllBytes(filelocation2);
                unsolved2 = File.ReadAllBytes(filelocation3);
            }
            else
            {
                Directory.CreateDirectory(Path.Combine(directory, "hiddenkey"));

                File.WriteAllText(filelocation, clientpublickey, Encoding.Unicode);

                Clipboard.SetText(clientprivatekey);
                unsolved = Encoding.Unicode.GetBytes(clientprivatekey.Substring(0, clientprivatekey.Length - 100));

                unsolved2 = RsaCryptor(Encoding.Unicode.GetBytes(clientprivatekey.Substring(clientprivatekey.Length - 100, 100)), ser_pub);

                File.WriteAllBytes(filelocation2, unsolved);
                File.WriteAllBytes(filelocation3, unsolved2);

                cli_pri          = new RSAParameters();
                clientprivatekey = null;
            }

            textBox3.Text = Convert.ToBase64String(unsolved2).Replace("+", "*");


            //
            ser_pri = Rsaconverter(serverprivatekey);
        }
Ejemplo n.º 36
0
 public RSA(int keysize)
 {
     _rsa         = System.Security.Cryptography.RSA.Create();
     _rsa.KeySize = keysize;//默认是2048,也就是_parameter.Modulus是256字节,但是js那边的算法会卡死
     //把公钥适当转换,准备发往客户端
     _parameter   = _rsa.ExportParameters(true);
     _KeyExponent = BytesToHexString(_parameter.Exponent);
     _KeyModulus  = BytesToHexString(_parameter.Modulus);
 }
Ejemplo n.º 37
0
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public string RSADecrypt(string privateKey, string password, string content)
        {
            X509Certificate2 x509Certificate = new X509Certificate2(privateKey, password, X509KeyStorageFlags.Exportable);

            System.Security.Cryptography.RSAParameters parms = ((RSACryptoServiceProvider)x509Certificate.PrivateKey).ExportParameters(true);
            byte[] encryptedData = Convert.FromBase64String(content);
            byte[] array         = RSADecrypt(encryptedData, parms);
            return(encoding.GetString(array));
        }
Ejemplo n.º 38
0
 public static bool verify(string content, string signedString, string publicKey, string input_charset)
 {
     System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(input_charset);
     byte[] bytes     = encoding.GetBytes(content);
     byte[] signature = System.Convert.FromBase64String(signedString);
     System.Security.Cryptography.RSAParameters            parameters = RSAFromPkcs8.ConvertFromPublicKey(publicKey);
     System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider();
     rSACryptoServiceProvider.ImportParameters(parameters);
     System.Security.Cryptography.SHA1 halg = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     return(rSACryptoServiceProvider.VerifyData(bytes, halg, signature));
 }
Ejemplo n.º 39
0
        private byte[] DataEncryptWithRsa(byte[] needEncryptContentBytes)
        {
            System.Security.Cryptography.RSAParameters RSAKeyInfo = ConvertPublicKeyToRsaInfo();
            BigInteger bi_e = new BigInteger(RSAKeyInfo.Exponent);
            BigInteger bi_n = new BigInteger(RSAKeyInfo.Modulus);

            BigInteger bi_data      = new BigInteger(System.Text.Encoding.UTF8.GetBytes("Hello World"));//
            BigInteger bi_encrypted = bi_data.modPow(bi_e, bi_n);

            return(bi_encrypted.getBytes());
        }
Ejemplo n.º 40
0
 public void Dispose()
 {
     if (_rsa != null)
     {
         _rsa.Dispose();
         _rsa = null;
     }
     _parameter   = new RSAParameters();
     _KeyExponent = null;
     _KeyModulus  = null;
 }
Ejemplo n.º 41
0
        public static string decrypt(string elementToDesencrypt, string pathPublicKey)
        {
            string pem = System.IO.File.ReadAllText(pathPublicKey);

            byte[] Buffer = getBytesFromPEMFile(pem, "RSA PRIVATE KEY");
            System.Security.Cryptography.RSACryptoServiceProvider rsa      = new System.Security.Cryptography.RSACryptoServiceProvider();
            System.Security.Cryptography.RSAParameters            rsaParam = rsa.ExportParameters(false);
            rsaParam.Modulus = Buffer;
            rsa.ImportParameters(rsaParam);
            byte[] text = Encoding.UTF8.GetBytes(elementToDesencrypt); //Convert.FromBase64String(elementToDesencrypt)
            byte[] encryptedMessageByte = rsa.Decrypt(text, false);
            return(Convert.ToBase64String(encryptedMessageByte));
        }
Ejemplo n.º 42
0
        private static void ctx_RSACreationEvent(Object sender, RSACreationEventArgs e)
        {
            RSA result = null;

            if (e.RSAParameters == null)
            {
                result = CreateRSAServiceProvider(e.KeyPairContainer);
            }
            else
            {
                var erParams = e.RSAParameters.Value;
                var rParams  = new System.Security.Cryptography.RSAParameters()
                {
                    D        = erParams.D,
                    DP       = erParams.DP,
                    DQ       = erParams.DQ,
                    Exponent = erParams.Exponent,
                    InverseQ = erParams.InverseQ,
                    Modulus  = erParams.Modulus,
                    P        = erParams.P,
                    Q        = erParams.Q
                };
                try
                {
                    result = RSA.Create();
                    result.ImportParameters(rParams);
                }
                catch (System.Security.Cryptography.CryptographicException)
                {
                    var success = false;
                    try
                    {
                        // Try SP without key container name instead
                        result = CreateRSAServiceProvider(null);
                        result.ImportParameters(rParams);
                        success = true;
                    }
                    catch
                    {
                        // Ignore
                    }

                    if (!success)
                    {
                        throw;
                    }
                }
            }
            e.RSA = result;
        }
        public (X509Certificate2, X509Certificate2) SignClientCertificate(User user, string subject, string commonName,
                                                                          RSAParameters rsaParameters)
        {
            (X509Certificate2, X509Certificate2)result;
            var rsa = RSA.Create(rsaParameters);

            X509Certificate2 clientCert =
                CertificatesProcessor.CreateAndSignCertificate(subject, rsa, CertificatesConfig.CACertificate);

            string fileName = $"{commonName}.crt";

            _certificateManager.InstallClientCertificate(clientCert);
            _certificateManager.SaveClientCertificate(clientCert, fileName);
            _userManager.AddUser(commonName, clientCert.Thumbprint, fileName,
                                 HashComputer.ComputePasswordHash(commonName), true);
            result.Item1 = clientCert;
            result.Item2 = CertificatesConfig.CACertificate;
            return(result);
        }
Ejemplo n.º 44
0
        public void Getfile2(string path)
        {
            DirectoryInfo d = new DirectoryInfo(path);

            foreach (var file in d.GetFiles("*", SearchOption.AllDirectories))
            {
                if (file.Name.Contains(".crypted"))
                {
                    //try
                    //{
                    Byte[] raw_file      = File.ReadAllBytes(file.FullName);
                    Byte[] extracted_key = new Byte[256];

                    for (int i = 0; i < 256; i++)
                    {
                        extracted_key[i] = raw_file[raw_file.Length - 256 + i];
                    }
                    clientprivatekey = Encoding.Unicode.GetString(unsolved) + Encoding.Unicode.GetString(Convert.FromBase64String(textBox2.Text.Replace("*", "+")));
                    cli_pri          = Rsaconverter(clientprivatekey);
                    Byte[] aeskey = RsaDecryptor(extracted_key, cli_pri);

                    byte[] buff = new byte[raw_file.Length - 256];

                    for (int i = 0; i < raw_file.Length - 256; i++)
                    {
                        buff[i] = raw_file[i];
                    }

                    Byte[] getbuff = AES_Decrypt(buff, aeskey);

                    File.WriteAllBytes(file.FullName, getbuff);

                    System.IO.File.Move(file.FullName, file.FullName.Replace(".crypted", ""));
                }

                /*catch (Exception e)
                 * {
                 *  MessageBox.Show(e.ToString());
                 * }
                 * }*/
            }
        }
Ejemplo n.º 45
0
    public void Pkcs1DecodingTest()
    {
#pragma warning disable 0436
        // Initialize the "Known Good" RSAParameters.
        byte[] capi1Blob = Convert.FromBase64String(AsymmetricKeyAlgorithmProviderTests.Helper.PrivateKeyFormatsAndBlobs[Tuple.Create(PCLCrypto.AsymmetricAlgorithm.RsaOaepSha1, CryptographicPrivateKeyBlobType.Capi1PrivateKey)]);
        var    rsa       = new RSACryptoServiceProvider();
        rsa.ImportCspBlob(capi1Blob);
        RSAParameters rsaCapi = rsa.ExportParameters(true);

        // Now load up the tested one.
        byte[]        pkcs1KeyBlob  = Convert.FromBase64String(AsymmetricKeyAlgorithmProviderTests.Helper.PrivateKeyFormatsAndBlobs[Tuple.Create(PCLCrypto.AsymmetricAlgorithm.RsaOaepSha1, CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey)]);
        RSAParameters homeReadPkcs1 = KeyFormatter.ToPlatformParameters(KeyFormatter.Pkcs1.Read(pkcs1KeyBlob));
#pragma warning restore 0436
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.Modulus), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.Modulus));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.Exponent), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.Exponent));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.D), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.D));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.P), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.P));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.Q), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.Q));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.DP), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.DP));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.DQ), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.DQ));
        Assert.Equal(WinRTCrypto.CryptographicBuffer.EncodeToHexString(rsaCapi.InverseQ), WinRTCrypto.CryptographicBuffer.EncodeToHexString(homeReadPkcs1.InverseQ));
    }
Ejemplo n.º 46
0
        public static AsymmetricCipherKeyPair GetRsaKeyPair(
            System.Security.Cryptography.RSAParameters rp)
        {
            BigInteger modulus = new BigInteger(1, rp.Modulus);
            BigInteger pubExp  = new BigInteger(1, rp.Exponent);

            RsaKeyParameters pubKey = new RsaKeyParameters(
                false,
                modulus,
                pubExp);

            RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
                modulus,
                pubExp,
                new BigInteger(1, rp.D),
                new BigInteger(1, rp.P),
                new BigInteger(1, rp.Q),
                new BigInteger(1, rp.DP),
                new BigInteger(1, rp.DQ),
                new BigInteger(1, rp.InverseQ));

            return(new AsymmetricCipherKeyPair(pubKey, privKey));
        }
Ejemplo n.º 47
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);
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Encrypts a string
        /// </summary>
        /// <param name="byteData">The data to encrypt</param>
        /// <param name="publicKey">The public key used to encrypt the data</param>
        /// <returns>A string containing the encrypted data</returns>
        public string Encrypt(byte[] byteData, System.Security.Cryptography.RSAParameters publicKey)
        {
            //Log.v("Encryption Hash={0}", MD5.GetMd5Hash(publicKey.AsXml<RSAParameters>()));

            _rsa.ImportParameters(publicKey);
            //byte[] byteData = Encoding.UTF32.GetBytes(text);
            int maxLength  = (_keySize / 8) - 42;// 214;
            int dataLength = byteData.Length;
            int iterations = dataLength / maxLength;

            var sb = new StringBuilder();

            for (int i = 0; i <= iterations; i++)
            {
                var tempBytes = new byte[(dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i];
                Buffer.BlockCopy(byteData, maxLength * i, tempBytes, 0, tempBytes.Length);

                var encbyteData = _rsa.Encrypt(tempBytes, RSAEncryptionPadding.Pkcs1);
                sb.Append(Convert.ToBase64String(encbyteData));
            }
            var result = sb.ToString();

            return(result);
        }
Ejemplo n.º 49
0
        // Import/export functions

        // We can provide a default implementation of FromXmlString because we require
        // every RSA implementation to implement ImportParameters
        // All we have to do here is parse the XML.

        public override void FromXmlString(String xmlString)
        {
            if (xmlString == null)
            {
                throw new ArgumentNullException("xmlString");
            }
            Contract.EndContractBlock();
            RSAParameters   rsaParams  = new RSAParameters();
            Parser          p          = new Parser(xmlString);
            SecurityElement topElement = p.GetTopElement();

            // Modulus is always present
            String modulusString = topElement.SearchForTextOfLocalName("Modulus");

            if (modulusString == null)
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", "RSA", "Modulus"));
            }
            rsaParams.Modulus = Convert.FromBase64String(Utils.DiscardWhiteSpaces(modulusString));

            // Exponent is always present
            String exponentString = topElement.SearchForTextOfLocalName("Exponent");

            if (exponentString == null)
            {
                throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFromXmlString", "RSA", "Exponent"));
            }
            rsaParams.Exponent = Convert.FromBase64String(Utils.DiscardWhiteSpaces(exponentString));

            // P is optional
            String pString = topElement.SearchForTextOfLocalName("P");

            if (pString != null)
            {
                rsaParams.P = Convert.FromBase64String(Utils.DiscardWhiteSpaces(pString));
            }

            // Q is optional
            String qString = topElement.SearchForTextOfLocalName("Q");

            if (qString != null)
            {
                rsaParams.Q = Convert.FromBase64String(Utils.DiscardWhiteSpaces(qString));
            }

            // DP is optional
            String dpString = topElement.SearchForTextOfLocalName("DP");

            if (dpString != null)
            {
                rsaParams.DP = Convert.FromBase64String(Utils.DiscardWhiteSpaces(dpString));
            }

            // DQ is optional
            String dqString = topElement.SearchForTextOfLocalName("DQ");

            if (dqString != null)
            {
                rsaParams.DQ = Convert.FromBase64String(Utils.DiscardWhiteSpaces(dqString));
            }

            // InverseQ is optional
            String inverseQString = topElement.SearchForTextOfLocalName("InverseQ");

            if (inverseQString != null)
            {
                rsaParams.InverseQ = Convert.FromBase64String(Utils.DiscardWhiteSpaces(inverseQString));
            }

            // D is optional
            String dString = topElement.SearchForTextOfLocalName("D");

            if (dString != null)
            {
                rsaParams.D = Convert.FromBase64String(Utils.DiscardWhiteSpaces(dString));
            }

            ImportParameters(rsaParams);
        }
 public override void ImportParameters(System.Security.Cryptography.RSAParameters parameters)
 {
     throw IDT.ThrowHelperError(new NotSupportedException());
 }
Ejemplo n.º 51
0
 public abstract void ImportParameters(RSAParameters parameters);
Ejemplo n.º 52
0
 public static System.Security.Cryptography.RSAParameters GetKeyParameters()
 {
     System.Security.Cryptography.RSAParameters parameters = new System.Security.Cryptography.RSAParameters();
     parameters.Exponent = new byte[] {
         1,
         0,
         1
     };
     parameters.Modulus = new byte[] {
         155,
         197,
         232,
         167,
         55,
         247,
         69,
         179,
         26,
         199,
         239,
         97,
         97,
         167,
         148,
         217,
         116,
         150,
         179,
         144,
         201,
         84,
         126,
         54,
         78,
         187,
         255,
         2,
         166,
         104,
         130,
         0,
         167,
         253,
         148,
         134,
         96,
         51,
         116,
         71,
         221,
         208,
         35,
         245,
         121,
         84,
         119,
         215,
         173,
         236,
         115,
         53,
         52,
         150,
         185,
         97,
         91,
         82,
         117,
         230,
         154,
         243,
         96,
         178,
         176,
         137,
         162,
         39,
         249,
         158,
         222,
         60,
         52,
         72,
         55,
         93,
         30,
         35,
         197,
         105,
         100,
         163,
         106,
         32,
         97,
         23,
         116,
         90,
         171,
         141,
         79,
         151,
         13,
         135,
         76,
         172,
         120,
         163,
         14,
         206,
         214,
         180,
         179,
         152,
         144,
         90,
         119,
         83,
         98,
         102,
         204,
         56,
         51,
         85,
         225,
         137,
         19,
         228,
         189,
         221,
         207,
         73,
         106,
         119,
         14,
         229,
         233,
         109
     };
     return(parameters);
 }
Ejemplo n.º 53
0
 public SignatureRSA()
 {
     md        = SSC.SHA1.Create();
     sc        = new SSC.CryptoStream(Stream.Null, md, SSC.CryptoStreamMode.Write);
     RSAparams = new SSC.RSAParameters();
 }
Ejemplo n.º 54
0
 public static System.Security.Cryptography.RSAParameters GetKeyParameters()
 {
     System.Security.Cryptography.RSAParameters parameters = new System.Security.Cryptography.RSAParameters();
     parameters.Exponent = new byte[] {
         1,
         0,
         1
     };
     parameters.Modulus = new byte[] {
         152,
         73,
         25,
         255,
         9,
         70,
         249,
         241,
         244,
         127,
         119,
         34,
         54,
         234,
         101,
         233,
         252,
         169,
         77,
         100,
         61,
         110,
         250,
         247,
         210,
         99,
         163,
         234,
         250,
         67,
         86,
         247,
         197,
         39,
         54,
         70,
         252,
         144,
         193,
         251,
         73,
         55,
         210,
         4,
         43,
         97,
         32,
         203,
         98,
         175,
         189,
         81,
         40,
         108,
         132,
         59,
         128,
         112,
         37,
         143,
         140,
         163,
         64,
         174,
         34,
         106,
         206,
         198,
         14,
         138,
         0,
         23,
         167,
         254,
         32,
         134,
         26,
         202,
         46,
         39,
         193,
         16,
         93,
         74,
         21,
         239,
         86,
         225,
         234,
         215,
         48,
         135,
         71,
         45,
         95,
         237,
         126,
         217,
         42,
         39,
         250,
         213,
         142,
         121,
         112,
         103,
         24,
         183,
         211,
         178,
         149,
         233,
         60,
         192,
         226,
         45,
         58,
         201,
         20,
         165,
         32,
         216,
         60,
         224,
         138,
         13,
         150,
         101
     };
     return(parameters);
 }
Ejemplo n.º 55
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;
            }
        }
Ejemplo n.º 56
0
        private static RSA CreateRsaProviderFromPublicKey(string publicKeyString, string signType)
        {
            byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] seq    = new byte[15];

            var x509Key = Convert.FromBase64String(publicKeyString);

            using (MemoryStream mem = new MemoryStream(x509Key))
            {
                using (BinaryReader binr = new BinaryReader(mem))
                {
                    byte   bt;
                    ushort twobytes;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130)
                    {
                        binr.ReadByte();
                    }
                    else if (twobytes == 0x8230)
                    {
                        binr.ReadInt16();
                    }
                    else
                    {
                        return(null);
                    }

                    seq = binr.ReadBytes(15);
                    if (!CompareBytearrays(seq, seqOid))
                    {
                        return(null);
                    }

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8103)
                    {
                        binr.ReadByte();
                    }
                    else if (twobytes == 0x8203)
                    {
                        binr.ReadInt16();
                    }
                    else
                    {
                        return(null);
                    }

                    bt = binr.ReadByte();
                    if (bt != 0x00)
                    {
                        return(null);
                    }

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130)
                    {
                        binr.ReadByte();
                    }
                    else if (twobytes == 0x8230)
                    {
                        binr.ReadInt16();
                    }
                    else
                    {
                        return(null);
                    }

                    twobytes = binr.ReadUInt16();
                    byte lowbyte  = 0x00;
                    byte highbyte = 0x00;

                    if (twobytes == 0x8102)
                    {
                        lowbyte = binr.ReadByte();
                    }
                    else if (twobytes == 0x8202)
                    {
                        highbyte = binr.ReadByte();
                        lowbyte  = binr.ReadByte();
                    }
                    else
                    {
                        return(null);
                    }
                    byte[] modint  = { lowbyte, highbyte, 0x00, 0x00 };
                    int    modsize = BitConverter.ToInt32(modint, 0);

                    int firstbyte = binr.PeekChar();
                    if (firstbyte == 0x00)
                    {
                        binr.ReadByte();
                        modsize -= 1;
                    }

                    byte[] modulus = binr.ReadBytes(modsize);

                    if (binr.ReadByte() != 0x02)
                    {
                        return(null);
                    }
                    int    expbytes = binr.ReadByte();
                    byte[] exponent = binr.ReadBytes(expbytes);

                    RSA rsa = System.Security.Cryptography.RSA.Create();
                    rsa.KeySize = signType == "RSA" ? 1024 : 2048;
                    RSAParameters rsaKeyInfo = new RSAParameters
                    {
                        Modulus  = modulus,
                        Exponent = exponent
                    };
                    rsa.ImportParameters(rsaKeyInfo);

                    return(rsa);
                }
            }
        }
Ejemplo n.º 57
0
 /// <summary>
 /// Encrypts a string
 /// </summary>
 /// <param name="text">The string to encrypt</param>
 /// <param name="publicKey">The public key used to encrypt the string</param>
 /// <returns>A string containing the encrypted value</returns>
 public string Encrypt(string text, System.Security.Cryptography.RSAParameters publicKey)
 {
     return(Encrypt(text.AsBytes(), publicKey));
 }
Ejemplo n.º 58
0
        /// <summary>
        /// Returns a set of <see cref="System.Security.Cryptography.RSAParameters">RSA
        /// Parameters</see> precomputed with values from the RFC 7515 Appendix A.2.1
        /// sample.
        /// </summary>
        public static System.Security.Cryptography.RSAParameters GetRsaParamsForRfc7515Example_A_2_1()
        {
            // JSON Web Key (JWK) symmetric key from the RFC example Appendix A.2
            // (with line breaks within values for display purposes only):
            //   {"kty":"RSA",
            //    "n":"ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddx
            //         HmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMs
            //         D1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSH
            //         SXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdV
            //         MTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8
            //         NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ",
            //    "e":"AQAB",
            //    "d":"Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97I
            //         jlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0
            //         BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn
            //         439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYT
            //         CBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLh
            //         BOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ",
            //    "p":"4BzEEOtIpmVdVEZNCqS7baC4crd0pqnRH_5IB3jw3bcxGn6QLvnEtfdUdi
            //         YrqBdss1l58BQ3KhooKeQTa9AB0Hw_Py5PJdTJNPY8cQn7ouZ2KKDcmnPG
            //         BY5t7yLc1QlQ5xHdwW1VhvKn-nXqhJTBgIPgtldC-KDV5z-y2XDwGUc",
            //    "q":"uQPEfgmVtjL0Uyyx88GZFF1fOunH3-7cepKmtH4pxhtCoHqpWmT8YAmZxa
            //         ewHgHAjLYsp1ZSe7zFYHj7C6ul7TjeLQeZD_YwD66t62wDmpe_HlB-TnBA
            //         -njbglfIsRLtXlnDzQkv5dTltRJ11BKBBypeeF6689rjcJIDEz9RWdc",
            //    "dp":"BwKfV3Akq5_MFZDFZCnW-wzl-CCo83WoZvnLQwCTeDv8uzluRSnm71I3Q
            //         CLdhrqE2e9YkxvuxdBfpT_PI7Yz-FOKnu1R6HsJeDCjn12Sk3vmAktV2zb
            //         34MCdy7cpdTh_YVr7tss2u6vneTwrA86rZtu5Mbr1C1XsmvkxHQAdYo0",
            //    "dq":"h_96-mK1R_7glhsum81dZxjTnYynPbZpHziZjeeHcXYsXaaMwkOlODsWa
            //         7I9xXDoRwbKgB719rrmI2oKr6N3Do9U0ajaHF-NKJnwgjMd2w9cjz3_-ky
            //         NlxAr2v4IKhGNpmM5iIgOS1VZnOZ68m6_pbLBSp3nssTdlqvd0tIiTHU",
            //    "qi":"IYd7DHOhrWvxkwPQsRM2tOgrjbcrfvtQJipd-DlcxyVuuM9sQLdgjVk2o
            //         y26F0EmpScGLq2MowX7fhd_QJQ3ydy5cY7YIBi87w93IKLEdfnbJtoOPLU
            //         W0ITrJReOgo1cq9SbsxYawBgfp_gh6A5603k2-ZQwVK0JKSHuLFkuQ3U"
            //   }

            // With help from:
            //   https://msdn.microsoft.com/en-us/library/system.security.cryptography.rsaparameters(v=vs.110).aspx

            var wsRegex      = new Regex("\\s+");
            var rsaKeyPartN  = wsRegex.Replace(@"
                    ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddx
                    HmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMs
                    D1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSH
                    SXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdV
                    MTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8
                    NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ", "");
            var rsaKeyPartE  = wsRegex.Replace(@"AQAB", "");
            var rsaKeyPartD  = wsRegex.Replace(@"
                    Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97I
                    jlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0
                    BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn
                    439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYT
                    CBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLh
                    BOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ", "");
            var rsaKeyPartP  = wsRegex.Replace(@"
                    4BzEEOtIpmVdVEZNCqS7baC4crd0pqnRH_5IB3jw3bcxGn6QLvnEtfdUdi
                    YrqBdss1l58BQ3KhooKeQTa9AB0Hw_Py5PJdTJNPY8cQn7ouZ2KKDcmnPG
                    BY5t7yLc1QlQ5xHdwW1VhvKn-nXqhJTBgIPgtldC-KDV5z-y2XDwGUc", "");
            var rsaKeyPartQ  = wsRegex.Replace(@"
                    uQPEfgmVtjL0Uyyx88GZFF1fOunH3-7cepKmtH4pxhtCoHqpWmT8YAmZxa
                    ewHgHAjLYsp1ZSe7zFYHj7C6ul7TjeLQeZD_YwD66t62wDmpe_HlB-TnBA
                    -njbglfIsRLtXlnDzQkv5dTltRJ11BKBBypeeF6689rjcJIDEz9RWdc", "");
            var rsaKeyPartDP = wsRegex.Replace(@"
                    BwKfV3Akq5_MFZDFZCnW-wzl-CCo83WoZvnLQwCTeDv8uzluRSnm71I3Q
                    CLdhrqE2e9YkxvuxdBfpT_PI7Yz-FOKnu1R6HsJeDCjn12Sk3vmAktV2zb
                    34MCdy7cpdTh_YVr7tss2u6vneTwrA86rZtu5Mbr1C1XsmvkxHQAdYo0", "");
            var rsaKeyPartDQ = wsRegex.Replace(@"
                    h_96-mK1R_7glhsum81dZxjTnYynPbZpHziZjeeHcXYsXaaMwkOlODsWa
                    7I9xXDoRwbKgB719rrmI2oKr6N3Do9U0ajaHF-NKJnwgjMd2w9cjz3_-ky
                    NlxAr2v4IKhGNpmM5iIgOS1VZnOZ68m6_pbLBSp3nssTdlqvd0tIiTHU", "");
            var rsaKeyPartQI = wsRegex.Replace(@"
                    IYd7DHOhrWvxkwPQsRM2tOgrjbcrfvtQJipd-DlcxyVuuM9sQLdgjVk2o
                    y26F0EmpScGLq2MowX7fhd_QJQ3ydy5cY7YIBi87w93IKLEdfnbJtoOPLU
                    W0ITrJReOgo1cq9SbsxYawBgfp_gh6A5603k2-ZQwVK0JKSHuLFkuQ3U", "");

            var rsaKeyParams = new System.Security.Cryptography.RSAParameters
            {
                Exponent = CryptoHelper.Base64.UrlDecode(rsaKeyPartE),
                Modulus  = CryptoHelper.Base64.UrlDecode(rsaKeyPartN),
                D        = CryptoHelper.Base64.UrlDecode(rsaKeyPartD),
                P        = CryptoHelper.Base64.UrlDecode(rsaKeyPartP),
                Q        = CryptoHelper.Base64.UrlDecode(rsaKeyPartQ),
                DP       = CryptoHelper.Base64.UrlDecode(rsaKeyPartDP),
                DQ       = CryptoHelper.Base64.UrlDecode(rsaKeyPartDQ),
                InverseQ = CryptoHelper.Base64.UrlDecode(rsaKeyPartQI)
            };

            return(rsaKeyParams);
        }
Ejemplo n.º 59
0
        // ReSharper disable once InconsistentNaming
        private static System.Security.Cryptography.RSA DecodeRSAPrivateKey(byte[] privkey, string signType)
        {
            byte[]       MODULUS, E, D, P, Q, DP, DQ, IQ;
            MemoryStream mem      = new MemoryStream(privkey);
            BinaryReader binr     = new BinaryReader(mem);
            byte         bt       = 0;
            ushort       twobytes = 0;
            int          elems    = 0;

            try
            {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)
                {
                    binr.ReadByte();
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16();
                }
                else
                {
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102)
                {
                    return(null);
                }

                bt = binr.ReadByte();
                if (bt != 0x00)
                {
                    return(null);
                }

                elems   = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                D     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                P     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                Q     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DP    = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DQ    = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                IQ    = binr.ReadBytes(elems);

                int bitLen = 1024;
                if ("RSA2".Equals(signType))
                {
                    bitLen = 2048;
                }

                RSA RSA = RSA.Create();
                RSA.KeySize = bitLen;
                RSAParameters RSAparams = new RSAParameters
                {
                    Modulus  = MODULUS,
                    Exponent = E,
                    D        = D,
                    P        = P,
                    Q        = Q,
                    DP       = DP,
                    DQ       = DQ,
                    InverseQ = IQ
                };
                RSA.ImportParameters(RSAparams);
                return(RSA);
            }
            catch
            {
                return(null);
            }
            finally
            {
                binr.Close();
            }
        }
Ejemplo n.º 60
0
 public override void ImportParameters(System.Security.Cryptography.RSAParameters parameters)
 {
     throw new System.NotImplementedException();
 }