首页 > 编程语言 >C++实现web token加密生成验证

C++实现web token加密生成验证

时间:2024-08-21 19:54:16浏览次数:13  
标签:web set claim jwt json C++ raw token payload

代码 
#include "jwt-cpp/traits/boost-json/traits.h"

#include <boost/json/src.hpp> // You may require this if you are not building it elsewhere
#include <iostream>
#include <sstream>

void testToken() {
	using sec = std::chrono::seconds;
	using min = std::chrono::minutes;
	using traits = jwt::traits::boost_json;
	using claim = jwt::basic_claim<traits>;

	traits::value_type raw_value;
	traits::parse(raw_value, R"##({"api":{"array":[1,2,3],"null":null}})##");
	claim from_raw_json(raw_value);

	claim::set_t list{ "once", "twice" };
	std::vector<int64_t> big_numbers{ 727663072ULL, 770979831ULL, 427239169ULL, 525936436ULL };

	const auto time = jwt::date::clock::now();
	const auto token = jwt::create<traits>()
		.set_type("JWT")
		.set_issuer("auth.mydomain.io")
		.set_audience("mydomain.io")
		.set_issued_at(time)
		.set_not_before(time)
		.set_expires_at(time + min{ 2 } + sec{ 15 })
		.set_payload_claim("boolean", true)
		.set_payload_claim("integer", 12345)
		.set_payload_claim("precision", 12.3456789)
		.set_payload_claim("strings", claim(list))
		.set_payload_claim("array", claim{ big_numbers.begin(), big_numbers.end() })
		.set_payload_claim("object", from_raw_json)
		.sign(jwt::algorithm::none{});
	const auto decoded = jwt::decode<traits>(token);

	for (auto& e : decoded.get_header_json())
		std::cout << e.key() << " = " << e.value() << std::endl;

	const auto array =
		traits::as_array(decoded.get_payload_claim("object").to_json().as_object()["api"].as_object()["array"]);
	std::cout << "payload /object/api/array = " << array << std::endl;

	jwt::verify<traits>()
		.allow_algorithm(jwt::algorithm::none{})
		.with_issuer("auth.mydomain.io")
		.with_audience("mydomain.io")
		.with_claim("object", from_raw_json)
		.verify(decoded);
}

void testTokenES256k() {
	using sec = std::chrono::seconds;
	using min = std::chrono::minutes;
	using traits = jwt::traits::boost_json;
	using claim = jwt::basic_claim<traits>;


	// openssl ecparam -name secp256k1 -genkey -noout -out ec-secp256k1-priv-key.pem
	std::string es256k_priv_key = R"(-----BEGIN EC PRIVATE KEY-----
MHQCAQEEIArnQWnspKtjiVuZuzuZ/l1Uqqq8gb2unLJ/6U/Saf4ioAcGBSuBBAAK
oUQDQgAEfy03KCKUpIPMIJBtIG4xOwGm0Np/yHKaK9EDZi0mZ7VUeeNKq476CU5X
940yusahgneePQrDMF2nWFEtBCOiXQ==
-----END EC PRIVATE KEY-----)";
	// openssl ec -in ec-secp256k1-priv-key.pem -pubout > ec-secp256k1-pub-key.pem
	std::string es256k_pub_key = R"(-----BEGIN PUBLIC KEY-----
MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEfy03KCKUpIPMIJBtIG4xOwGm0Np/yHKa
K9EDZi0mZ7VUeeNKq476CU5X940yusahgneePQrDMF2nWFEtBCOiXQ==
-----END PUBLIC KEY-----)";

	traits::value_type raw_value;
	traits::parse(raw_value, R"##({"api":{"array":[1,2,3],"null":null}})##");
	claim from_raw_json(raw_value);

	claim::set_t list{ "once", "twice" };
	std::vector<int64_t> big_numbers{ 727663072ULL, 770979831ULL, 427239169ULL, 525936436ULL };

	const auto time = jwt::date::clock::now();
	const auto token = jwt::create<traits>()
		.set_type("JWT")
		.set_id("rsa-create-example")
		.set_issuer("auth.mydomain.io")
		.set_audience("mydomain.io")
		.set_issued_at(time)
		.set_not_before(time)
		.set_expires_at(time + min{ 2 } + sec{ 15 })
		.set_payload_claim("boolean", true)
		.set_payload_claim("integer", 12345)
		.set_payload_claim("precision", 12.3456789)
		.set_payload_claim("strings", claim(list))
		.set_payload_claim("array", claim{ big_numbers.begin(), big_numbers.end() })
		.set_payload_claim("object", from_raw_json)
		.sign(jwt::algorithm::es256k(es256k_pub_key, es256k_priv_key, "", ""));
	const auto decoded = jwt::decode<traits>(token);

	for (auto& e : decoded.get_header_json())
		std::cout << e.key() << " = " << e.value() << std::endl;

	const auto array =
		traits::as_array(decoded.get_payload_claim("object").to_json().as_object()["api"].as_object()["array"]);
	std::cout << "payload /object/api/array = " << array << std::endl;

	jwt::verify<traits>()
		.allow_algorithm(jwt::algorithm::es256k(es256k_pub_key, es256k_priv_key, "", ""))
		.with_issuer("auth.mydomain.io")
		.with_audience("mydomain.io")
		.with_claim("object", from_raw_json)
		.verify(decoded);
}


void testTokenRS256() {
	using sec = std::chrono::seconds;
	using min = std::chrono::minutes;
	using traits = jwt::traits::boost_json;
	using claim = jwt::basic_claim<traits>;

	std::string rsa_priv_key = R"(-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC4ZtdaIrd1BPIJ
tfnF0TjIK5inQAXZ3XlCrUlJdP+XHwIRxdv1FsN12XyMYO/6ymLmo9ryoQeIrsXB
XYqlET3zfAY+diwCb0HEsVvhisthwMU4gZQu6TYW2s9LnXZB5rVtcBK69hcSlA2k
ZudMZWxZcj0L7KMfO2rIvaHw/qaVOE9j0T257Z8Kp2CLF9MUgX0ObhIsdumFRLaL
DvDUmBPr2zuh/34j2XmWwn1yjN/WvGtdfhXW79Ki1S40HcWnygHgLV8sESFKUxxQ
mKvPUTwDOIwLFL5WtE8Mz7N++kgmDcmWMCHc8kcOIu73Ta/3D4imW7VbKgHZo9+K
3ESFE3RjAgMBAAECggEBAJTEIyjMqUT24G2FKiS1TiHvShBkTlQdoR5xvpZMlYbN
tVWxUmrAGqCQ/TIjYnfpnzCDMLhdwT48Ab6mQJw69MfiXwc1PvwX1e9hRscGul36
ryGPKIVQEBsQG/zc4/L2tZe8ut+qeaK7XuYrPp8bk/X1e9qK5m7j+JpKosNSLgJj
NIbYsBkG2Mlq671irKYj2hVZeaBQmWmZxK4fw0Istz2WfN5nUKUeJhTwpR+JLUg4
ELYYoB7EO0Cej9UBG30hbgu4RyXA+VbptJ+H042K5QJROUbtnLWuuWosZ5ATldwO
u03dIXL0SH0ao5NcWBzxU4F2sBXZRGP2x/jiSLHcqoECgYEA4qD7mXQpu1b8XO8U
6abpKloJCatSAHzjgdR2eRDRx5PMvloipfwqA77pnbjTUFajqWQgOXsDTCjcdQui
wf5XAaWu+TeAVTytLQbSiTsBhrnoqVrr3RoyDQmdnwHT8aCMouOgcC5thP9vQ8Us
rVdjvRRbnJpg3BeSNimH+u9AHgsCgYEA0EzcbOltCWPHRAY7B3Ge/AKBjBQr86Kv
TdpTlxePBDVIlH+BM6oct2gaSZZoHbqPjbq5v7yf0fKVcXE4bSVgqfDJ/sZQu9Lp
PTeV7wkk0OsAMKk7QukEpPno5q6tOTNnFecpUhVLLlqbfqkB2baYYwLJR3IRzboJ
FQbLY93E8gkCgYB+zlC5VlQbbNqcLXJoImqItgQkkuW5PCgYdwcrSov2ve5r/Acz
FNt1aRdSlx4176R3nXyibQA1Vw+ztiUFowiP9WLoM3PtPZwwe4bGHmwGNHPIfwVG
m+exf9XgKKespYbLhc45tuC08DATnXoYK7O1EnUINSFJRS8cezSI5eHcbQKBgQDC
PgqHXZ2aVftqCc1eAaxaIRQhRmY+CgUjumaczRFGwVFveP9I6Gdi+Kca3DE3F9Pq
PKgejo0SwP5vDT+rOGHN14bmGJUMsX9i4MTmZUZ5s8s3lXh3ysfT+GAhTd6nKrIE
kM3Nh6HWFhROptfc6BNusRh1kX/cspDplK5x8EpJ0QKBgQDWFg6S2je0KtbV5PYe
RultUEe2C0jYMDQx+JYxbPmtcopvZQrFEur3WKVuLy5UAy7EBvwMnZwIG7OOohJb
vkSpADK6VPn9lbqq7O8cTedEHttm6otmLt8ZyEl3hZMaL3hbuRj6ysjmoFKx6CrX
rK0/Ikt5ybqUzKCMJZg2VKGTxg==
-----END PRIVATE KEY-----)";

	traits::value_type raw_value;
	traits::parse(raw_value, R"##({"api":{"array":[1,2,3],"null":null}})##");
	claim from_raw_json(raw_value);

	claim::set_t list{ "once", "twice" };
	std::vector<int64_t> big_numbers{ 727663072ULL, 770979831ULL, 427239169ULL, 525936436ULL };

	const auto time = jwt::date::clock::now();
	const auto token = jwt::create<traits>()
		.set_type("JWT")
		.set_id("rsa-create-example")
		.set_issuer("auth.mydomain.io")
		.set_audience("mydomain.io")
		.set_issued_at(time)
		.set_not_before(time)
		.set_expires_at(time + min{ 2 } + sec{ 15 })
		.set_payload_claim("boolean", true)
		.set_payload_claim("integer", 12345)
		.set_payload_claim("precision", 12.3456789)
		.set_payload_claim("strings", claim(list))
		.set_payload_claim("array", claim{ big_numbers.begin(), big_numbers.end() })
		.set_payload_claim("object", from_raw_json)
		.set_payload_claim("sample", claim(std::string{ "test" }))
		.sign(jwt::algorithm::rs256("", rsa_priv_key, "", ""));
	const auto decoded = jwt::decode<traits>(token);

	std::cout << "token: " << token << std::endl;
	for (auto& e : decoded.get_header_json())	// get_payload_json
		std::cout << e.key() << " = " << e.value() << std::endl;

	std::string rsa_pub_key = R"(-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuGbXWiK3dQTyCbX5xdE4
yCuYp0AF2d15Qq1JSXT/lx8CEcXb9RbDddl8jGDv+spi5qPa8qEHiK7FwV2KpRE9
83wGPnYsAm9BxLFb4YrLYcDFOIGULuk2FtrPS512Qea1bXASuvYXEpQNpGbnTGVs
WXI9C+yjHztqyL2h8P6mlThPY9E9ue2fCqdgixfTFIF9Dm4SLHbphUS2iw7w1JgT
69s7of9+I9l5lsJ9cozf1rxrXX4V1u/SotUuNB3Fp8oB4C1fLBEhSlMcUJirz1E8
AziMCxS+VrRPDM+zfvpIJg3JljAh3PJHDiLu902v9w+Iplu1WyoB2aPfitxEhRN0
YwIDAQAB
-----END PUBLIC KEY-----)";

	const auto array =
		traits::as_array(decoded.get_payload_claim("object").to_json().as_object()["api"].as_object()["array"]);
	std::cout << "payload /object/api/array = " << array << std::endl;;

	jwt::verify<traits>()
		.allow_algorithm(jwt::algorithm::rs256(rsa_pub_key, "", "", ""))
		.with_issuer("auth.mydomain.io")
		.with_audience("mydomain.io")
		.with_claim("object", from_raw_json)
		.verify(decoded);
}

int test() {
	testToken();	// token有效验证
	testTokenES256k(); // token加密验证,依赖openssl
	testTokenRS256();
	return 0;
}
输出

    
    typ = "JWT"
    alg = "none"
    payload /object/api/array = [1,2,3]
    
    
    typ = "JWT"
    alg = "ES256K"
    payload /object/api/array = [1,2,3]
    
    
    token: eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJhdXRoLm15ZG9tYWluLmlvIiwiYXVkIjoibXlkb21haW4uaW8iLCJpYXQiOjE3MjQxMzY1NzMsIm5iZiI6MTcyNDEzNjU3MywiZXhwIjoxNzI0MTM2NzA4LCJib29sZWFuIjp0cnVlLCJpbnRlZ2VyIjoxMjM0NSwicHJlY2lzaW9uIjoxLjIzNDU2Nzg5RTEsInN0cmluZ3MiOlsib25jZSIsInR3aWNlIl0sImFycmF5IjpbNzI3NjYzMDcyLDc3MDk3OTgzMSw0MjcyMzkxNjksNTI1OTM2NDM2XSwib2JqZWN0Ijp7ImFwaSI6eyJhcnJheSI6WzEsMiwzXSwibnVsbCI6bnVsbH19fQ.abnNu6Cw15Bhw-KSyLRyNoczx277lC8X0T2qipZ6zujh_EWGZXzVqIkdgSPrXAmuC9fbOEgdgKoLGSTNvkw4iFX6bql8qcde91rr5wYtp_EnjMk8xM_Ootp6ETO5fF8jZSNdEWWLVpZQxFIm_IFogjbTAzySP4ZuQC1B4Gf_qVM0XAJMG1fW7Hwl_6VtW_SfXf9JEKrJB7d-Tex3aTm-BfRqKIQl0GclWuZtfmvvRmJuMpTr4OqhM7w8FDbavsbjvbNNZyr2tH5P0k8Zm6BWgjAD5y4vlsp0drb_NIaVay5J3VxhGnQ-aReVBfi_N3sbJrLF6vpruEwCnu084P4a-A
    typ = "JWT"
    alg = "RS256"
    payload /object/api/array = [1,2,3]
    

参考 

GitHub - Thalhammer/jwt-cpp: A header only library for creating and validating json web tokens in c++

标签:web,set,claim,jwt,json,C++,raw,token,payload
From: https://blog.csdn.net/qq_30220519/article/details/141367851

相关文章

  • C++ 有向图拓扑排序算法
    代码 #include<algorithm>#include<cassert>#include<functional>#include<map>#include<memory>#include<queue>#include<set>#include<unordered_set>#include<vector>namespacejc{templa......
  • 昇腾 - AscendCL C++应用开发 目标检测中的非极大值抑制NMS和计算候选边界框之间的交
    昇腾-AscendCLC++应用开发目标检测中的非极大值抑制(NMS,Non-MaximumSuppression)涉及计算候选边界框之间的交并比(IOU,IntersectionoverUnion)flyfish结构体BBox:定义了一个边界框的数据结构,包含中心坐标、宽高、置信度分数、类别索引和输出索引。函数IOU:计算两个......
  • 软件测试-web端测试-代码起步
    记录学习笔记第一步、导包web自动化测试常用selenium,这是必要的。fromseleniumimportwebdriver 第二步、确定要使用的浏览器浏览器有很多,常用Chrome,这里看你下载的webdriver是谁的,我用的是edge。用谷歌,那就把Edge改为Chrome,用火狐就改为Firefoxdriver=webdriver.Ed......
  • 软件测试-web自动化测试-前期环境搭建
    记录学习笔记web端自动化测试也就是网页自动化测试。主要在PyCharm软件里编写代码,前期需要准备python+selenium的基础环境搭建。1、下载安装python,下载最新版检查环境:在cmd里python -v和pip -v可以正常出现。√2、PyCharm安装,下载社区免费版直接next安装即可,打开软......
  • 短视频生成与AI的结合应用,Web/App RPA 智能化应用
    在这个日新月异的时代,人工智能(AI)与自动化技术的融合正以前所未有的速度重塑着各行各业。你是否梦想过,在信息的海洋中自动筛选出精华,用创意点亮每一篇内容,同时让繁琐的工作流程变得轻松高效?我们诚邀您参加即将开启的“AI自动化应用开发”公开课第3期,一同探索如何用好AI与自动化,让您......
  • 二叉树入门学习 优势对比 以及 完全二叉树c++代码的实现
    二叉树介绍文档一、概述二叉树是一种常见的数据结构,它是一种树形结构,每个节点最多有两个子节点,通常称为左子节点和右子节点。二叉树的基本概念如下:节点(Node):二叉树的基本单元,包含一个值以及指向左右子节点的引用。根节点(Root):树的顶端节点,没有父节点。叶子节点(Leaf):没有子节......
  • WebDriver API剖析----元素、鼠标、键盘的操作
    一、元素的操作1、清除元素的内容clear()方法用于清除元素中已有的内容。fromseleniumimportwebdriverfromtimeimportsleepfromselenium.webdriver.common.byimportBydriver=webdriver.Firefox()driver.get("https://www.baidu.com")driver.find_element(......
  • centos7安装FreeRadius3及WEB管理界面DaloRadius
    一、基础环境安装1.安装基础环境yum-yinstallgccgcc-c++autoconflibjpeglibjpeg-devellibpnglibpng-develfreetypefreetype-devellibxml2libxml2-develzlibzlib-develglibcglibc-develglib2glib2-develbzip2bzip2-develncursesncurses-develcurlcurl-......
  • 【卡码网C++基础课 3.A+B问题3】
    目录题目描述与分析一、if语句二、关系运算符三、逻辑运算符四、break退出循环五、延伸题目描述与分析题目描述:你的任务依然是计算a+b。输入描述:输入中每行是一对a和b。其中会有一对是0和0标志着输入结束,且这一对不要计算。输出描述:对于输入的每对a和b,你需要在......
  • 从零开始学习C++(1-1)
    本篇帖子学习C++输入输出。C++目前最常用的两种输入输出方法,cin/cout和scanf/printf。cin/cout这是C++入门必学且最最最基础的输入输出方式,在<iostream>头文件,std命名空间下。基本格式如下:cin>>x;cout<<x<<"\n";//"\n"为换行符注:很多教材会教你换行输出......