1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

docs: add a jwt example to vlib/crypto/README.md (#14872)

This commit is contained in:
Hitalo de Jesus do Rosário Souza 2022-06-29 05:57:05 -03:00 committed by GitHub
parent 51649b924b
commit c481b80ec3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -15,6 +15,7 @@ The implementations here are loosely based on [Go's crypto package](https://pkg.
## Examples:
### AES:
```v
import crypto.aes
import crypto.rand
@ -43,3 +44,40 @@ fn main() {
assert decrypted == data
}
```
### JWT:
```v
import crypto.hmac
import crypto.sha256
import encoding.base64
import json
struct JwtHeader {
alg string
typ string
}
struct JwtPayload {
sub string
name string
iat int
}
fn main() {
token := make_token()
println(token)
}
fn make_token() string {
secret := 'your-256-bit-secret'
header := base64.url_encode(json.encode(JwtHeader{'HS256', 'JWT'}).bytes())
payload := base64.url_encode(json.encode(JwtPayload{'1234567890', 'John Doe', 1516239022}).bytes())
signature := base64.url_encode(hmac.new(secret.bytes(), '${header}.$payload'.bytes(),
sha256.sum, sha256.block_size).bytestr().bytes())
jwt := '${header}.${payload}.$signature'
return jwt
}
```