JWT(JSON Web Token) 在IOT常被使用的Token協定。因為其具有方便製作以及高安全性被廣泛使用各種裝置認證。這篇文章主旨是在RTOS mbed環境中,使用open ssl從KEY pair的生成到使用KEY簽屬JWT,之後再使用Public key認證JWT token
JWT的組成
JWT可以分為三個部分組成,分別為:header.payload.signature
Mbed JWT tutorial
zephyer environment
- open one thread to run jwt , this article only foucus on how zephyer jwt used. ### 1. Open ssl - Key pair generate create key use mbedtls header
#include <mbedtls/pk.h>
#include "mbedtls/entropy.h"
#include <mbedtls/rsa.h>
#include <mbedtls/sha256.h>
- Gen private key
- Gen key pair
#use for random seed
static int csprng_wrapper(void *ctx, unsigned char *dest, size_t size)
{
ARG_UNUSED(ctx);
return sys_csrand_get((void *)dest, size);
}
void create_rsa_keys(mbedtls_pk_context *private_key)
{
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_entropy_init(&entropy); #進行初始化
mbedtls_ctr_drbg_init(&ctr_drbg); #進行亂數的初始化
const char *pers = "test pers for test" # 設置pers
const char *msg = "test msg for test" #設置msg
int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, csprng_wrapper, NULL ,(const unsigned char *)pers, strlen(pers));#封裝生成key 的seed
ret = mbedtls_pk_setup(private_key, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA));#輸入的位置初始化為儲存private key的空間
mbedtls_rsa_gen_key(mbedtls_pk_rsa(*private_key), csprng_wrapper, NULL, 2048, 65537); #產生private key後儲存
printf("\r\nKey generation %s\r\n", ret == 0 ? "successful" : "failed");
ret = mbedtls_rsa_check_privkey(mbedtls_pk_rsa(*private_key)); #check private key 是否合法
printf("\r\n check private key sucessfully %s\r\n", ret == 0 ? "successful" : "failed");
mbedtls_ctr_drbg_free(&ctr_drbg); #釋放空間
mbedtls_entropy_free(&entropy); #釋放空間
}
因為public key可以快速地從private key中取得。在mbedtls中有兩組函數
mbedtls_pk_parse_key(&pri_key, private_pem_buf, strlen(private_pem_buf) + 1, NULL, 0, csprng_wrapper, NULL);
#此函數的pk不代表private key,因此函數將同時撈出private key and public key儲存到第一個你指定的空間中,private_pem_buf則是你存放的private key
mbedtls_pk_parse_public_key(); # 而此函數直接提取public key
2. Mbed JWT - Create JWT token
- Use mbed JWT lib
- Use private key sign Token
3. Token verify
- use Public key verify
Top comments (0)