Example #1
0
        /// <summary>
        /// Encrypts a plain array of bytes using a public key
        /// </summary>
        /// <param name="publicKey">the public key used for encryption</param>
        /// <param name="plainBytes">the plain bytes to encrypt</param>
        /// <returns></returns>
        public byte[] EncryptBytes(byte[] publicKey, byte[] plainBytes)
        {
            //CreateKeyPair public key
            var pubKey = (RsaKeyParameters)CreateAsymmetricKeyParameterFromPublicKeyInfo(publicKey);

            cipher.Init(true, pubKey);

            byte[] encrypted;
            try
            {
                //encrypt plain bytes
                encrypted = cipher.ProcessBlock(plainBytes, 0, plainBytes.Length);
            }
            catch (CryptoException exception)
            {
                if (exception.Message == "input too large for RSA cipher.")
                {
                    string message = "Encryption Failure!\n" +
                                     $"{exception.Message}\n" +
                                     "The plain data bit size cannot be greater than the selected key size.\n" +
                                     $"Key bit size: {cipher.GetInputBlockSize() * 8}\n" +
                                     $"Plain data bit size: {plainBytes.Length * 8}";
                    throw new CryptoException(message, exception);
                }
                else
                {
                    string message = "Encryption Failure!\n" +
                                     $"{exception.Message}\n" +
                                     "Contact developer.";
                    throw new CryptoException(message, exception);
                }
            }
            return(encrypted);
        }
Example #2
0
        /**
         * Generate a signature for the message we've been loaded with using the key
         * we were initialised with.
         */
        public virtual byte[] GenerateSignature()
        {
            if (!forSigning)
            {
                throw new InvalidOperationException("GenericSigner not initialised for signature generation.");
            }

            byte[] hash = new byte[digest.GetDigestSize()];
            byte[] a, b = new byte[engine.GetInputBlockSize()];
            int    n;

            digest.DoFinal(hash, 0);
            using (MemoryStream dat = new MemoryStream(hash))
            {
                using (MemoryStream bf = new MemoryStream())
                {
                    while ((n = dat.Read(b, 0, b.Length)) > 0)
                    {
                        a = engine.ProcessBlock(b, 0, n);

                        bf.Write(a, 0, a.Length);
                        Array.Clear(a, 0, a.Length);
                    }

                    Array.Clear(b, 0, b.Length);
                    b = bf.ToArray();
                }
            }

            return(b);
        }
Example #3
0
        public int GetInputBlockSize()
        {
            int baseBlockSize = engine.GetInputBlockSize();

            return(forEncryption
                                ?       baseBlockSize - HeaderLength
                                :       baseBlockSize);
        }
Example #4
0
        public int GetInputBlockSize()
        {
            int inputBlockSize = engine.GetInputBlockSize();

            if (!forEncryption)
            {
                return(inputBlockSize);
            }
            return(inputBlockSize - 10);
        }
Example #5
0
        private static void XTest(string mechanism, IAsymmetricBlockCipher encryptor, IAsymmetricBlockCipher decryptor, byte[] test)
        {
            byte[] enc  = encryptor.ProcessBlock(test, 0, test.Length);
            byte[] dec  = decryptor.ProcessBlock(enc, 0, enc.Length);
            bool   diff = !StructuralComparisons.StructuralEqualityComparer.Equals(dec, test);

            //
            Console.Write("{0}{1} max {2} bytes - src {3} bytes, enc {4} bytes - ",
                          mechanism.PadRight(32),
                          encryptor.AlgorithmName.PadRight(32),
                          encryptor.GetInputBlockSize(),
                          test.Length,
                          enc.Length);
            if (diff)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("diff");
                _diff++;
                Console.ResetColor();
            }
            else
            {
                Console.WriteLine("same");
            }
        }
Example #6
0
        public int GetInputBlockSize()
        {
            var baseBlockSize = _engine.GetInputBlockSize();

            if (_forEncryption)
            {
                return(baseBlockSize - 1 - 2 * _defHash.Length);
            }
            return(baseBlockSize);
        }
Example #7
0
    public int GetInputBlockSize()
    {
        int inputBlockSize = engine.GetInputBlockSize();

        if (forEncryption)
        {
            return(inputBlockSize - 1 - 2 * defHash.Length);
        }
        return(inputBlockSize);
    }
        public int GetInputBlockSize()
        {
            int inputBlockSize = engine.GetInputBlockSize();

            if (forEncryption)
            {
                return((inputBlockSize + 1) / 2);
            }
            return(inputBlockSize);
        }
Example #9
0
        /**
         * return the input block size. The largest message we can process
         * is (key_size_in_bits + 3)/16, which in our world comes to
         * key_size_in_bytes / 2.
         */
        public int GetInputBlockSize()
        {
            int baseBlockSize = engine.GetInputBlockSize();

            if (forEncryption)
            {
                return((baseBlockSize + 1) / 2);
            }
            else
            {
                return(baseBlockSize);
            }
        }
        public bool Setup(Func <RsaKeyParameters, bool> authorizedCallback)
        {
            var publicKey = keyPair.Public as RsaKeyParameters;
            var mod       = publicKey.Modulus.ToByteArray();
            var exp       = publicKey.Exponent.ToByteArray();

            bWriter.Write(mod.Length);
            bWriter.Write(mod);
            bWriter.Write(exp.Length);
            bWriter.Write(exp);

            mod               = bReader.ReadBytes(bReader.ReadInt32());
            exp               = bReader.ReadBytes(bReader.ReadInt32());
            publicKey         = new RsaKeyParameters(false, new BigInteger(mod), new BigInteger(exp));
            ReceivedPublicKey = publicKey;

            var authorized = true;

            if (authorizedCallback != null)
            {
                try
                {
                    authorized = authorizedCallback(publicKey);
                }
                catch
                {
                    authorized = false;
                }
            }

            if (!authorized)
            {
                bWriter.Write(false);
            }
            else
            {
                bWriter.Write(true);
                encryptEngine.Init(true, publicKey);
                outputBuffer = new byte[encryptEngine.GetInputBlockSize()];
            }

            var remoteAuthorized = bReader.ReadBoolean();

            if (!remoteAuthorized || !authorized)
            {
                Base.Close();
            }

            return(authorized && remoteAuthorized);
        }
Example #11
0
 /// <summary>
 /// Decryption using rsa private key
 /// </summary>
 /// <param name="dataBytes"></param>
 /// <param name="privateKey"></param>
 /// <returns></returns>
 public static string Decrypt(byte[] dataBytes, AsymmetricKeyParameter privateKey)
 {
     try
     {
         cipher.Init(!privateKey.IsPrivate, privateKey);
         Debug.WriteLine(cipher.GetInputBlockSize());
         byte[] decipheredBytes = cipher.ProcessBlock(dataBytes, 0, dataBytes.Length);
         return(encoding.GetString(decipheredBytes));
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.Message);
         return("0");
     }
 }
        public static byte[] ProcessCipher(byte[] data, IAsymmetricBlockCipher cipher)
        {
            if (cipher == null || data == null)
            {
                return(null);
            }

            List <byte> result    = new List <byte>();
            int         blockSize = cipher.GetInputBlockSize();

            for (int offset = 0; offset < data.Length; offset += blockSize)
            {
                int    nextBlockSize  = Math.Min(data.Length - offset, blockSize);
                byte[] processedBlock = cipher.ProcessBlock(data, offset, nextBlockSize);
                result.AddRange(processedBlock);
            }

            return(result.ToArray());
        }
        public override int Read(byte[] buffer, int offset, int count)
        {
            for (var i = 0; i < count; i++)
            {
                if (inputBuffer == null)
                {
                    var readBytes = bReader.ReadBytes(decryptEngine.GetInputBlockSize());
                    inputBuffer = decryptEngine.ProcessBlock(readBytes, 0, readBytes.Length);
                }

                buffer[offset + i] = inputBuffer[inputBufferPos];
                inputBufferPos++;

                if (inputBufferPos == inputBuffer.Length)
                {
                    inputBuffer    = null;
                    inputBufferPos = 0;
                }
            }
            return(count);
        }
 public override int GetBlockSize()
 {
     return(cipher.GetInputBlockSize());
 }
Example #15
0
        public override void Execute(string[] commandline)
        {
            if (commandline.Length < 2)
            {
                _console.Out.WriteLine("Error: [local_session_alias] not specified");
                return;
            }
            else if (commandline.Length < 3)
            {
                _console.Out.WriteLine("Error: [command] not specified");
                return;
            }

            ClientContext ctx = _console.GetValue <ClientContext> ("client_context", null);

            if (ctx == null)
            {
                _console.Out.WriteLine("No active connection was found");
                return;
            }

            string localAlias = commandline[1];

            IDictionary <string, TPMSession> tpmSessions = _console.GetValue <IDictionary <string, TPMSession> > ("tpm_sessions", null);

            if (tpmSessions == null || tpmSessions.ContainsKey(localAlias) == false)
            {
                _console.Out.WriteLine("Error: Specified local alias was not found");
                return;
            }

            if (tpmSessions[localAlias].Keystore == null)
            {
                _console.Out.WriteLine("Error: No keystore was opened");
                return;
            }

            IDictionary <string, string> arguments = _console.SplitArguments(commandline[2], 0);

            if (arguments.ContainsKey("name") == false)
            {
                _console.Out.WriteLine("Error: no key name was specified");
                return;
            }

            if (arguments.ContainsKey("data_input") == false)
            {
                _console.Out.WriteLine("Error: no data input source specified");
                return;
            }

            TPMSessionSealCommand.DataInputMode dataInputMode;

            try
            {
                dataInputMode = (TPMSessionSealCommand.DataInputMode)Enum.Parse(typeof(TPMSessionSealCommand.DataInputMode), arguments["data_input"], true);
            }
            catch (Exception)
            {
                _console.Out.WriteLine("Error: Invalid data input source");
                return;
            }

            TPMSessionSealCommand.DataOutputMode dataOutputMode;

            try
            {
                dataOutputMode = (TPMSessionSealCommand.DataOutputMode)Enum.Parse(typeof(TPMSessionSealCommand.DataOutputMode), arguments["data_output"], true);
            }
            catch (Exception)
            {
                _console.Out.WriteLine("Error: Invalid data output destination");
                return;
            }

            TPMSessionSealCommand.DataFormat inputDataFormat = TPMSessionSealCommand.DataFormat.Raw;

            if (arguments.ContainsKey("input_data_format"))
            {
                try
                {
                    inputDataFormat = (TPMSessionSealCommand.DataFormat)Enum.Parse(typeof(TPMSessionSealCommand.DataFormat), arguments["input_data_format"], true);
                }
                catch (Exception)
                {
                    _console.Out.WriteLine("Error: Invalid input data format");
                    return;
                }
            }

            TPMSessionSealCommand.DataFormat outputDataFormat = TPMSessionSealCommand.DataFormat.Raw;

            if (arguments.ContainsKey("output_data_format"))
            {
                try
                {
                    outputDataFormat = (TPMSessionSealCommand.DataFormat)Enum.Parse(typeof(TPMSessionSealCommand.DataFormat), arguments["output_data_format"], true);
                }
                catch (Exception)
                {
                    _console.Out.WriteLine("Error: Invalid output data format");
                    return;
                }
            }


            if (dataInputMode == TPMSessionSealCommand.DataInputMode.File && arguments.ContainsKey("file") == false)
            {
                _console.Out.WriteLine("Error: data_input=file requires file argument!");
                return;
            }


            if (dataOutputMode == TPMSessionSealCommand.DataOutputMode.File && arguments.ContainsKey("output_file") == false)
            {
                _console.Out.WriteLine("Error: data_output=file requires output_file argument!");
                return;
            }

            ClientKeyHandle keyHandle = tpmSessions[localAlias].KeyClient.GetKeyHandleByFriendlyName(arguments["name"]);


            Stream inputStream = null;

            if (dataInputMode == TPMSessionSealCommand.DataInputMode.Console)
            {
                inputStream = new TextReaderStream(_console.In);
            }
            else if (dataInputMode == TPMSessionSealCommand.DataInputMode.Embedded)
            {
                if (commandline.Length <= 3)
                {
                    _console.Out.WriteLine("Error: no embedded data");
                    return;
                }

                StringBuilder embeddedData = new StringBuilder();
                for (int i = 3; i < commandline.Length; i++)
                {
                    embeddedData.Append(commandline[i]);
                    if (i + 1 < commandline.Length)
                    {
                        embeddedData.Append(" ");
                    }
                }

                inputStream = new TextReaderStream(new StringReader(embeddedData.ToString()));
            }
            else if (dataInputMode == TPMSessionSealCommand.DataInputMode.File)
            {
                inputStream = new FileStream(arguments["file"], FileMode.Open, FileAccess.Read);
            }

            if (inputDataFormat == TPMSessionSealCommand.DataFormat.Hex)
            {
                inputStream = new HexFilterStream(inputStream);
            }

            Stream outputStream = null;

            if (dataOutputMode == TPMSessionSealCommand.DataOutputMode.Console)
            {
                outputStream = new TextWriterStream(_console.Out);
            }
            else if (dataOutputMode == TPMSessionSealCommand.DataOutputMode.File)
            {
                outputStream = new FileStream(arguments["output_file"], FileMode.OpenOrCreate, FileAccess.Write);
            }

            if (outputDataFormat == TPMSessionSealCommand.DataFormat.Hex)
            {
                outputStream = new HexFilterStream(outputStream);
            }

            IAsymmetricBlockCipher bindCipher = keyHandle.CreateBindBlockCipher();

            bindCipher.Init(false, null);

            int read;

            byte[] buffer = new byte[bindCipher.GetInputBlockSize()];
            do
            {
                read = inputStream.Read(buffer, 0, buffer.Length);

                if (read > 0)
                {
                    byte[] encrypted = bindCipher.ProcessBlock(buffer, 0, read);
                    outputStream.Write(encrypted, 0, encrypted.Length);
                }
            }while(read > 0);

            _console.Out.WriteLine();
            outputStream.Dispose();
            inputStream.Dispose();
        }
Example #16
0
        public int GetInputBlockSize()
        {
            int inputBlockSize = engine.GetInputBlockSize();

            return((!forEncryption) ? inputBlockSize : (inputBlockSize - 10));
        }