Skip to content

Commit

Permalink
Sign messages
Browse files Browse the repository at this point in the history
  • Loading branch information
lpil committed Aug 10, 2023
1 parent 4470c0e commit d3a608c
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/wisp.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -1432,6 +1432,38 @@ pub fn random_string(length: Int) -> String {
|> string.slice(0, length)
}

/// Sign a message which can later be verified using the `verify_signed_message`
/// function to detect if the message has been tampered with.
///
/// Signed messages are not encrypted and can be read by anyone. They are not
/// suitable for storing sensitive information.
///
/// This function uses the secret key base from the request. If the secret
/// changes then the signature will no longer be verifiable.
///
pub fn sign_message(
request: Request,
message: BitString,
algorithm: crypto.HashAlgorithm,
) -> String {
crypto.sign_message(message, <<request.body.secret_key_base:utf8>>, algorithm)
}

/// Verify a signed message which was signed using the `sign_message` function.
///
/// Returns the content of the message if the signature is valid, otherwise
/// returns an error.
///
/// This function uses the secret key base from the request. If the secret
/// changes then the signature will no longer be verifiable.
///
pub fn verify_signed_message(
request: Request,
message: String,
) -> Result(BitString, Nil) {
crypto.verify_signed_message(message, <<request.body.secret_key_base:utf8>>)
}

fn random_slug() -> String {
random_string(16)
}
Expand Down
16 changes: 16 additions & 0 deletions test/wisp_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import gleam/http/request
import gleam/http/response.{Response}
import gleam/list
import gleam/string
import gleam/crypto
import gleam/string_builder
import gleam/erlang
import gleam/set
Expand Down Expand Up @@ -713,3 +714,18 @@ pub fn urlencoded_form_fields_are_sorted_test() {
})
|> should.equal(wisp.ok())
}

pub fn message_signing_test() {
let request = wisp.test_request(<<>>)
let request1 = wisp.set_secret_key_base(request, wisp.random_string(64))
let request2 = wisp.set_secret_key_base(request, wisp.random_string(64))

let signed1 = wisp.sign_message(request1, <<"a":utf8>>, crypto.Sha512)
let signed2 = wisp.sign_message(request2, <<"b":utf8>>, crypto.Sha512)

let assert Ok(<<"a":utf8>>) = wisp.verify_signed_message(request1, signed1)
let assert Ok(<<"b":utf8>>) = wisp.verify_signed_message(request2, signed2)

let assert Error(Nil) = wisp.verify_signed_message(request1, signed2)
let assert Error(Nil) = wisp.verify_signed_message(request2, signed1)
}

0 comments on commit d3a608c

Please sign in to comment.