imkcat / CatCrypto

An easy way for hashing and encryption.
MIT License
69 stars 13 forks source link

Argon2 result with \0 at the end #4

Closed SimonasA closed 6 years ago

SimonasA commented 6 years ago

Issue type

Before question

Desciption

After updating to 0.3.0 I noticed null char at the end of result string when using Argon2 hash function.

i.e. Even when checking CatCrypto tests (ArgonTests.swift) I expect to get

"$argon2i$v=19$m=4096,t=3,p=1$ODExM0FENzYtQjFENC00NzE0LUE1NjktQTkyMDMzNkYzRkI3$wJfIvpKfuE91unyYNwEfLyuaXhWS9XuTJOGaFbP7wOE"

and I get this instead:

"$argon2i$v=19$m=4096,t=3,p=1$ODExM0FENzYtQjFENC00NzE0LUE1NjktQTkyMDMzNkYzRkI3$wJfIvpKfuE91unyYNwEfLyuaXhWS9XuTJOGaFbP7wOE\0"

Is that expected behaviour?

arg

imkcat commented 6 years ago

It is due to the different from String(cString:, encoding:) and String(bytes:, encoding:).

You can check this: Why does String's bytes: and cString: initializers give different results here?

Before 0.3.0, there is only one string output way and the process depend on cryptos, the Argon2 hash string was handle with String(cString:, encoding:), the \0 at the end of raw bytes was ignored.

After 0.3.0, I added more value output ways: Raw, Bool, String, Hex and Base64, the string value output was processed from raw bytes with String(bytes:, encoding:), so the string is not terminated by the first \0.

SimonasA commented 6 years ago

@ImKcat thanks for clarifying, now I see where that \0 comes from 🙇

But does that mean that we should "strip" that \0 from result? i.e. use this

  let string = result.hexStringValue().dataFromHex().withUnsafeBytes { pointer -> String? in
    return String(cString: pointer, encoding: .utf8)
  }

instead of

let string = result.stringValue()

Couldn't we do that "inside" CatCrypto and have stringValue() return already "stripped" string?

imkcat commented 6 years ago

@SimonasA Sure, it is should be

If you want to use filtered string, here is the quick snippet to solve that:


let string = result.stringValue().filter{ $0 != "\0" }
SimonasA commented 6 years ago

@ImKcat, I could 👍

Just then I must be 100% that "\0" is never a valid char in the given string :)

imkcat commented 6 years ago

Added in 4c3e6b389f80c3fb9d873e039b10cb69dbbde34e