protected override void initCipher(byte[] iv, bool isCipher) { base.initCipher(iv, isCipher); IntPtr ctx = Marshal.AllocHGlobal(MbedTLS.cipher_get_size_ex()); if (isCipher) { _encryptCtx = ctx; } else { _decryptCtx = ctx; } byte[] realkey; if (_method.StartsWith("rc4-")) { byte[] temp = new byte[keyLen + ivLen]; realkey = new byte[keyLen]; Array.Copy(_key, 0, temp, 0, keyLen); Array.Copy(iv, 0, temp, keyLen, ivLen); realkey = MbedTLS.MD5(temp); } else { realkey = _key; } MbedTLS.cipher_init(ctx); if (MbedTLS.cipher_setup(ctx, MbedTLS.cipher_info_from_string(getInfo().name)) != 0) { throw new Exception("Cannot initialize mbed TLS cipher context"); } /* * MbedTLS takes key length by bit * cipher_setkey() will set the correct key schedule * and operation * * MBEDTLS_AES_{EN,DE}CRYPT * == MBEDTLS_BLOWFISH_{EN,DE}CRYPT * == MBEDTLS_CAMELLIA_{EN,DE}CRYPT * == MBEDTLS_{EN,DE}CRYPT * */ if (MbedTLS.cipher_setkey(ctx, realkey, keyLen * 8, isCipher ? MbedTLS.MBEDTLS_ENCRYPT : MbedTLS.MBEDTLS_DECRYPT) != 0) { throw new Exception("Cannot set mbed TLS cipher key"); } if (MbedTLS.cipher_set_iv(ctx, iv, ivLen) != 0) { throw new Exception("Cannot set mbed TLS cipher IV"); } if (MbedTLS.cipher_reset(ctx) != 0) { throw new Exception("Cannot finalize mbed TLS cipher context"); } }
protected void bytesToKey(byte[] password, byte[] key) { byte[] result = new byte[password.Length + 16]; int i = 0; byte[] md5sum = null; while (i < key.Length) { if (i == 0) { md5sum = MbedTLS.MD5(password); } else { md5sum.CopyTo(result, 0); password.CopyTo(result, md5sum.Length); md5sum = MbedTLS.MD5(result); } md5sum.CopyTo(key, i); i += md5sum.Length; } }
protected byte[] GetPasswordHash() { byte[] inputBytes = Encoding.UTF8.GetBytes(Password); byte[] hash = MbedTLS.MD5(inputBytes); return(hash); }