示例#1
0
        private void Init()
        {
            IntPtr ctx = Marshal.AllocHGlobal(MbedTLS.cipher_get_size_ex());

            MbedTLS.cipher_init(ctx);
            if (MbedTLS.cipher_setup(ctx, MbedTLS.cipher_info_from_string(FormalName)) != 0)
            {
                throw new EncryptorException("Cannot initialize mbed TLS cipher  context.");
            }
            _ctx = ctx;
        }
示例#2
0
        public void InitCipher(byte[] key, byte[] iv, bool isCipher)
        {
            IntPtr ctx = Marshal.AllocHGlobal(MbedTLS.cipher_get_size_ex());

            if (isCipher)
            {
                _encryptIV  = iv;
                _encryptCtx = ctx;
            }
            else
            {
                _decryptIV  = iv;
                _decryptCtx = ctx;
            }
            byte[] realkey = key;
            if (Method == "rc4-md5")
            {
                byte[] temp = new byte[KeySize + IVSize];
                //realkey = new byte[KeySize];
                Array.Copy(key, 0, temp, 0, KeySize);
                Array.Copy(iv, 0, temp, KeySize, IVSize);
                realkey = MbedTLS.MD5(temp);
            }
            Key = realkey;
            MbedTLS.cipher_init(ctx);
            if (MbedTLS.cipher_setup(ctx, MbedTLS.cipher_info_from_string(FormalName)) != 0)
            {
                throw new EncryptorException("Cannot initialize mbed TLS cipher  context.");
            }
            if (MbedTLS.cipher_setkey(ctx, realkey, KeySize * 8, isCipher ? MbedTLS.MbedTLS_Encrypt :
                                      MbedTLS.MbedTLS_Decrypt) != 0)
            {
                throw new EncryptorException("Cannot set mbed TLS cipher key.");
            }
            if (MbedTLS.cipher_set_iv(ctx, iv, IVSize) != 0)
            {
                throw new EncryptorException("Cannot set mbed TLS cipher IV.");
            }
            if (MbedTLS.cipher_reset(ctx) != 0)
            {
                throw new EncryptorException("Cannot finalize mbed TLS cipher context.");
            }
        }