/// <summary>
        /// Encrypts the data with RSA oaep SHA 512
        /// </summary>
        /// <param name="key">The RSA public keys</param>
        /// <param name="data">Data to encrypt</param>
        /// <returns>Encrypted data</returns>
        public static byte[] RsaEncrypt(AsymmetricKeyParameter key, byte[] data)
        {
            var encryptEngine = new OaepEncoding(new RsaEngine(), new Sha512Digest());

            encryptEngine.Init(true, key);
            return(encryptEngine.ProcessBlock(data, 0, data.Length));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Creates an asymmetric algorithm instance (RSA) with the public key of this instance,
        /// ready for encryption
        /// </summary>
        /// <returns></returns>
        public IAsymmetricBlockCipher CreateRSAEncrypter()
        {
            if (_keyParams.AlgorithmId == TPMAlgorithmId.TPM_ALG_RSA && _keyParams.EncScheme == TPMEncScheme.TPM_ES_RSAESOAEP_SHA1_MGF1)
            {
                IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha1Digest(), Encoding.ASCII.GetBytes("TCPA"));

                RsaKeyParameters parameters =
                    new RsaKeyParameters(false,
                                         new BigInteger(1, _publicKey.Pubkey),
                                         new BigInteger(1, ((TPMRSAKeyParams)_keyParams.Params).GetExponent()));

                cipher.Init(true, parameters);

                return(cipher);
            }
            else if (_keyParams.AlgorithmId == TPMAlgorithmId.TPM_ALG_RSA && _keyParams.EncScheme == TPMEncScheme.TPM_ES_RSAESPKCSv15)
            {
                IAsymmetricBlockCipher cipher = new Pkcs1Encoding(new RsaEngine());

                RsaKeyParameters parameters =
                    new RsaKeyParameters(false,
                                         new BigInteger(1, _publicKey.Pubkey),
                                         new BigInteger(1, ((TPMRSAKeyParams)_keyParams.Params).GetExponent()));

                cipher.Init(true, parameters);

                return(cipher);
            }
            else
            {
                throw new NotSupportedException(string.Format("Algorithm '{0}' with '{1}' is not supported", _keyParams.AlgorithmId, _keyParams.EncScheme));
            }
        }
Ejemplo n.º 3
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());
        }
Ejemplo n.º 4
0
 internal static string Decode(string data)
 {
     try
     {
         X509Certificate k;
         // read in the certificate
         using (var textReader = File.OpenText("public.cer"))
         {
             // I'm assuming here that the certificate is PEM-encoded.
             var pemReader = new PemReader(textReader);
             k = (X509Certificate)pemReader.ReadObject();
         }
         // un-base64 the input
         var dataBytes = Convert.FromBase64String(data);
         // what php openssl_public_decrypt does
         var cipher = new OaepEncoding(new RsaEngine());
         cipher.Init(false, k.GetPublicKey());
         var returnBytes = cipher.ProcessBlock(dataBytes, 0, dataBytes.Length);
         // What is the character-encoding of the bytes? UTF-8?
         return(Encoding.UTF8.GetString(returnBytes));
     }
     catch (Exception ex)
     {
         return("Failed:" + ex.Message);
     }
 }
Ejemplo n.º 5
0
        // 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));
        }
Ejemplo n.º 6
0
        public static byte[] Decrypt(byte[] data, AsymmetricKeyParameter key)
        {
            var cipher = new OaepEncoding(new RsaEngine());

            cipher.Init(false, key);
            return(cipher.ProcessBlock(data, 0, data.Length));
        }
Ejemplo n.º 7
0
        private void EncDec(
            string label,
            RsaKeyParameters pubParameters,
            RsaKeyParameters privParameters,
            byte[]                              seed,
            byte[]                              input,
            byte[]                              output)
        {
            IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());

            cipher.Init(true, new ParametersWithRandom(pubParameters, new VecRand(seed)));

            byte[] outBytes = cipher.ProcessBlock(input, 0, input.Length);

            for (int i = 0; i != output.Length; i++)
            {
                if (outBytes[i] != output[i])
                {
                    Fail(label + " failed encryption");
                }
            }

            cipher.Init(false, privParameters);

            outBytes = cipher.ProcessBlock(output, 0, output.Length);

            for (int i = 0; i != input.Length; i++)
            {
                if (outBytes[i] != input[i])
                {
                    Fail(label + " failed decoding");
                }
            }
        }
Ejemplo n.º 8
0
        public static string RSAEncryptLong(string XmlPublicKey, string PlainText)
        {
            byte[] publicInfoByte            = Convert.FromBase64String(XmlPublicKey);
            AsymmetricKeyParameter publicKey = PublicKeyFactory.CreateKey(publicInfoByte);
            var decryptEngine = new OaepEncoding(new RsaEngine());

            decryptEngine.Init(true, publicKey);

            byte[] bytesToDecrypt = Encoding.Default.GetBytes(PlainText);

            int MaxPlainTextLength = Common.GetOEAPFixedMaxPlainTextLength(decryptEngine.GetOutputBlockSize());

            byte[] decrypted = null;

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

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

            while (Counter < Times)
            {
                int    RemainLength   = bytesToDecrypt.Length - MaxPlainTextLength * Counter;
                int    Length         = MaxPlainTextLength > RemainLength ? RemainLength : MaxPlainTextLength;
                byte[] decryptedPatch = decryptEngine.ProcessBlock(bytesToDecrypt, MaxPlainTextLength * Counter, Length);
                encryptedCache.AddRange(decryptedPatch);

                Counter++;
            }

            decrypted = encryptedCache.ToArray();

            return(Convert.ToBase64String(decrypted));
        }
Ejemplo n.º 9
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;
            }
        }
        public void btn_enc_Ok_Click(object sender, EventArgs e)
        {
            bool isChecked_enc = rb_enc_pri.Checked;

            //Encryption using private key
            if (isChecked_enc)
            {
                IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());
                cipher.Init(true, GprivateKey);
                // byte[] ciphertext = System.Text.Encoding.UTF8.GetBytes(txt_enc_writeText.Text);
                byte[] plaintext = System.Text.Encoding.UTF8.GetBytes(txt_enc_writeText.Text);

                byte[] ciphertext = cipher.ProcessBlock(plaintext, 0, plaintext.Length);

                string result = Encoding.UTF8.GetString(ciphertext);
                txt_enc_output.Text = result;

                //txt_enc_output.Text = System.Text.Encoding.UTF8.GetString(ciphertext);
            }
            //encryption using public key
            else
            {
                IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());
                cipher.Init(true, GpublicKey);
                // byte[] ciphertext = System.Text.Encoding.UTF8.GetBytes(txt_enc_writeText.Text);
                byte[] plaintext = System.Text.Encoding.UTF8.GetBytes(txt_enc_writeText.Text);

                byte[] ciphertext = cipher.ProcessBlock(plaintext, 0, plaintext.Length);

                string result = Encoding.UTF8.GetString(ciphertext);
                txt_enc_output.Text = result;
            }
        }
Ejemplo n.º 11
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());
        }
Ejemplo n.º 12
0
        public string Encrypt(string plainText, string publicCertificateFile)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);


            PemReader pr = new PemReader(
                (StreamReader)File.OpenText(publicCertificateFile)
                );
            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()));
        }
Ejemplo n.º 13
0
        public void Test_Function()
        {
            SHA256Managed hash         = new SHA256Managed();
            SecureRandom  randomNumber = new SecureRandom();

            byte[]       encodingParam = hash.ComputeHash(Encoding.UTF8.GetBytes(randomNumber.ToString()));
            string       inputMessage  = "Test Message";
            UTF8Encoding utf8enc       = new UTF8Encoding();


            byte[] inputBytes = utf8enc.GetBytes(inputMessage);


            RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();

            rsaKeyPairGnr.Init(new Org.BouncyCastle.Crypto.KeyGenerationParameters(new SecureRandom(), 1024));
            AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();

            publicKey  = (RsaKeyParameters)keyPair.Public;
            privateKey = (RsaKeyParameters)keyPair.Private;
            //string pub = GetPublicKey();
            //string priv = GetPrivateKey();
            IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha256Digest(), encodingParam);

            cipher.Init(true, publicKey);
            byte[] ciphered     = cipher.ProcessBlock(inputBytes, 0, inputMessage.Length);
            string cipheredText = utf8enc.GetString(ciphered);


            cipher.Init(false, privateKey);
            byte[] deciphered     = cipher.ProcessBlock(ciphered, 0, ciphered.Length);
            string decipheredText = utf8enc.GetString(deciphered);
        }
Ejemplo n.º 14
0
        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));
            }
        }
Ejemplo n.º 15
0
        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);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Decrypts a file key.
        /// </summary>
        /// <param name="encFileKey">The file key to decrypt.</param>
        /// <param name="userPrivateKey">The private key which should be used for the decryption.</param>
        /// <param name="password">The password which secures the private key.</param>
        /// <returns>The decrypted file key.</returns>
        /// <exception cref="Dracoon.Crypto.Sdk.InvalidFileKeyException">If the provided encrypted file key is invalid.</exception>
        /// <exception cref="Dracoon.Crypto.Sdk.InvalidKeyPairException">If the provided private key is invalid.</exception>
        /// <exception cref="Dracoon.Crypto.Sdk.InvalidPasswordException">If the provided private key password is invalid</exception>
        /// <exception cref="Dracoon.Crypto.Sdk.CryptoException">If an unexpected error in the decryption occured.</exception>
        public static PlainFileKey DecryptFileKey(EncryptedFileKey encFileKey, UserPrivateKey userPrivateKey, string password)
        {
            ValidateEncryptedFileKey(encFileKey);
            ValidateUserPrivateKey(userPrivateKey);
            ValidatePassword(password);

            AsymmetricKeyParameter privateKey = DecryptPrivateKey(userPrivateKey.PrivateKey, password);

            byte[] dFileKey;
            try {
                OaepEncoding engine = new OaepEncoding(new RsaEngine(), new Sha256Digest(), new Sha1Digest(), null);
                engine.Init(false, privateKey);
                byte[] eFileKey = Convert.FromBase64String(encFileKey.Key);
                dFileKey = engine.ProcessBlock(eFileKey, 0, eFileKey.Length);
            } catch (InvalidCipherTextException e) {
                throw new CryptoException("Could not decrypt file key. Decryption failed.", e);
            }

            PlainFileKey plainFileKey = new PlainFileKey()
            {
                Key     = Convert.ToBase64String(dFileKey),
                Iv      = encFileKey.Iv,
                Tag     = encFileKey.Tag,
                Version = encFileKey.Version
            };

            return(plainFileKey);
        }
Ejemplo n.º 17
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()));
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            // Console.WriteLine("Hello World!");

            // Variables declaration
            string SrcData;

            byte[] tmpSource;
            // byte[] tempHash;

            // Retrieve message
            Console.WriteLine("Ingrese cualquier texto: ");
            SrcData = Console.ReadLine();

            // Create byte array from source data
            tmpSource = Encoding.ASCII.GetBytes(SrcData);
            Console.WriteLine();
            Console.WriteLine("Pareja de llaves generandose...\n");

            // RSAKeyPairGenerator
            RsaKeyPairGenerator rsaKeyPairGen = new RsaKeyPairGenerator();

            rsaKeyPairGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            AsymmetricCipherKeyPair keyPair = rsaKeyPairGen.GenerateKeyPair();

            // Extract public and private key
            RsaKeyParameters PrivateKey = (RsaKeyParameters)keyPair.Private;
            RsaKeyParameters PublicKey  = (RsaKeyParameters)keyPair.Public;

            // Print public key in PEM format
            TextWriter textWriter1 = new StringWriter();
            PemWriter  pemWriter1  = new PemWriter(textWriter1);

            pemWriter1.WriteObject(PublicKey);
            pemWriter1.Writer.Flush();
            string printPublicKey = textWriter1.ToString();

            Console.WriteLine("La llave pública es: {0}", printPublicKey);
            Console.WriteLine();


            // Encryption
            IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());

            cipher.Init(true, PublicKey);
            byte[] cipherText = cipher.ProcessBlock(tmpSource, 0, tmpSource.Length);
            string result     = Encoding.UTF8.GetString(cipherText);

            Console.WriteLine("Texto cifrado: ");
            Console.WriteLine(result);
            Console.WriteLine();

            Console.WriteLine("¿Quiete descifrar el texto? Presione espacio para cifrarlo, o cualquier otra tecla si no");
            char inputChar = Console.ReadKey().KeyChar;

            if (inputChar == ' ')
            {
                Decryption(cipherText, PrivateKey);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Encrypts a file key.
        /// </summary>
        /// <param name="plainFileKey">The file key to encrypt.</param>
        /// <param name="userPublicKey">The public key which should be used for the encryption.</param>
        /// <returns>The encrypted file key.</returns>
        /// <exception cref="Dracoon.Crypto.Sdk.InvalidFileKeyException">If the provided file key is invalid.</exception>
        /// <exception cref="Dracoon.Crypto.Sdk.InvalidKeyPairException">If the provided public key is invalid.</exception>
        /// <exception cref="Dracoon.Crypto.Sdk.CryptoException">If an unexpected error occured.</exception>
        public static EncryptedFileKey EncryptFileKey(PlainFileKey plainFileKey, UserPublicKey userPublicKey)
        {
            ValidatePlainFileKey(plainFileKey);
            ValidateUserPublicKey(userPublicKey);

            AsymmetricKeyParameter pubKey = ConvertPublicKey(userPublicKey.PublicKey);

            byte[] eFileKey;
            try {
                OaepEncoding engine = new OaepEncoding(new RsaEngine(), new Sha256Digest(), new Sha1Digest(), null);
                engine.Init(true, pubKey);
                byte[] pFileKey = Convert.FromBase64String(plainFileKey.Key);
                eFileKey = engine.ProcessBlock(pFileKey, 0, pFileKey.Length);
            } catch (Exception e) {
                throw new CryptoException("Could not encrypt file key. Encryption failed.", e);
            }
            EncryptedFileKey encFileKey = new EncryptedFileKey()
            {
                Key     = Convert.ToBase64String(eFileKey),
                Iv      = plainFileKey.Iv,
                Tag     = plainFileKey.Tag,
                Version = plainFileKey.Version
            };

            return(encFileKey);
        }
Ejemplo n.º 20
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));
                }
            }
        }
Ejemplo n.º 21
0
        public static byte[] RsaOaepDeciper(byte[] data, AsymmetricKeyParameter privateKey)
        {
            IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine(), new Sha1Digest());

            cipher.Init(false, privateKey);

            return(cipher.ProcessBlock(data, 0, data.Length));
        }
Ejemplo n.º 22
0
        private void doTestOaep(RsaKeyParameters pubParameters, RsaKeyParameters privParameters)
        {
            //
            // OAEP - public encrypt, private decrypt
            //
            IAsymmetricBlockCipher eng = new OaepEncoding(new RsaEngine());

            byte[] data = Hex.Decode(input);

            eng.Init(true, pubParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            eng.Init(false, privParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed OAEP Test");
            }

            // check for oversized input
            byte[]    message             = new byte[87];
            RsaEngine rsaEngine           = new RsaEngine();
            IAsymmetricBlockCipher cipher = new OaepEncoding(rsaEngine, new Sha1Digest(), new Sha1Digest(), message);

            cipher.Init(true, new ParametersWithRandom(pubParameters, new SecureRandom()));

            try
            {
                cipher.ProcessBlock(message, 0, message.Length);

                Fail("no exception thrown");
            }
            catch (DataLengthException e)
            {
                IsTrue("message mismatch", "input data too long".Equals(e.Message));
            }
            catch (InvalidCipherTextException e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }
        }
            public void ThenCreateEncodingWithDefaultsSucceeds(string algorithmName)
            {
                // Act
                OaepEncoding encoding = EncodingFactory.Instance.Create(algorithmName);

                // Assert
                AssertEqualRSAOAPPadding(encoding.AlgorithmName);
                AssertMgf1Hash(encoding, "SHA-1");
            }
Ejemplo n.º 24
0
    protected void btnOpenEmail_Click(object sender, EventArgs e)
    {
        IAsymmetricBlockCipher cipher1 = new OaepEncoding(new RsaEngine());

        cipher1.Init(false, usr.PrivateKey);
        byte[] deciphered     = cipher1.ProcessBlock(usrEmail.cipherByteArray, 0, usrEmail.cipherByteArray.Length);
        string decipheredText = Encoding.UTF8.GetString(deciphered);

        lblDecrypted.Text = decipheredText;
    }
Ejemplo n.º 25
0
        private void RSA_OAEP_KeyWrap(IDigest digest)
        {
            IAsymmetricBlockCipher cipher        = new OaepEncoding(new RsaEngine(), digest);
            RsaKeyParameters       pubParameters = new RsaKeyParameters(false, _mKey.AsBigInteger("n"), _mKey.AsBigInteger("e"));

            cipher.Init(true, new ParametersWithRandom(pubParameters, Message.s_PRNG));

            byte[] outBytes = cipher.ProcessBlock(_payload, 0, _payload.Length);

            _rgbEncrypted = outBytes;
        }
Ejemplo n.º 26
0
        private static string EncryptId()
        {
            var cipher = new OaepEncoding(new RsaEngine());

            cipher.Init(true, CreateCipherParameters());

            var decryptedId = Encoding.UTF8.GetBytes(Id);
            var encryptedId = cipher.ProcessBlock(decryptedId, 0, decryptedId.Length);

            return(Convert.ToBase64String(encryptedId));
        }
Ejemplo n.º 27
0
        public static byte[] Decrypt(byte[] privateKey, byte[] data)
        {
            rsaCryptoProvider = new RSACryptoServiceProvider(keyLength, CSPParam);
            rsaCryptoProvider.ImportCspBlob(privateKey);
            RSAParameters           parameters = rsaCryptoProvider.ExportParameters(true);
            AsymmetricCipherKeyPair keyPair    = DotNetUtilities.GetRsaKeyPair(parameters);
            IAsymmetricBlockCipher  cipher     =
                new OaepEncoding(new RsaEngine(), new Sha1Digest(), new Sha1Digest(), new byte[0]);

            cipher.Init(false, keyPair.Private);
            return(cipher.ProcessBlock(data, 0, data.Length));
        }
Ejemplo n.º 28
0
        static void Decryption(byte[] ct, RsaKeyParameters PvtKey)
        {
            IAsymmetricBlockCipher cipher1 = new OaepEncoding(new RsaEngine());

            cipher1.Init(false, PvtKey);
            byte[] deciphered = cipher1.ProcessBlock(ct, 0, ct.Length);
            string dekodolt   = Encoding.UTF8.GetString(deciphered);

            Console.WriteLine();
            Console.WriteLine("Dekodolt szoveg:{0}", dekodolt);
            Console.WriteLine();
        }
Ejemplo n.º 29
0
        static byte[] RsaEncrypt(byte[] textBytes)
        {
            //get PublicKey pem File
            PemReader        KeyTextReader = new PemReader(File.OpenText(publicKeyFileLocation));
            RsaKeyParameters publicKey     = KeyTextReader.ReadObject() as RsaKeyParameters;

            //encrypt byte array
            IAsymmetricBlockCipher encryptCipher = new OaepEncoding(new RsaEngine());

            encryptCipher.Init(true, publicKey);
            return(encryptCipher.ProcessBlock(textBytes, 0, textBytes.Length));
        }
Ejemplo n.º 30
0
        static void Decryption(byte[] cipherText, RsaKeyParameters PrivateKey)
        {
            IAsymmetricBlockCipher decipher = new OaepEncoding(new RsaEngine());

            decipher.Init(false, PrivateKey);
            byte[] deciphered     = decipher.ProcessBlock(cipherText, 0, cipherText.Length);
            string decipheredText = Encoding.UTF8.GetString(deciphered);

            Console.WriteLine();
            Console.WriteLine("Texto decifrado: {0}", decipheredText);
            Console.WriteLine();
        }