JuliaLang / MbedTLS.jl

Wrapper around mbedtls
Other
41 stars 50 forks source link

`encrypt` method mentioned in the documentation does not actually work #263

Open iuliadmtru opened 1 year ago

iuliadmtru commented 1 year ago

In the documentation for encrypt one possible method to specify the cipher is as a Cipher object. However, this throws an error:

julia> using MbedTLS

julia> secret_key = rand(UInt8, 32);

julia> encrypt(Cipher(CIPHER_AES), secret_key, "message")
ERROR: MethodError: no method matching Cipher(::Cipher)
Closest candidates are:
  Cipher() at ~/.julia/packages/MbedTLS/lqmet/src/cipher.jl:93
  Cipher(::Union{MbedTLS.CipherID, MbedTLS.CipherKind}) at ~/.julia/packages/MbedTLS/lqmet/src/cipher.jl:182
  Cipher(::MbedTLS.CipherInfo) at ~/.julia/packages/MbedTLS/lqmet/src/cipher.jl:166
Stacktrace:
 [1] crypt(cipher_info::Cipher, op::MbedTLS.Operation, key::Vector{UInt8}, iv::Nothing, msg::String)
   @ MbedTLS ~/.julia/packages/MbedTLS/lqmet/src/cipher.jl:277
 [2] encrypt(cipher::Cipher, key::Vector{UInt8}, msg::String, iv::Nothing) (repeats 2 times)
   @ MbedTLS ~/.julia/packages/MbedTLS/lqmet/src/cipher.jl:306
 [3] top-level scope
   @ REPL[6]:1

Looking at the source code, it looks like encrypt calls crypt, which calls the Cipher constructor on the cipher_info parameter, which in this case is already a Cipher!

Maybe in the documentation it should say that the cipher can be a CipherInfo object instead of a Cipher object? This works:

julia> encrypt(MbedTLS.CipherInfo(CIPHER_AES), secret_key, "message")
16-element Vector{UInt8}:
 0xbd
 0x5f
 0x2b
 0x20
 0x33
 0xa3
 0x7e
 0x54
 0x86
 0x03
 0x68
 0x26
 0xa9
 0xa2
 0xaf
 0xa5