//修改key or iv后需调用。 private void Reset() { if (MbedTLS.cipher_reset(_ctx) != 0) { throw new EncryptorException("Cannot finalize mbed TLS cipher context."); } Finished = true; }
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."); } }