Exemplo n.º 1
0
        public static int Encrypt(byte[] plaintext, int offset, int len, byte[] additionalData, byte[] nonce, byte[] key, byte[] outBuffer)
        {
            lock (mutex) {
                if (cipher == null)
                {
                    cipher = new ChaCha7539Engine();
                }
                else
                {
                    cipher.Reset();
                }

                if (_encryptKey == null)
                {
                    _encryptKey = new KeyParameter(key);
                }
                else
                {
                    _encryptKey.Reset();
                    _encryptKey.SetKey(key);
                }

                if (_temp_Params == null)
                {
                    _temp_Params = new ParametersWithIV(_encryptKey, nonce);
                }
                else
                {
                    _temp_Params.Reset();
                    _temp_Params.Set(_encryptKey, nonce);
                }

                cipher.Init(true, _temp_Params);

                byte[]       firstBlock = BufferPool.GetBuffer(64);
                KeyParameter macKey     = GenerateRecordMacKey(cipher, firstBlock);

                cipher.ProcessBytes(plaintext, offset, len, outBuffer, 0);

                byte[] mac     = BufferPool.GetBuffer(16);
                int    macsize = CalculateRecordMac(macKey, additionalData, outBuffer, 0, len, mac);
                Array.Copy(mac, 0, outBuffer, len, macsize);

                BufferPool.ReturnBuffer(mac);
                BufferPool.ReturnBuffer(firstBlock);

                return(len + 16);
            }
        }