Exemple #1
0
        /*
         *  Function: EncryptByPublicKey()
         *  Key Type: PEM
         *  Description: Encrypt data by public key, corresponding to function DecryptByPrivateKey()
         */
        public static string EncryptByPublicKey(string plainText, string publicKey, string paddingMode)
        {
            byte[] plainByte = Encoding.UTF8.GetBytes(plainText);
            IAsymmetricBlockCipher encoding;

            switch (paddingMode)
            {
            case MessageDefinition.RSAPaddingMode01:
                encoding = new Pkcs1Encoding(new RsaEngine());
                break;

            case MessageDefinition.RSAPaddingMode02:
                encoding = new ISO9796d1Encoding(new RsaEngine());
                break;

            default:
                encoding = new OaepEncoding(new RsaEngine());
                break;
            }
            encoding.Init(true, ReadPublicKey(publicKey));

            int         blockSize = encoding.GetInputBlockSize();
            List <byte> output    = new List <byte>();

            for (int chunkPositon = 0; chunkPositon < plainByte.Length; chunkPositon += blockSize)
            {
                int chunkSize = Math.Min(blockSize, plainByte.Length - chunkPositon);
                output.AddRange(encoding.ProcessBlock(plainByte, chunkPositon, chunkSize));
            }
            return(Convert.ToBase64String(output.ToArray()));
        }
Exemple #2
0
        private static byte[] DecodeSymmetricKey(string label, string privateKeyPath, string ciphertext)
        {
            byte[] cipherTextBytes = HexToByte(ciphertext);
            byte[] labelBytes      = Encoding.UTF8.GetBytes(label);

            PemReader pr = new PemReader(File.OpenText(privateKeyPath));
            AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pr.ReadObject();

            OaepEncoding eng = new OaepEncoding(new RsaEngine(), new Sha256Digest(), new Sha256Digest(), labelBytes);

            eng.Init(false, keys.Private);

            int         length         = cipherTextBytes.Length;
            int         blockSize      = eng.GetInputBlockSize();
            List <byte> plainTextBytes = new List <byte>();

            for (int chunkPosition = 0;
                 chunkPosition < length;
                 chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                plainTextBytes.AddRange(eng.ProcessBlock(
                                            cipherTextBytes, chunkPosition, chunkSize
                                            ));
            }
            return(plainTextBytes.ToArray());
        }
        private string decrypt(string cipherText, string filepath)
        {
            byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            PemReader pr = new PemReader(
                (StreamReader)File.OpenText(filepath)
                );
            AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pr.ReadObject();


            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(false, keys.Private);

            int         length         = cipherTextBytes.Length;
            int         blockSize      = eng.GetInputBlockSize();
            List <byte> plainTextBytes = new List <byte>();

            for (int chunkPosition = 0;
                 chunkPosition < length;
                 chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                plainTextBytes.AddRange(eng.ProcessBlock(
                                            cipherTextBytes, chunkPosition, chunkSize
                                            ));
            }
            return(Encoding.UTF8.GetString(plainTextBytes.ToArray()));
        }
        // to be done
        public static string RSADecryptLong(string XmlPrivateKey, string EncryptedText)
        {
            AsymmetricKeyParameter privateKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(XmlPrivateKey));
            var decryptEngine = new OaepEncoding(new RsaEngine());

            decryptEngine.Init(false, privateKey);

            int CipherLength = decryptEngine.GetInputBlockSize();

            byte[] bytesToDecrypt = Convert.FromBase64String(EncryptedText);

            byte[] decrypted = null;

            int Times = (bytesToDecrypt.Length - 1) / CipherLength + 1;

            List <byte> decryptedCache = new List <byte>();
            int         Counter        = 0;

            while (Counter < Times)
            {
                byte[] decryptedPatch = decryptEngine.ProcessBlock(bytesToDecrypt, CipherLength * Counter, CipherLength);
                decryptedCache.AddRange(decryptedPatch);

                Counter++;
            }

            decrypted = decryptedCache.ToArray();

            return(Encoding.Default.GetString(decrypted));
        }
Exemple #5
0
        private byte[] get_encrypted_session_key(byte[] session_key)
        {
            int length = session_key.Length;

            RsaKeyParameters keys = settings.get_public_key();

            // Pure mathematical RSA implementation
            // RsaEngine eng = new RsaEngine();

            // PKCS1 v1.5 paddings
            // Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());

            // PKCS1 OAEP paddings
            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(true, keys);

            int         blockSize       = eng.GetInputBlockSize();
            List <byte> cipherTextBytes = new List <byte>();

            for (int chunkPosition = 0;
                 chunkPosition < length;
                 chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                cipherTextBytes.AddRange(eng.ProcessBlock(
                                             session_key, chunkPosition, chunkSize
                                             ));
            }
            return(cipherTextBytes.ToArray());
        }
Exemple #6
0
        public static byte[] Decrypt(byte[] data, byte[] key, byte[] encodingParam)
        {
            var pr   = new PemReader(new StringReader(StringHelper.NewString(key).Trim()));
            var keys = (AsymmetricCipherKeyPair)pr.ReadObject();

            // Pure mathematical RSA implementation
            // RsaEngine eng = new RsaEngine();

            // PKCS1 v1.5 paddings
            // Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());

            // PKCS1 OAEP paddings
            var eng = new OaepEncoding(new RsaEngine(), new Sha256Digest(), encodingParam);

            eng.Init(false, keys.Private);

            var length        = data.Length;
            var blockSize     = eng.GetInputBlockSize();
            var decryptedData = new List <byte>();

            for (var chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize)
            {
                var chunkSize = Math.Min(blockSize, length - chunkPosition);
                decryptedData.AddRange(eng.ProcessBlock(data, chunkPosition, chunkSize));
            }
            return(decryptedData.ToArray());
        }
Exemple #7
0
        /// <summary>
        /// Uses RSA Publickey to Ecrypt
        /// Requires .pem file
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns>Cypherbasestring</returns>
        protected internal static string Encrypt(string plainText)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            Org.BouncyCastle.OpenSsl.PemReader pr = new Org.BouncyCastle.OpenSsl.PemReader(
                File.OpenText(Program.tempDirectory + "\\IAPubkey.pem")
                );
            RsaKeyParameters keys = (RsaKeyParameters)pr.ReadObject();


            // PKCS1 OAEP paddings
            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(true, keys);

            // Pure mathematical RSA implementation
            int         length          = plainTextBytes.Length;
            int         blockSize       = eng.GetInputBlockSize();
            List <byte> cipherTextBytes = new List <byte>();

            for (int chunkPosition = 0;
                 chunkPosition < length;
                 chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                cipherTextBytes.AddRange(eng.ProcessBlock(
                                             plainTextBytes, chunkPosition, chunkSize
                                             ));
            }
            return(Convert.ToBase64String(cipherTextBytes.ToArray()));
        }
Exemple #8
0
        public string Decrypt(string encryptedText, string certificateKey, string privateCertificateFile)
        {
            try
            {
                byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);

                IPasswordFinder pf = new securityPasswordFinderInterface(certificateKey);
                PemReader       pr = new PemReader(
                    (StreamReader)File.OpenText(privateCertificateFile), pf
                    );

                AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pr.ReadObject();

                OaepEncoding eng = new OaepEncoding(new RsaEngine());
                eng.Init(false, keys.Private);

                int         length         = cipherTextBytes.Length;
                int         blockSize      = eng.GetInputBlockSize();
                List <byte> plainTextBytes = new List <byte>();
                for (int chunkPosition = 0;
                     chunkPosition < length;
                     chunkPosition += blockSize)
                {
                    int chunkSize = Math.Min(blockSize, length - chunkPosition);
                    plainTextBytes.AddRange(eng.ProcessBlock(
                                                cipherTextBytes, chunkPosition, chunkSize
                                                ));
                }
                return(Encoding.UTF8.GetString(plainTextBytes.ToArray()));
            } catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #9
0
        public byte[] Decrypt(byte[] data)
        {
            if (_keyPrivate == null)
            {
                throw new Exception("Private key not set");
            }

            var engine = new OaepEncoding(new RsaEngine());

            engine.Init(false, _keyPrivate);

            int length         = data.Length;
            int blockSize      = engine.GetInputBlockSize();
            var decryptedBytes = new List <byte>();

            for (int chunkPosition = 0;
                 chunkPosition < length;
                 chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                decryptedBytes.AddRange(engine.ProcessBlock(
                                            data, chunkPosition, chunkSize
                                            ));
            }
            return(decryptedBytes.ToArray());
        }
        public static string DecryptRsa(byte[] encrypted, string key, Encoding encoding)
        {
            using (var privateKeyPem = new StringReader(key))
            {
                var rsa = new OaepEncoding(new RsaEngine());
                var privateKeyReader = new PemReader(privateKeyPem);
                var keyPair          = (AsymmetricCipherKeyPair)privateKeyReader.ReadObject();
                rsa.Init(false, keyPair.Private);


                var blockDataSize = rsa.GetInputBlockSize();

                var decrypted = encrypted
                                .Buffer(blockDataSize)
                                .Select(x =>
                {
                    var arr = x.ToArray();
                    return(rsa.ProcessBlock(arr, 0, arr.Length));
                })
                                .SelectMany(x => x)
                                .ToArray();

                return(encoding.GetString(decrypted));
            }
        }
        public static byte[] EncryptRsa(string plainText, string key, Encoding encoding)
        {
            using (var publicKeyPem = new StringReader(key))
            {
                var publicKeyReader = new PemReader(publicKeyPem);
                var publicKeyParam  = (AsymmetricKeyParameter)publicKeyReader.ReadObject();

                var rsa = new OaepEncoding(new RsaEngine());

                rsa.Init(true, publicKeyParam);

                var blockDataSize = rsa.GetInputBlockSize();

                var encrypted = encoding
                                .GetBytes(plainText)
                                .Buffer(blockDataSize)
                                .Select(x =>
                {
                    var arr = x.ToArray();
                    return(rsa.ProcessBlock(arr, 0, arr.Length));
                })
                                .SelectMany(x => x)
                                .ToArray();

                return(encrypted);
            }
        }
Exemple #12
0
        public static byte[] Encrypt(byte[] data, byte[] key)
        {
            var pr   = new PemReader(new StringReader(StringHelper.NewString(key).Trim()));
            var keys = (RsaKeyParameters)pr.ReadObject();

            // Pure mathematical RSA implementation
            // RsaEngine eng = new RsaEngine();

            // PKCS1 v1.5 paddings
            // Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());

            // PKCS1 OAEP paddings
            var eng = new OaepEncoding(new RsaEngine());

            eng.Init(true, keys);

            var length = data.Length;

            var blockSize     = eng.GetInputBlockSize();
            var encryptedData = new List <byte>();

            for (var chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize)
            {
                var chunkSize = Math.Min(blockSize, length - chunkPosition);
                encryptedData.AddRange(eng.ProcessBlock(data, chunkPosition, chunkSize));
            }
            return(encryptedData.ToArray());
        }
        ///
        private string encrypt(string plainText, string filepath)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            PemReader pr = new PemReader(
                (StreamReader)File.OpenText(filepath)
                );
            RsaKeyParameters keys = (RsaKeyParameters)pr.ReadObject();


            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(true, keys);

            int         length          = plainTextBytes.Length;
            int         blockSize       = eng.GetInputBlockSize();
            List <byte> cipherTextBytes = new List <byte>();

            for (int chunkPosition = 0;
                 chunkPosition < length;
                 chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                cipherTextBytes.AddRange(eng.ProcessBlock(
                                             plainTextBytes, chunkPosition, chunkSize
                                             ));
            }
            return(Convert.ToBase64String(cipherTextBytes.ToArray()));
        }
Exemple #14
0
        private string encryptPin(string pin, UInt64 iterator)
        {
            var pinTokenBytes = Convert.FromBase64String(pinToken);
            var pr            = new PemReader(new StringReader(privateKey));
            var keys          = (AsymmetricCipherKeyPair)pr.ReadObject();

            var eng = new OaepEncoding(new RsaEngine(), new Sha256Digest(), new Sha256Digest(),
                                       Encoding.UTF8.GetBytes(sessionId));

            eng.Init(false, keys.Private);

            var plainTextBytes = new List <byte>();
            var blockSize      = eng.GetInputBlockSize();

            for (var chunkPosition = 0; chunkPosition < pinTokenBytes.Length; chunkPosition += blockSize)
            {
                var chunkSize = Math.Min(blockSize, pinTokenBytes.Length - chunkPosition);
                plainTextBytes.AddRange(eng.ProcessBlock(pinTokenBytes, chunkPosition, chunkSize));
            }

            var keyBytes = plainTextBytes.ToArray();


            var pinBytes  = new List <byte>(Encoding.ASCII.GetBytes(pin));
            var timeBytes = BitConverter.GetBytes(DateTimeOffset.UtcNow.ToUnixTimeSeconds());

            pinBytes.AddRange(timeBytes);
            var iteratorBytes = BitConverter.GetBytes(iterator);

            pinBytes.AddRange(iteratorBytes);

            var aesBlockSize = 16;
            var padding      = aesBlockSize - pinBytes.Count % aesBlockSize;
            var padText      = Enumerable.Repeat(Convert.ToByte(padding), padding);

            pinBytes.AddRange(padText);

            using (var ms = new MemoryStream())
            {
                using (var cryptor = new AesManaged())
                {
                    cryptor.Mode    = CipherMode.CBC;
                    cryptor.Padding = PaddingMode.None;

                    byte[] iv = cryptor.IV;

                    using (var cs = new CryptoStream(ms, cryptor.CreateEncryptor(keyBytes, iv), CryptoStreamMode.Write))
                    {
                        cs.Write(pinBytes.ToArray(), 0, pinBytes.Count);
                    }

                    var encrypted = ms.ToArray();
                    var result    = new byte[iv.Length + encrypted.Length];
                    Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
                    Buffer.BlockCopy(encrypted, 0, result, iv.Length, encrypted.Length);
                    return(Convert.ToBase64String(result));
                }
            }
        }
Exemple #15
0
        public virtual byte[] Decrypt(byte[] data)
        {
            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(false, DeviceKeys.Private);

            int length    = data.Length;
            int blockSize = eng.GetInputBlockSize();

            List <byte> plainText = new List <byte>();

            for (int chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                plainText.AddRange(eng.ProcessBlock(data, chunkPosition, chunkSize));
            }

            return(plainText.ToArray());
        }
Exemple #16
0
        /// <summary>
        /// Encrypts or decrypts the input <paramref name="data"/> parameter
        /// according to the <paramref name="encrypt"/> <c>bool</c> parameter, using the provided RSA <paramref name="key"/>.<para> </para>
        /// If <paramref name="encrypt"/> is set to <c>false</c>, the method will try to decrypt instead.<para> </para>
        /// This method can throw exceptions! E.g. don't pass any <c>null</c> or invalid arguments.
        /// Trying to decrypt with a <c>null</c> or public <paramref name="key"/> will throw exceptions! Make sure to wrap the call to this method in a try/catch block.
        /// </summary>
        /// <param name="data">The data to encrypt or decrypt</param>
        /// <param name="key">The RSA key to use for encryption/decryption.</param>
        /// <param name="encrypt">Should the method encrypt the passed input <paramref name="data"/> or attempt to decrypt it?</param>
        /// <returns>The processed data <c>byte[]</c> array; exceptions are thrown in case of a failure.</returns>
        private static byte[] ProcessData(byte[] data, ICipherParameters key, bool encrypt)
        {
            // PKCS1 OAEP paddings
            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(encrypt, key);

            int length    = data.Length;
            int blockSize = eng.GetInputBlockSize();

            List <byte> processedBytes = new List <byte>(length);

            for (int chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                processedBytes.AddRange(eng.ProcessBlock(data, chunkPosition, chunkSize));
            }

            return(processedBytes.ToArray());
        }
Exemple #17
0
        public void loadKey(String filein, String privateKeyFile)
        {
            byte[] cipherTextBytes = File.ReadAllBytes(filein);

            PemReader pr = new PemReader(
                (StreamReader)File.OpenText(privateKeyFile)
                ); //"./private.pem"
            AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pr.ReadObject();

            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(false, keys.Private);

            int         length         = cipherTextBytes.Length;
            int         blockSize      = eng.GetInputBlockSize();
            List <byte> plainTextBytes = new List <byte>();

            for (int chunkPosition = 0;
                 chunkPosition < length;
                 chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                plainTextBytes.AddRange(eng.ProcessBlock(
                                            cipherTextBytes, chunkPosition, chunkSize
                                            ));
            }

            //Inicializar encryptor
            var aes = new AesCryptoServiceProvider();

            //aes.GenerateKey();
            byte[] clave = plainTextBytes.ToArray();
            byte[] iv    = Convert.FromBase64String("Enf3G3rTMC7lwBJmtVcRvQ==");

            aes       = new AesCryptoServiceProvider();
            encryptor = aes.CreateEncryptor(clave, iv);
            decryptor = aes.CreateDecryptor(clave, iv);

            AESKey = Convert.ToBase64String(plainTextBytes.ToArray());
        }
Exemple #18
0
        private byte[] get_plain_session_key(byte[] cipherTextBytes)
        {
            RsaPrivateCrtKeyParameters keys = settings.get_private_key();


            // Pure mathematical RSA implementation
            // RsaEngine eng = new RsaEngine();

            // PKCS1 v1.5 paddings
            // Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());

            // PKCS1 OAEP paddings
            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(false, keys);

            int length    = cipherTextBytes.Length;
            int blockSize = eng.GetInputBlockSize();

            byte[] decipheredBytes = eng.ProcessBlock(cipherTextBytes, 0, length);
            return(decipheredBytes);
        }
Exemple #19
0
        public static string Encrypt(string plainText, string key)
        {
            string encrypted = string.Empty;

            if (!string.IsNullOrEmpty(plainText))
            {
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

                PemReader        pr   = new PemReader(new StringReader(key));
                RsaKeyParameters keys = (RsaKeyParameters)pr.ReadObject();

                // Pure mathematical RSA implementation
                // RsaEngine eng = new RsaEngine();

                // PKCS1 v1.5 paddings
                // Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());

                // PKCS1 OAEP paddings
                OaepEncoding eng = new OaepEncoding(new RsaEngine());
                eng.Init(true, keys);

                int         length          = plainTextBytes.Length;
                int         blockSize       = eng.GetInputBlockSize();
                List <byte> cipherTextBytes = new List <byte>();
                for (int chunkPosition = 0;
                     chunkPosition < length;
                     chunkPosition += blockSize)
                {
                    int chunkSize = Math.Min(blockSize, length - chunkPosition);
                    cipherTextBytes.AddRange(eng.ProcessBlock(
                                                 plainTextBytes, chunkPosition, chunkSize
                                                 ));
                }
                encrypted = Convert.ToBase64String(cipherTextBytes.ToArray());
            }

            return(encrypted);
        }
Exemple #20
0
        public void saveKey(String fileout, String publicKeyFile)
        {
            byte[] plainTextBytes = Convert.FromBase64String(AESKey);

            PemReader pr = new PemReader(
                (StreamReader)File.OpenText(publicKeyFile)
                ); //"./public.pem"
            RsaKeyParameters keys = (RsaKeyParameters)pr.ReadObject();

            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(true, keys);

            int         length          = plainTextBytes.Length;
            int         blockSize       = eng.GetInputBlockSize();
            List <byte> cipherTextBytes = new List <byte>();

            for (int chunkPosition = 0;
                 chunkPosition < length;
                 chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                cipherTextBytes.AddRange(eng.ProcessBlock(
                                             plainTextBytes, chunkPosition, chunkSize
                                             ));
            }
            //Inicializar encryptor
            var aes = new AesCryptoServiceProvider();

            //aes.GenerateKey();
            byte[] clave = plainTextBytes.ToArray();
            byte[] iv    = Convert.FromBase64String("Enf3G3rTMC7lwBJmtVcRvQ==");

            aes       = new AesCryptoServiceProvider();
            encryptor = aes.CreateEncryptor(clave, iv);
            decryptor = aes.CreateDecryptor(clave, iv);
            File.WriteAllBytes(fileout, cipherTextBytes.ToArray());
        }
Exemple #21
0
        public static string Decrypt(string cipherText, string key)
        {
            string decrypted = string.Empty;

            if (!string.IsNullOrEmpty(cipherText))
            {
                byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

                PemReader pr = new PemReader(new StringReader(key));
                AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pr.ReadObject();

                // Pure mathematical RSA implementation
                // RsaEngine eng = new RsaEngine();

                // PKCS1 v1.5 paddings
                // Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());

                // PKCS1 OAEP paddings
                OaepEncoding eng = new OaepEncoding(new RsaEngine());
                eng.Init(false, keys.Private);

                int         length         = cipherTextBytes.Length;
                int         blockSize      = eng.GetInputBlockSize();
                List <byte> plainTextBytes = new List <byte>();
                for (int chunkPosition = 0;
                     chunkPosition < length;
                     chunkPosition += blockSize)
                {
                    int chunkSize = Math.Min(blockSize, length - chunkPosition);
                    plainTextBytes.AddRange(eng.ProcessBlock(
                                                cipherTextBytes, chunkPosition, chunkSize
                                                ));
                }
                decrypted = Encoding.UTF8.GetString(plainTextBytes.ToArray());
            }

            return(decrypted);
        }