Encrypt() public method

public Encrypt ( byte data, RSAEncryptionPadding padding ) : byte[]
data byte
padding RSAEncryptionPadding
return byte[]
Example #1
1
        public static void EncryptionKeyRequest(MinecraftClient client, IPacket _packet)
        {
            var packet = (EncryptionKeyRequestPacket)_packet;
            var random = RandomNumberGenerator.Create();
            client.SharedSecret = new byte[16];
            random.GetBytes(client.SharedSecret); // Generate a secure AES key

            if (packet.ServerId != "-") // Online mode
            {
                // Authenticate with minecraft.net
                var data = Encoding.ASCII.GetBytes(packet.ServerId)
                    .Concat(client.SharedSecret)
                    .Concat(packet.PublicKey).ToArray();
                var hash = Cryptography.JavaHexDigest(data);
                var webClient = new WebClient();
                string result = webClient.DownloadString("http://session.minecraft.net/game/joinserver.jsp?user="******"&sessionId=" + Uri.EscapeUriString(client.Session.SessionId) +
                    "&serverId=" + Uri.EscapeUriString(hash));
                if (result != "OK")
                    LogProvider.Log("Unable to verify session: " + result);
            }

            var parser = new AsnKeyParser(packet.PublicKey);
            var key = parser.ParseRSAPublicKey();

            // Encrypt shared secret and verification token
            var crypto = new RSACryptoServiceProvider();
            crypto.ImportParameters(key);
            var encryptedSharedSecret = crypto.Encrypt(client.SharedSecret, false);
            var encryptedVerification = crypto.Encrypt(packet.VerificationToken, false);
            var response = new EncryptionKeyResponsePacket(encryptedSharedSecret, encryptedVerification);
            client.SendPacket(response);
        }
Example #2
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);
            }
        }
Example #3
0
        /// <summary>
        /// Genera _bytEncriptado: Es unByte[] con el contenido de llavePublica RSA encriptada (bytes) y contenido Encriptado Simetrico 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAsimEncriptar_Click(object sender, EventArgs e)
        {
            byte[] _bytEncriptado = null;
            System.Security.Cryptography.CspParameters csp = new CspParameters();
            csp.KeyContainerName = "pepe";
            //Creamos una instancia del encritador publico 
            RSACryptoServiceProvider _objEncriptadorPublicoRSA = new RSACryptoServiceProvider(csp);
            //Le asignamos la llave genarada 
            _objEncriptadorPublicoRSA.FromXmlString(this.txtAsimLlavePublica.Text);

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

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

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

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

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

        }
Example #4
0
        /// <summary>
        /// Start network encryption. Automatically called by Login() if the server requests encryption.
        /// </summary>
        /// <returns>True if encryption was successful</returns>
        private bool StartEncryption(string uuid, string sessionID, byte[] token, string serverIDhash, byte[] serverKey)
        {
            System.Security.Cryptography.RSACryptoServiceProvider RSAService = CryptoHandler.DecodeRSAPublicKey(serverKey);
            byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();

            if (Settings.DebugMessages)
            {
                ConsoleIO.WriteLineFormatted("§8Crypto keys & hash generated.");
            }

            if (serverIDhash != "-")
            {
                Console.WriteLine("Checking Session...");
                if (!ProtocolHandler.SessionCheck(uuid, sessionID, CryptoHandler.getServerHash(serverIDhash, serverKey, secretKey)))
                {
                    handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, "Failed to check session.");
                    return(false);
                }
            }

            //Encrypt the data
            byte[] key_enc   = dataTypes.GetArray(RSAService.Encrypt(secretKey, false));
            byte[] token_enc = dataTypes.GetArray(RSAService.Encrypt(token, false));

            //Encryption Response packet
            SendPacket(0x01, dataTypes.ConcatBytes(key_enc, token_enc));

            //Start client-side encryption
            socketWrapper.SwitchToEncrypted(secretKey);

            //Process the next packet
            int         packetID   = -1;
            List <byte> packetData = new List <byte>();

            while (true)
            {
                ReadNextPacket(ref packetID, packetData);
                if (packetID == 0x00) //Login rejected
                {
                    handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, ChatParser.ParseText(dataTypes.ReadNextString(packetData)));
                    return(false);
                }
                else if (packetID == 0x02) //Login successful
                {
                    login_phase = false;

                    if (!pForge.CompleteForgeHandshake())
                    {
                        return(false);
                    }

                    StartUpdating();
                    return(true);
                }
                else
                {
                    HandlePacket(packetID, packetData);
                }
            }
        }
        public override void HandlePacket(Proxy proxy)
        {
            // Interact with the remote server
            proxy.RemoteSharedKey = new byte[16];
            RandomNumberGenerator random = RandomNumberGenerator.Create();
            random.GetBytes(proxy.RemoteSharedKey);

            AsnKeyParser keyParser = new AsnKeyParser(PublicKey);
            var key = keyParser.ParseRSAPublicKey();

            var cryptoService = new RSACryptoServiceProvider();
            cryptoService.ImportParameters(key);
            byte[] encryptedSharedSecret = cryptoService.Encrypt(proxy.RemoteSharedKey, false);
            byte[] encryptedVerify = cryptoService.Encrypt(VerifyToken, false);

            // Construct an 0xFC packet to send the server
            proxy.RemoteEncryptionResponse = new byte[] { 0xFC }
                .Concat(DataUtility.CreateInt16((short)encryptedSharedSecret.Length))
                .Concat(encryptedSharedSecret)
                .Concat(DataUtility.CreateInt16((short)encryptedVerify.Length))
                .Concat(encryptedVerify).ToArray();

            if (ServerId != "-")
            {
                // Generate session hash
                byte[] hashData = Encoding.ASCII.GetBytes(ServerId)
                    .Concat(proxy.RemoteSharedKey)
                    .Concat(PublicKey).ToArray();
                var hash = Cryptography.JavaHexDigest(hashData);
                var webClient = new WebClient();
                string result = webClient.DownloadString("http://session.minecraft.net/game/joinserver.jsp?user="******"&sessionId=" + Uri.EscapeUriString(proxy.Settings.UserSession) +
                    "&serverId=" + Uri.EscapeUriString(hash));
                if (result != "OK")
                    Console.WriteLine("Warning: Unable to login as user " + proxy.Settings.Username + ", expect mixed results.");
            }

            // Interact with the local client
            var verifyToken = new byte[4];
            var csp = new RNGCryptoServiceProvider();
            csp.GetBytes(verifyToken);

            AsnKeyBuilder.AsnMessage encodedKey = AsnKeyBuilder.PublicKeyToX509(Proxy.ServerKey);

            // Construct an 0xFD to send the client
            byte[] localPacket = new[] { PacketId }
                .Concat(DataUtility.CreateString("-"))
                .Concat(DataUtility.CreateInt16((short)encodedKey.GetBytes().Length))
                .Concat(encodedKey.GetBytes())
                .Concat(DataUtility.CreateInt16((short)verifyToken.Length))
                .Concat(verifyToken).ToArray();
            proxy.LocalSocket.BeginSend(localPacket, 0, localPacket.Length, SocketFlags.None, null, null);

            base.HandlePacket(proxy);
        }
        private bool StartEncryption(string uuid, string username, string sessionID, byte[] token, string serverIDhash, byte[] serverKey)
        {
            System.Security.Cryptography.RSACryptoServiceProvider RSAService = CryptoHandler.DecodeRSAPublicKey(serverKey);
            byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();

            if (Settings.DebugMessages)
            {
                ConsoleIO.WriteLineFormatted("§8Crypto keys & hash generated.");
            }

            if (serverIDhash != "-")
            {
                Console.WriteLine("Checking Session...");
                if (!ProtocolHandler.SessionCheck(uuid, sessionID, CryptoHandler.getServerHash(serverIDhash, serverKey, secretKey)))
                {
                    handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, "Failed to check session.");
                    return(false);
                }
            }

            //Encrypt the data
            byte[] key_enc   = RSAService.Encrypt(secretKey, false);
            byte[] token_enc = RSAService.Encrypt(token, false);
            byte[] keylen    = BitConverter.GetBytes((short)key_enc.Length);
            byte[] tokenlen  = BitConverter.GetBytes((short)token_enc.Length);

            Array.Reverse(keylen);
            Array.Reverse(tokenlen);

            //Building the packet
            byte[] data = new byte[5 + (short)key_enc.Length + (short)token_enc.Length];
            data[0] = 0xFC;
            keylen.CopyTo(data, 1);
            key_enc.CopyTo(data, 3);
            tokenlen.CopyTo(data, 3 + (short)key_enc.Length);
            token_enc.CopyTo(data, 5 + (short)key_enc.Length);

            //Send it back
            Send(data);

            //Getting the next packet
            byte[] pid = new byte[1];
            Receive(pid, 0, 1, SocketFlags.None);
            if (pid[0] == 0xFC)
            {
                readData(4);
                s         = CryptoHandler.getAesStream(c.GetStream(), secretKey);
                encrypted = true;
                return(true);
            }
            else
            {
                ConsoleIO.WriteLineFormatted("§8Invalid response to StartEncryption packet");
                return(false);
            }
        }
Example #7
0
        /// <summary>
        /// 由于RSA的rgb参数不能超过字符串长度为117,进行分截加密,获取公钥
        /// </summary>
        /// <param name="str">The STR.</param>
        /// <returns></returns>
        public static string RSAEncrypt(string str, string publcikeypath)
        {
            string ls_str = string.Empty;
            string ls_temp = string.Empty;
            string ls_encrypt_str = string.Empty;
            string publickey;
            byte[] byte_encrypt;
            int ll_num = 0;
            ls_str = str;
            System.Text.Encoding utf8 = new System.Text.UTF8Encoding();
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            try
            {
                StreamReader reader = new StreamReader(publcikeypath);
                publickey = reader.ReadToEnd();
                RSA.FromXmlString(publickey);
            }
            catch (Exception ex)
            {
                MessageBox.Show("加密文件没有在当前执行目录:" + ex.Message);
                return string.Empty;
            }

            if (ls_str == string.Empty || ls_str == "")
                return ls_encrypt_str;
            do
            {
                if (ls_str.Length > 100)
                {
                    ls_temp = ls_str.Substring(0, 100);
                    ls_str = ls_str.Substring(100);
                    byte_encrypt = utf8.GetBytes(ls_temp);
                    byte_encrypt = RSA.Encrypt(byte_encrypt, false);
                    ls_temp = System.Convert.ToBase64String(byte_encrypt);
                    ll_num = ll_num + 1;
                    ls_encrypt_str = ls_encrypt_str + "<" + ll_num.ToString() + ">" + ls_temp + "</" + ll_num.ToString() + ">";
                }
                else
                {
                    ls_temp = ls_str;
                    byte_encrypt = utf8.GetBytes(ls_temp);
                    byte_encrypt = RSA.Encrypt(byte_encrypt, false);
                    ls_temp = System.Convert.ToBase64String(byte_encrypt);
                    ll_num = ll_num + 1;
                    ls_encrypt_str = ls_encrypt_str + "<" + ll_num.ToString() + ">" + ls_temp + "</" + ll_num.ToString() + ">";
                    break;
                }

            } while (2 > 1);
            return ls_encrypt_str;

        }
        /// <summary>
        /// Start network encryption. Automatically called by Login() if the server requests encryption.
        /// </summary>
        /// <returns>True if encryption was successful</returns>

        private bool StartEncryption(string uuid, string sessionID, byte[] token, string serverIDhash, byte[] serverKey)
        {
            System.Security.Cryptography.RSACryptoServiceProvider RSAService = CryptoHandler.DecodeRSAPublicKey(serverKey);
            byte[] secretKey = CryptoHandler.GenerateAESPrivateKey();

            ConsoleIO.WriteLineFormatted("§8Crypto keys & hash generated.");

            if (serverIDhash != "-")
            {
                Console.WriteLine("Checking Session...");
                if (!ProtocolHandler.SessionCheck(uuid, sessionID, CryptoHandler.getServerHash(serverIDhash, serverKey, secretKey)))
                {
                    handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, "Failed to check session.");
                    return(false);
                }
            }

            //Encrypt the data
            byte[] key_enc   = RSAService.Encrypt(secretKey, false);
            byte[] token_enc = RSAService.Encrypt(token, false);
            byte[] key_len   = BitConverter.GetBytes((short)key_enc.Length); Array.Reverse(key_len);
            byte[] token_len = BitConverter.GetBytes((short)token_enc.Length); Array.Reverse(token_len);

            //Encryption Response packet
            byte[] packet_id                  = getVarInt(0x01);
            byte[] encryption_response        = concatBytes(packet_id, key_len, key_enc, token_len, token_enc);
            byte[] encryption_response_tosend = concatBytes(getVarInt(encryption_response.Length), encryption_response);
            Send(encryption_response_tosend);

            //Start client-side encryption
            s         = CryptoHandler.getAesStream(c.GetStream(), secretKey, this);
            encrypted = true;

            //Read and skip the next packet
            int  received_packet_size = readNextVarInt();
            int  received_packet_id   = readNextVarInt();
            bool encryption_success   = (received_packet_id == 0x02);

            if (received_packet_id == 0)
            {
                handler.OnConnectionLost(ChatBot.DisconnectReason.LoginRejected, ChatParser.ParseText(readNextString()));
            }
            else
            {
                readData(received_packet_size - getVarInt(received_packet_id).Length);
            }
            if (encryption_success)
            {
                StartUpdating();
            }
            return(encryption_success);
        }
Example #9
0
    public static NCryptoParms EncryptCode(string decData, string spKey) {
      NCryptoParms parms = new NCryptoParms();
      ICryptoTransform encryptor;
      CryptoStream cStream;
      MemoryStream mStream = new MemoryStream();

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

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

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

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

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

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

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

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

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

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

        parms.enc = Convert.ToBase64String(bytesOut);
      } catch {
        mStream.Close();
      }
      return parms;
    }
        public void DoEncryption()
        {
            // create a symmetric encryptor
            TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider ();
            // create IV and Key need for symmetric encryption
            TDES.GenerateIV();
            TDES.GenerateKey();

            // create an asymmetric encryptor
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider ();
            string AsymKeys = RSA.ToXmlString (true);

            // export the public and private keys to a file
            WriteKeyToFile(AsymKeys);

            // asymmetric encryption is good for
            // small data, hence, we use it to encrypted
            // IV and Key for symmetric encryption
            byte[] encryptedIV = RSA.Encrypt(TDES.IV, false);
            byte[] encryptedKey = RSA.Encrypt(TDES.Key, false);

            // convert the length of IV and Key (e.g. number of bytes used)
            // into a byte, e.g. 4 to 0000 0100
            // as default length of a Integer in .NET is 32,
            // the result byte length should be 4 bytes, i.e. 32/8
            byte[] IVSize = BitConverter.GetBytes(encryptedIV.Length);
            byte[] keySize = BitConverter.GetBytes(encryptedKey.Length);

            // write out the IV length, the key length,
            // the encrypted iv, the encrypted key and the actual
            // date to a file using the symmetric encryptor.
            using(FileStream ostream = new FileStream("encrypted.enc", FileMode.Create)){
                ostream.Write(IVSize, 0, IVSize.Length);
                ostream.Write(keySize, 0, keySize.Length);
                ostream.Write(encryptedIV, 0, encryptedIV.Length);
                ostream.Write(encryptedKey, 0, encryptedKey.Length);

                CryptoStream cstream = new CryptoStream(ostream,
                                                       TDES.CreateEncryptor(),
                                                        CryptoStreamMode.Write);

                // encrypt the data using the crypto stream
                EncryptFile(cstream);

                // close streams
                cstream.Close();
                ostream.Close();
            }
        }
        /// <summary>
        /// Metoda za asimetrično kriptiranje
        /// </summary>
        /// <param name="file"></param>
        public void AsymetriycCrypt(string file)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            StreamReader streamReader = new StreamReader("javni_kljuc.txt");
            string publicKey = streamReader.ReadToEnd();
            rsa.FromXmlString(publicKey);
            streamReader.Close();

            string record = file + ".rsa";

            FileStream fstreamU = File.OpenRead(file),
            fstreamO = new FileStream(record, FileMode.Create, FileAccess.ReadWrite);

            BinaryWriter bw = new BinaryWriter(fstreamO);

            BinaryReader binReader = new BinaryReader(fstreamU);
            byte[] bytes = binReader.ReadBytes((int)fstreamU.Length);
            binReader.Close();

            byte[] crypt = rsa.Encrypt(bytes, false);

            bw.Write(crypt);
            bw.Flush();
            bw.Close();
            bw.Dispose();

            fstreamU.Close();
            fstreamU.Dispose();
        }
        public void Run()
        {
            var _exportKey = new RSACryptoServiceProvider();
            string publicKeyXML = _exportKey.ToXmlString(false);
            string privateKeyXML = _exportKey.ToXmlString(true);

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

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

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

            string decryptedString = ByteConverter.GetString(decryptedData);
            Console.WriteLine(decryptedString); // Displays: My Secret Data!        }
        }
            public UniRx.IObservable <bool> DumpAutoLogin(string filename)
            {
                return(Observable.Range(0, 1)
                       .Select(_ => {
                    if (context.accept_equip == null)
                    {
                        throw new System.MissingFieldException("context", "accept_equip");
                    }

                    var body = new AutoLoginFile();
                    body.token = context.token;

                    using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider()) {
                        rsa.FromXmlString(context.public_key);
                        var encrypted = rsa.Encrypt(context.token_time.ToString());
                        body.password = Convert.ToBase64String(encrypted);
                    }
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(body);
                    var pbkdf = new Rfc2898DeriveBytes(json, SecureHelper.APP_SALT.GetByte(Convert.FromBase64String), 3483);
                    body.signature = Convert.ToBase64String(pbkdf.GetBytes(256));
                    JsonDB db = new JsonDB("account");
                    var obj = JToken.FromObject(body);
                    db.Put(filename, obj);
                    return true;
                }));
            }
Example #14
0
        // 暗号化
        public static byte[] Encript(String publicKey, byte[] src)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(publicKey);

            return rsa.Encrypt(src, false);
        }
Example #15
0
        /// <summary> 
        /// RSA 加密
        /// </summary> 
        /// <param name="sSource" >明文</param> 
        /// <param name="sPublicKey" >公钥</param> 
        public static string EncryptString(string sSource, string sPublicKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            string plaintext = sSource;
            rsa.FromXmlString(sPublicKey);
            byte[] cipherbytes;
            byte[] byteEn = rsa.Encrypt(Encoding.UTF8.GetBytes("a"), false);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(plaintext), false);

            StringBuilder sbString = new StringBuilder();
            for (int i = 0; i < cipherbytes.Length; i++)
            {
                sbString.Append(cipherbytes[i] + ",");
            }
            return sbString.ToString();
        }
Example #16
0
 private static byte[] cifrar(string texto, string xmlKeys)
 {
     RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
     rsa.FromXmlString(xmlKeys);
     byte[] datosEnc = rsa.Encrypt(Encoding.Default.GetBytes(texto), false);
     return datosEnc;
 }
        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;
        }
Example #18
0
        public override void Encrypt()
            {
                //RSA Rsa = new RSA();
                //base.Component.Text = Rsa.encode(base.Component.tp.Text);

                try
                {
                    UnicodeEncoding ByteConverter = new UnicodeEncoding();
                    byte[] encryptedData;
                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                    {
                        RSA.ImportParameters(RSA.ExportParameters(false));
  
                        
                        byte[] Data = ByteConverter.GetBytes(base.Component.tp.Text.ToString());
                        encryptedData = RSA.Encrypt(Data , false);
                    }
                    base.Component.Text = ByteConverter.GetString(encryptedData);
                }
                //Catch and display a CryptographicException  
                //to the console.
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                    base.Component.Text = base.Component.tp.Text.ToString();
                }
               
            }
 public string EncryptString(string inputString, int dwKeySize,
                      string xmlString)
 {
     RSACryptoServiceProvider rsaCryptoServiceProvider =
                                   new RSACryptoServiceProvider(dwKeySize);
     rsaCryptoServiceProvider.FromXmlString(xmlString);
     int keySize = dwKeySize / 8;
     byte[] bytes = Encoding.UTF32.GetBytes(inputString);
     int maxLength = keySize - 42;
     int dataLength = bytes.Length;
     int iterations = dataLength / maxLength;
     StringBuilder stringBuilder = new StringBuilder();
     for (int i = 0; i <= iterations; i++)
     {
         byte[] tempBytes = new byte[
                 (dataLength - maxLength * i > maxLength) ? maxLength :
                                               dataLength - maxLength * i];
         Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0,
                           tempBytes.Length);
         byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes,
                                                                   true);
         Array.Reverse(encryptedBytes);
         stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
     }
     return stringBuilder.ToString();
 }
Example #20
0
 public string EncryptData(string data2Encrypt, string strPublicKey)
 {
     RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
     provider.FromXmlString(strPublicKey);
     byte[] bytes = Encoding.UTF8.GetBytes(data2Encrypt);
     return Convert.ToBase64String(provider.Encrypt(bytes, false));
 }
Example #21
0
 /// <summary>
 /// 加密
 /// </summary>
 /// <param name="publicKey">公钥</param>
 /// <param name="data">要加密的字串</param>
 /// <returns></returns>
 public virtual string Encode(string publicKey, string data)
 {
     var rsa = new RSACryptoServiceProvider();
     rsa.FromXmlString(publicKey);
     var cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(data), false);
     return Convert.ToBase64String(cipherbytes);
 }
Example #22
0
        private readonly static RSAParameters PrivateParams = Rsa.ExportParameters(true); //Complete key pairs.

        /// <summary>
        /// Encrypt an input string 
        /// </summary>
        /// <param name="input">the input string to be encrpty</param>
        /// <param name="signature">the private key signature</param>
        /// <returns>A Base 64 encrypted string or empty if can't encrpyt</returns>
        public static string Encrpyt(string input, out byte[] signature)
        {
            signature = null;
            try
            {
                if (string.IsNullOrEmpty(input)) return string.Empty;
                var provider = new RSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore });
                provider.ImportParameters(PublicParams);

                var buffer = Encoding.ASCII.GetBytes(input);
                var encryptedbuffer = provider.Encrypt(buffer, false);

                var hash = new SHA1Managed();
                provider.ImportParameters(PrivateParams);
                var hashedData = hash.ComputeHash(encryptedbuffer);
                signature = provider.SignHash(hashedData, CryptoConfig.MapNameToOID("SHA1"));

                var stringBuilder = new StringBuilder();
                stringBuilder.Append(Convert.ToBase64String(encryptedbuffer));

                return stringBuilder.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
 public string EncryptString( string inputString, int dwKeySize, string xmlString )
 {
     // TODO: Add Proper Exception Handlers
     RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider( dwKeySize );
     rsaCryptoServiceProvider.FromXmlString( xmlString );
     int keySize = dwKeySize / 8;
     byte[] bytes = Encoding.UTF32.GetBytes( inputString );
     // The hash function in use by the .NET RSACryptoServiceProvider here is SHA1
     // int maxLength = ( keySize ) - 2 - ( 2 * SHA1.Create().ComputeHash( rawBytes ).Length );
     int maxLength = keySize - 42;
     int dataLength = bytes.Length;
     int iterations = dataLength / maxLength;
     StringBuilder stringBuilder = new StringBuilder();
     for( int i = 0; i <= iterations; i++ )
     {
         byte[] tempBytes = new byte[ ( dataLength - maxLength * i > maxLength ) ? maxLength : dataLength - maxLength * i ];
         Buffer.BlockCopy( bytes, maxLength * i, tempBytes, 0, tempBytes.Length );
         byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt( tempBytes, true );
         // Be aware the RSACryptoServiceProvider reverses the order of encrypted bytes after encryption and before decryption.
         // If you do not require compatibility with Microsoft Cryptographic API (CAPI) and/or other vendors.
         // Comment out the next line and the corresponding one in the DecryptString function.
         Array.Reverse( encryptedBytes );
         // Why convert to base 64?
         // Because it is the largest power-of-two base printable using only ASCII characters
         stringBuilder.Append( Convert.ToBase64String( encryptedBytes ) );
     }
     return stringBuilder.ToString();
 }
Example #24
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 #25
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 #26
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;
        }
        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 #28
0
 public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
 {
     System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider();
     rSACryptoServiceProvider.FromXmlString(xmlPublicKey);
     byte[] inArray = rSACryptoServiceProvider.Encrypt(EncryptString, false);
     return(System.Convert.ToBase64String(inArray));
 }
Example #29
0
File: RSA.cs Project: 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;
            }

        }
Example #30
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.Encrypt(DataToEncrypt, DoOAEPPadding);
                }
                return encryptedData;
            }
            //Catch and display a CryptographicException   
            //to the console. 
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
        //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 #32
0
        public byte[] Encrypt(byte[] Data, int Offset, int Length)
        {
            lock (rsa)
            {
                int ExpectedSize = (KeySize / 8) * (Length / EncChunkSize);
                using (MemoryStream stream = new MemoryStream(Data.Length + ExpectedSize))
                {
                    int LengthLeft = Length;
                    if (PublicKey != null && PublicKey.Length > 0)
                    {
                        rsa.FromXmlString(PublicKey);
                    }

                    for (int i = Offset; i < Length; i += EncChunkSize)
                    {
                        int size = i + EncChunkSize < Length ? EncChunkSize : LengthLeft;

                        byte[] temp = new byte[size];
                        Array.Copy(Data, i, temp, 0, size);
                        byte[] encrypted = rsa.Encrypt(temp, PkcsPadding);
                        stream.Write(encrypted, 0, encrypted.Length);

                        if (LengthLeft >= EncChunkSize)
                        {
                            LengthLeft -= size;
                        }
                    }
                    return(stream.ToArray());
                }
            }
        }
Example #33
0
 /// <summary>
 /// 公钥加密
 /// </summary>
 /// <param name="publichKey"></param>
 /// <param name="strData"></param>
 public static string EncryptRSA(string publicKey, string strData)
 {
     RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
     rsa.FromXmlString(publicKey);
     byte[] dataRSAed = rsa.Encrypt(Encoding.UTF8.GetBytes(strData), false);
     return CommonHelper.ByteArrayToString(dataRSAed);
 }
Example #34
0
 public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
 {
     RSACryptoServiceProvider provider1 = new RSACryptoServiceProvider();
     provider1.FromXmlString(xmlPublicKey);
     byte[] buffer1 = provider1.Encrypt(EncryptString, false);
     return Convert.ToBase64String(buffer1);
 }
Example #35
0
        /// <summary>
        /// 公開鍵を使って文字列を暗号化する
        /// </summary>
        /// <param name="str">暗号化する文字列</param>
        /// <returns>暗号化された文字列</returns>
        public static string ClientEncrypt(string str)
        {
            try
            {
                //RSACryptoServiceProviderオブジェクトの作成
                var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(KeySize);

                //公開鍵を指定
                rsa.FromXmlString(clientPublicKey);

                //暗号化する文字列をバイト配列に
                byte[] data = System.Text.Encoding.UTF8.GetBytes(str);

                //  データサイズのチェック
                if (data.Length > rsa.KeySize / 8 - 11)
                {
                    throw new Exception();
                }

                //暗号化する
                //(XP以降の場合のみ2項目にTrueを指定し、OAEPパディングを使用できる)
                //  RSACryptoServiceProvider.KeySize プロパティで取得できるキーサイズが1024ビットだとすると、暗号化されるデータの最大長は、 1024/8-11=117バイト となります。
                byte[] encryptedData = rsa.Encrypt(data, false);

                //Base64で結果を文字列に変換
                return(System.Convert.ToBase64String(encryptedData));
            }
            catch (Exception)
            {
            }

            return(null);
        }
Example #36
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 #37
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 void Main(string[] args)
 {
     byte[] key = Encoding.UTF8.GetBytes("fade3390ab9d49c88f2e0e69ed6e40af");
     System.Security.Cryptography.RSACryptoServiceProvider RSACryp = null;
     RSACryp = GetPublicKey();
     byte[] bytesEncrypted = RSACryp.Encrypt(key, false);
     var    str            = Convert.ToBase64String(bytesEncrypted);
 }
Example #39
0
 public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
 {
     System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider();
     rSACryptoServiceProvider.FromXmlString(xmlPublicKey);
     byte[] bytes   = new System.Text.UnicodeEncoding().GetBytes(m_strEncryptString);
     byte[] inArray = rSACryptoServiceProvider.Encrypt(bytes, false);
     return(System.Convert.ToBase64String(inArray));
 }
Example #40
0
 /// <summary>
 /// Encrypt data by public key.
 /// </summary>
 /// <param name="dataBytes">Need to encrypt data</param>
 /// <param name="fOEAP"></param>
 /// <returns></returns>
 public byte[] EncryptByPublicKey(byte[] dataBytes, bool fOEAP)
 {
     if (PublicRsa is null)
     {
         throw new ArgumentException("public key can not null");
     }
     return(PublicRsa.Encrypt(dataBytes, fOEAP));
 }
Example #41
0
 /// <summary>
 /// 公開鍵を使って文字列を暗号化する
 /// </summary>
 /// <param name="str">暗号化する文字列</param>
 /// <param name="publicKey">暗号化に使用する公開鍵(XML形式)</param>
 /// <returns>暗号化された文字列</returns>
 public static string Encrypt(string str, string publicKey)
 {
     System.Security.Cryptography.RSACryptoServiceProvider rsa =
         new System.Security.Cryptography.RSACryptoServiceProvider();
     rsa.FromXmlString(publicKey);
     byte[] data          = System.Text.Encoding.UTF8.GetBytes(str);
     byte[] encryptedData = rsa.Encrypt(data, false);
     return(System.Convert.ToBase64String(encryptedData));
 }
Example #42
0
        public string UseSystemRsaDataEncrypt(string needEncryptContent)
        {
            #region Use System Default Encrypt Mether Handler Data
            RSAParameters rsaDefineRap = ConvertPublicKeyToRsaInfo();
            string        modulus      = Convert.ToBase64String(rsaDefineRap.Modulus);
            string        exponent     = Convert.ToBase64String(rsaDefineRap.Exponent);

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

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

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

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

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

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

                    byte[] encryBytes = rsaCrypt.Encrypt(System.Text.Encoding.UTF8.GetBytes("Hello World"), false);
                    return(Convert.ToBase64String(encryBytes));
                }
            #endregion
        }
Example #43
0
 /// <summary>
 /// RSA加密数据
 /// </summary>
 /// <param name="express">要加密数据</param>
 /// <param name="KeyContainerName">密匙容器的名称</param>
 /// <returns></returns>
 public static string RSAEncryption(string express, string KeyContainerName = null)
 {
     System.Security.Cryptography.CspParameters param = new System.Security.Cryptography.CspParameters();
     param.KeyContainerName = KeyContainerName ?? "default"; //密匙容器的名称,保持加密解密一致才能解密成功
     using (System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(param))
     {
         byte[] plaindata   = System.Text.Encoding.ASCII.GetBytes(express); //将要加密的字符串转换为字节数组
         byte[] encryptdata = rsa.Encrypt(plaindata, false);                //将加密后的字节数据转换为新的加密字节数组
         return(Convert.ToBase64String(encryptdata));                       //将加密后的字节数组转换为字符串
     }
 }
Example #44
0
        public static string encrypt(string elementToEncrypt, string pathPrivateKey)
        {
            string pem = System.IO.File.ReadAllText(pathPrivateKey);

            byte[] Buffer = getBytesFromPEMFile(pem, "PUBLIC 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(elementToEncrypt); // Convert.FromBase64String(elementToEncrypt);
            byte[] encryptedMessageByte = rsa.Encrypt(text, false);
            return(Convert.ToBase64String(encryptedMessageByte));
        }
Example #45
0
        /// <summary>
        /// 公開鍵を使って暗号化する
        /// </summary>
        /// <param name="str">暗号化するデータ</param>
        /// <returns>暗号化されたデータ</returns>
        public static byte[] EncryptBigData(byte[] targetData)
        {
            try
            {
                //RSACryptoServiceProviderオブジェクトの作成
                var rsa = new System.Security.Cryptography.RSACryptoServiceProvider(KeySize);

                //公開鍵を指定
                rsa.FromXmlString(publicKey);

                int blockNumber = targetData.Length;
                blockNumber /= rsa.KeySize / 8 - 11;
                if (targetData.Length % (rsa.KeySize / 8 - 11) != 0)
                {
                    blockNumber++;
                }
                int totalSize = blockNumber * (rsa.KeySize / 8);

                byte[] resultData = new byte[totalSize];

                for (int index = 0; index < blockNumber; index++)
                {
                    //暗号化する
                    //(XP以降の場合のみ2項目にTrueを指定し、OAEPパディングを使用できる)
                    //  RSACryptoServiceProvider.KeySize プロパティで取得できるキーサイズが1024ビットだとすると、暗号化されるデータの最大長は、 1024/8-11=117バイト となります。
                    int tempSize = rsa.KeySize / 8 - 11;
                    if (targetData.Length - index * tempSize < tempSize)
                    {
                        tempSize = targetData.Length - index * tempSize;
                    }
                    byte[] tempData = new byte[tempSize];
                    Buffer.BlockCopy(targetData, index * (rsa.KeySize / 8 - 11), tempData, 0, tempSize);
                    byte[] encryptedData = rsa.Encrypt(tempData, false);
                    Buffer.BlockCopy(encryptedData, 0, resultData, index * (rsa.KeySize / 8), encryptedData.Length);
                }

                return(resultData);
            }
            catch (Exception)
            {
            }

            return(null);
        }
Example #46
0
        public void RSA_SendString(String _TxData)
        {
            //Pad the string length with whitespace to make a size evenly divisible into blocks:
            int toAdd = _TxData.Length % BlockSize;

            for (int i = 0; i < toAdd; i++)
            {
                _TxData = _TxData.Insert(_TxData.Length, " ");
            }

            //Figure out how many blocks need to be transmitted:
            int numBlocks = _TxData.Length / BlockSize;

            //Start the message transmit:
            m_CommStack.StartEncryptedMessage(numBlocks);

            //Encrypt the blocks and dump into the output stream:
            for (int i = 0; i < numBlocks; i++)
            {
                char[] temp  = _TxData.ToCharArray(i * BlockSize, BlockSize);
                byte[] bytes = new byte[BlockSize];

                int j = 0;
                foreach (char c in temp)
                {
                    bytes[j++] = Convert.ToByte(c);
                }

                byte[] encrypted = m_RSAEncryptSvc.Encrypt(bytes, false);

                //Transmit the encrypted block.
                m_CommStack.TransmitEncryptedBlock(BlockSize, encrypted);
            }

            //Transmit end encrypted message
            m_CommStack.EndEncryptedMessage();
        }
Example #47
0
        public string Encrypt(string publicKey, string plainText)
        {
            System.Security.Cryptography.CspParameters            cspParams   = null;
            System.Security.Cryptography.RSACryptoServiceProvider rsaProvider = null;
            byte[] plainBytes     = null;
            byte[] encryptedBytes = null;

            string result = "";

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

                rsaProvider.FromXmlString(publicKey);

                plainBytes     = System.Text.Encoding.UTF8.GetBytes(plainText);
                encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
                result         = Convert.ToBase64String(encryptedBytes);
            }
            catch (Exception ex) { Log(ex.Message); }
            return(result);
        }