code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222 values | license stringclasses 20 values | size int64 1 1.05M |
|---|---|---|---|---|---|
<template>
<view>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">button,按钮</view>
</view>
<!--主题-->
<view class="smart-padding-wrap">
<button type="primary">页面主操作 normal</button>
<button type="primary" :loading="loading">页面主操作 loading</button>
<button type="primary" disabled="false">页面主操作 disabled</button>
<button type="default">页面次要操作 normal</button>
<button type="default" disabled="false">页面次要操作 disabled</button>
<button type="warn">警告类操作 warn</button>
<button type="warn" @click="goto()">警告类操作 Normal</button>
<button type="warn" disabled="false">警告类操作 disabled</button>
<view class="button-sp-area">
<button type="primary" plain="true">镂空按钮</button>
<button type="default" plain="true">镂空按钮</button>
<button type="warn" plain="true">镂空按钮</button>
<button type="default" disabled="true" plain="true">不可点击的按钮</button>
<button class="mini-btn" type="primary" size="mini">按钮</button>
<button class="mini-btn" type="default" size="mini">按钮</button>
<button class="mini-btn" type="warn" size="mini">按钮</button>
</view>
<!-- #ifdef MP-WEIXIN || MP-QQ || APP-PLUS -->
<button open-type="launchApp" app-parameter="uni-app" @error="openTypeError">打开APP</button>
<button open-type="feedback">意见反馈</button>
<!-- #endif -->
</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
goto() {
// 跳转方法
uni.showToast({
title: '按钮点击',
icon: 'success'
})
}
}
}
</script>
<style>
button {
margin-top: 30rpx;
margin-bottom: 30rpx;
}
.mini-btn {
margin-right: 30rpx;
}
</style> | 2401_83220332/SmartUI_wht027 | pages/components/button/button.vue | Vue | unknown | 1,854 |
<template>
<view v-for="(item,index) in datalist" style="margin:10rpx">
<cardTopVue :img="item.img" :title="item.title" :writer="item.writer" :comment="item.comment" :time="item.time" :isTop="item.isTop">
</cardTopVue>
</view>
</template>
<script>
import cardTopVue from '../../../components/cardViewText.vue'
export default {
components: {
cardTopVue
},
data() {
return {
datalist: [{
img: '/static/new1.jpg',
title: "长沙潮宗街墙体垮塌附近商户发声:事发前涉事店铺装修打洞曾引发邻居投诉",
writer: "澎湃新闻",
comment: "69评",
time: "14小时前",
isTop: true,
},
{
img: '/static/new2.jpg',
title: "中方:已向日方提出严正交涉和强烈抗议!",
writer: "环球时报",
comment: "35评",
time: "3小时前",
isTop: false,
},
{
img: '/static/new3.jpg',
title: "陕西31岁女护士被同居男友杀害案将于11月3日开庭,家属:放弃赔偿,不接受道歉,希望对方被判死刑",
writer: "大河报",
comment: "1376评",
time: "3小时前",
isTop: true,
},
{
img: '/static/new4.jpg',
title: "江西一窝点被端,多名男女被抓!",
writer: "闽南网",
comment: "16评",
time: "5天前",
isTop: false,
}
]
}
},
methods: {
}
}
</script>
<style>
</style> | 2401_83220332/SmartUI_wht027 | pages/components/cardTop/cardTop.vue | Vue | unknown | 1,454 |
<template>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">checkarea</view>
</view>
<!--主题-->
<view class="smart-padding-wrap">
<view>默认样式</view>
<checkbox-group>
<checkbox value="cb1" checked="true" />选中
<checkbox value="cb" />未选中
</checkbox-group>
<view class="smart-page-head-title">不同颜色和尺寸的checkbox</view>
<checkbox-group>
<label style="background-color: #8A6DE9;">
<checkbox value="cb1" checked="true" style="transform:scale(0.7)" />选中
</label>
<label style="background-color: #00ff00;">
<checkbox value="cb" style="transform:scale(0.7)" />未选中
</label>
</checkbox-group>
<view>推荐展示样式</view>
<view class="uni-list">
<checkbox-group @change="checkboxChange">
<label class="uni-list-cell uni-list-cell-pd" v-for="item in items" :key="item.value" style="background-color: #F3A73F;">
<checkbox :value="item.value" :checked="item.checked" />
{{item.name}}
</label>
</checkbox-group>
</view>
</view>
</template>
<script>
export default {
data() {
return {
items: [
{value: 'USA', name: '美国', checked: false},
{value: 'CHN', name: '中国', checked: false},
{value: 'BRA', name: '巴西', checked: false},
{value: 'JPN', name: '日本', checked: false},
{value: 'ENG', name: '英国', checked: false},
{value: 'FRA', name: '法国', checked: false}
]
}
},
methods: {
checkboxChange: function (e) {
var items = this.items,
values = e.detail.value;
for (var i = 0, lenI = items.length; i < lenI; ++i) {
const item = items[i]
if(values.indexOf(item.value) >= 0){
this.$set(item,'checked',true)
}else{
this.$set(item,'checked',false)
}
console.log('i: '+i+'---'+item.name+', index:'
+ values.indexOf(item.value)
+', isCheck: '+item.checked)
}
}
}
}
</script>
<style>
.uni-list {
background-color: #FFFFFF;
border-radius: 10rpx;
}
.uni-list-cell {
display: flex;
align-items: center;
padding: 20rpx;
}
.uni-list-cell-pd {
padding: 20rpx 30rpx;
}
</style> | 2401_83220332/SmartUI_wht027 | pages/components/checkbox/checkbox.vue | Vue | unknown | 2,609 |
<template>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">from</view>
</view>
<!--主题-->
<view class="container">
<form @submit="formSubmit" @reset="formReset">
<view class="item uni-column">
<view class="title">switch</view>
<switch name="switch" />
</view>
<view class="item uni-column">
<view class="title">radio</view>
<radio-group name="radio">
<label>
<radio value="radio1" /><text>选项一</text>
</label>
<label>
<radio value="radio2" /><text>选项二</text>
</label>
</radio-group>
</view>
<view class="item uni-column">
<view class="title">checkbox</view>
<checkbox-group name="checkbox">
<label>
<checkbox value="checkbox1" /><text>选项一</text>
</label>
<label>
<checkbox value="checkbox2" /><text>选项二</text>
</label>
</checkbox-group>
</view>
<view class="item uni-column">
<view class="title">Slider</view>
<slider value="50" name="slider" show-value></slider>
</view>
<view class="item uni-column">
<view class="title">input</view>
<input class="uni-input" name="input" placeholder="这是一个输入框" />
</view>
<view>
<button form-type="submit">Submit</button>
<button type="default" form-type="reset">Reset</button>
</view>
</form>
</view>
</template>
<script>
export default {
data() {
return {};
},
methods: {
formSubmit: function(e) {
console.log('form发生了submit事件,携带数据为:' + JSON.stringify(e.detail.value));
var formdata = e.detail.value;
uni.showModal({
content: '表单数据内容:' + JSON.stringify(formdata),
showCancel: false
});
},
formReset: function(e) {
console.log('清空数据');
}
}
};
</script>
<style>
switch {
transform: scale(0.7);
}
radio {
transform: scale(0.7);
}
checkbox {
transform: scale(0.7);
}
.container {
padding: 40upx;
}
.item .title {
padding: 20rpx 0;
}
</style> | 2401_83220332/SmartUI_wht027 | pages/components/from/from.vue | Vue | unknown | 2,056 |
<template>
<view>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">icon图标</view>
</view>
<!--主题-->
<view style="display:flex; flex-direction: column;align-items: center;">
<icon type="waiting" />
<icon type="waiting" size="32" color="red" />
</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
}
}
</script>
<style>
</style>
| 2401_83220332/SmartUI_wht027 | pages/components/icon/icon.vue | Vue | unknown | 490 |
<template>
<view>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">input输入框</view>
</view>
<!--主题-->
<view class="smart-padding-wrap">
<view class="item">可自动获取焦点的</view>
<view><input class="smart-input" focus="true" placeholder="自动获取焦点" /></view>
<view>右下角显示搜索</view>
<view><input class="smart-input" confirm-type="search" placeholder="右下角显示搜索" /></view>
<view>控制最大输入长度</view>
<view><input class="smart-input" maxlength="10" placeholder="控制最大输入长度为10" /></view>
<view>同步获取输入值 <text style="color: #007AFF;">{{ inputValue }}</text></view>
<view><input class="smart-input" @input="onKeyInput" placeholder="同步获取输入值" /></view>
<view>数字输入</view>
<view><input class="smart-input" type="number" placeholder="这是一个数字输入框" /></view>
<view>密码输入</view>
<view><input class="smart-input" type="text" password="true" placeholder="这是一个密码输入框" /></view>
<view>带小数点输入</view>
<view><input class="smart-input" type="digit" placeholder="这是一个带小数点输入框" /></view>
<view>身份输入</view>
<view><input class="smart-input" type="idcard" placeholder="这是一个身份输入框" /></view>
<view>带清除按钮</view>
<view class="wrapper">
<input class="smart-input" :value="clearinputValue" @input="clearInput" placeholder="这是一个带清除按钮输入框" />
<text v-if="showClearIcon" @click="clearIcon" class="uni-icon"></text>
</view>
<view>可查看密码的输入框</view>
<view class="wrapper">
<input class="smart-input" placeholder="请输入密码" :password="showPassword" />
<text class="uni-icon" :class="[!showPassword ? 'eye-active' : '']" @click="changePassword"></text>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
inputValue: '',
showPassword: true,
clearinputValue: '',
showClearIcon: false
};
},
methods: {
onKeyInput: function(event) {
this.inputValue = event.detail.value;
},
clearInput: function(event) {
this.clearinputValue = event.detail.value;
if (event.detail.value.length > 0) {
this.showClearIcon = true;
} else {
this.showClearIcon = false;
}
},
clearIcon: function(event) {
this.clearinputValue = '';
this.showClearIcon = false;
},
changePassword: function() {
this.showPassword = !this.showPassword;
}
}
};
</script>
<style>
.uni-icon {
font-family: uniicons;
font-size: 24px;
font-weight: normal;
font-style: normal;
width: 24px;
height: 24px;
line-height: 24px;
color: #999999;
margin-top: 5px;
}
.wrapper {
/* #ifdef */
display: flex;
/* #endif */
flex-direction: row;
flex-wrap: nowrap;
background-color: #d8d8d8;
}
.eye-active {
color: #007aff;
}
.item {
margin-bottom: 40rpx;
}
</style> | 2401_83220332/SmartUI_wht027 | pages/components/input/input.vue | Vue | unknown | 3,245 |
<template>
<view>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">lable</view>
</view>
<!--主题-->
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
}
}
</script>
<style>
</style>
| 2401_83220332/SmartUI_wht027 | pages/components/label/label.vue | Vue | unknown | 299 |
<template>
<view>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">navigator, 链接</view>
</view>
<!--主题-->
<view class="smart-padding-wrap">
<navigator url="newpage/newpage?title=navigator" hover-class="navigator-hover">
<button type="default">跳转到新页面</button>
</navigator>
<navigator url="newpage/newpage?title=redirect" open-type="redirect" hover-class="other-navigator-hover">
<button type="default">在当前页打开</button>
</navigator>
<navigator url="/pages/tabBar/api/api" open-type="switchTab" hover-class="other-navigator-hover">
<button type="default">跳转tab页面</button>
</navigator>
</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'navigator'
};
},
methods: {
}
};
</script>
<style>
</style> | 2401_83220332/SmartUI_wht027 | pages/components/navigator/navigator.vue | Vue | unknown | 911 |
<template>
<view>
new。。。。。。
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
}
}
</script>
<style>
</style>
| 2401_83220332/SmartUI_wht027 | pages/components/navigator/newpage/newpage.vue | Vue | unknown | 183 |
<template>
<view>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">scroll-view区域滚动视图</view>
</view>
<!--主题-->
<view class="smart-padding-wrap">
<view class="text">可滚动视图区域</view>
<view>vertical scroll 纵向滚动</view>
<view>
<scroll-view class="scroll-y" scroll-y="true">
<view class="scroll-view-tiem smart-bg-red">A</view>
<view class="scroll-view-tiem smart-bg-orange">B</view>
<view class="scroll-view-tiem smart-bg-green">C</view>
</scroll-view>
</view>
<view>vertical scroll 横向滚动</view>
<view>
<scroll-view class="scroll-x" scroll-x="true" scroll-left="120">
<view class="scroll-view-tiem-h smart-bg-red">A</view>
<view class="scroll-view-tiem-h smart-bg-orange">B</view>
<view class="scroll-view-tiem-h smart-bg-green">C</view>
</scroll-view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
}
}
</script>
<style>
</style>
| 2401_83220332/SmartUI_wht027 | pages/components/scroll-view/scroll-view.vue | Vue | unknown | 1,071 |
<template>
<view>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">swiper 视图</view>
</view>
<!--主题-->
<view class="smart-padding-wrap">
<view>轮播图</view>
<swiper circular :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval"
:duration="duration" style="height: 350rpx;">
<swiper-item>
<view class="swiper-item smart-bg-red">A</view>
</swiper-item>
<swiper-item>
<view class="swiper-item smart-bg-orange">B</view>
</swiper-item>
<swiper-item>
<view class="swiper-item smart-bg-green">C</view>
</swiper-item>
</swiper>
</view>
</view>
</template>
<script>
export default {
data() {
return {
indicatorDots: true,
/*指示点*/
autoplay: true,
/*自动播放*/
interval: 5000,
/*停留时长*/
duration: 500 /*切换间隔时长*/
}
},
methods: {
}
}
</script>
<style>
.swiper-item{
display: block;
height: 100%;
width: 100%;
}
</style> | 2401_83220332/SmartUI_wht027 | pages/components/swiper/swiper.vue | Vue | unknown | 1,030 |
<template>
<view>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">text</view>
</view>
<!--主题-->
<view class="smart-padding-wrap">
<text space="ensp" class="text-space">A  B C \n</text>
<text space="emsp" class="text-space">A  B C \n</text>
<text space="nbsp" class="text-space">A  B C \n</text>
<view class="text-box">
<text selectable="true">{{ text }}</text>
</view>
<button type="primary" :disabled="!canAdd" @click="add">Add Line</button>
<button type="warn" :disabled="!canRemove" @click="remove">Remove Line</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
texts: [
'HBuilder,400万开发者选择的IDE',
'HBuilderX,轻巧、急速、极客编辑器',
'uni-app,终极跨平台方案',
'HBuilder,400万开发者选择的IDE',
'HBuilderX,轻巧、急速、极客编辑器',
'uni-app,终极跨平台方案',
'HBuilder,400万开发者选择的IDE',
'HBuilderX,轻巧、急速、极客编辑器',
'uni-app,终极跨平台方案',
'......'
],
text: '',
canAdd: true,
canRemove: false,
extraLine: []
}
},
methods: {
add: function(e){
this.extraLine.push(this.texts[this.extraLine.length % 12]);
this.text=this.extraLine.join('\n');
this.canAdd=this.extraLine.length<12;
this.canRemove=this.extraLine.length>0
},
remove: function(e){
if(this.extraLine.length>0){
this.extraLine.pop();
this.text=this.extraLine.join('\n');
this.canAdd=this.extraLine.length<12;
this.canRemove=this.extraLine.length>0
}
}
}
}
</script>
<style>
</style> | 2401_83220332/SmartUI_wht027 | pages/components/text/text.vue | Vue | unknown | 1,741 |
<template>
<view>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">textarea多行文本</view>
</view>
<!--主题-->
<view class="smart-padding-wrap">
<view>输入区域高度自适应,不会出现滚动条</view>
<textarea class="text-area" />
<view>占位符字体是红色的</view>
<textarea class="text-area" placeholder-style="color:#F76260" placeholder="占位符字体是红色的"/>
</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
}
}
</script>
<style>
.text-area{
border: 1px solid #D8D8D8;
width: 100%;
line-height: 100%;
}
</style>
| 2401_83220332/SmartUI_wht027 | pages/components/textarea/textarea.vue | Vue | unknown | 686 |
<template>
<view>
<!--顶部区域-->
<view class="smart-panel-head">
<view class="smart-panel-head-title">view</view>
</view>
<!--主题-->
<view class="smart-padding-wrap">
<view>flex-direction:row 横向布局</view>
<view class="smart-flex smart-row">
<view class="flex-item smart-bg-red">red</view>
<view class="flex-item smart-bg-orange">orange</view>
<view class="flex-item smart-bg-green">green</view>
</view>
<view>flex-direction:column 纵向布局</view>
<view class="smart-flex smart-column">
<view class="flex-item-c smart-bg-red">red</view>
<view class="flex-item-c smart-bg-orange">orange</view>
<view class="flex-item-c smart-bg-green">green</view>
</view>
<view>其他布局</view>
<view>
<view class="text">纵向布局-自动宽度</view>
<view class="text" style="width:300rpx;">纵向布局-固定宽度</view>
<view class="smart-flex smart-row">
<view class="text">横向布局-自动宽度</view>
<view class="text">横向布局-自动宽度</view>
</view>
<view class="smart-flex smart-row" style="justify-content: center;">
<view class="text">横向布局-居中</view>
<view class="text">横向布局-居中</view>
</view>
<view class="smart-flex smart-row" style="justify-content: flex-end;">
<view class="text">横向布局-居右</view>
<view class="text">横向布局-居右</view>
</view>
<view class="smart-flex smart-row">
<view class="text" style="flex:1;">横向布局-平均分布</view>
<view class="text" style="flex:1;">横向布局-平均分布</view>
</view>
<view class="smart-flex smart-row" style="justify-content: space-between;">
<view class="text">横向布局-两端对齐</view>
<view class="text">横向布局-两端对齐</view>
</view>
<view class="smart-flex smart-row">
<view class="text" style="width: 150rpx;">固定宽度</view>
<view class="text" style="flex:1;">自动占满</view>
</view>
<view class="smart-flex smart-row">
<view class="text" style="width: 120rpx;">固定宽度</view>
<view class="text" style="flex:1;">自动占满</view>
<view class="text" style="width: 120rpx;">固定宽度</view>
</view>
<view class="smart-flex smart-row" style="flex-wrap: wrap;">
<view class="text" style="width: 280rpx;">一行显示不全wrap折行</view>
<view class="text" style="width: 280rpx;">一行显示不全wrap折行</view>
<view class="text" style="width: 280rpx;">一行显示不全wrap折行</view>
</view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
}
}
</script>
<style>
</style> | 2401_83220332/SmartUI_wht027 | pages/components/view/view.vue | Vue | unknown | 2,752 |
<template>
<view class="first-wrap">
<view class="form">
<view class="title-text">泉州风光</view>
<swiper :indicator-dots="true" :autoplay="true" :interval="5000" :duration="500"
style="height: 400rpx;">
<swiper-item>
<image style="height: 100%;width: 100%;" src="/static/city1.png"></image>
</swiper-item>
<swiper-item>
<image style="height: 100%;width: 100%;" src="/static/city2.jpg"></image>
</swiper-item>
<swiper-item>
<image style="height: 100%;width: 100%;" src="/static/city3.jpg"></image>
</swiper-item>
<swiper-item>
<image style="height: 100%;width: 100%;" src="/static/city4.jpg"></image>
</swiper-item>
<swiper-item>
<image style="height: 100%;width: 100%;" src="/static/city5.jpg"></image>
</swiper-item>
</swiper>
</view>
<view class="form">
<view class="title-text">泉州介绍</view>
<view class="second-text">海上丝绸之路起点 - 泉州</view>
<view class="main-text">历史文化:泉州是国务院首批公布的24个历史文化名城之一,是古代“海上丝绸之路”起点,宋元时期被誉为“东方第一大港”。</view>
<view class="main-text">著名景点:清源山、开元寺、泉州清净寺、崇武古城、洛阳桥等。</view>
<rich-text class="main-text" :nodes="htmlContent"></rich-text>
</view>
<view class="form">
<view class="title-text">探索进度</view>
<view class="main-text">当前进度:50%</view>
<progress style="padding: 10rpx;" :percent="50" show-info stroke-width="3" />
</view>
<view class="form">
<view class="title-text">选择城市</view>
<view class="smart-flex smart-row">
<view class="main-text">当前选择:</view>
<picker class="main-text" mode="multiSelector" @columnchange="bindMultiPickerColumnChange" :value="multiIndex"
:range="multiArray">
<view>
{{multiArray[0][multiIndex[0]]}},{{multiArray[1][multiIndex[1]]}},{{multiArray[2][multiIndex[2]]}}
</view>
</picker>
</view>
</view>
<view class="form">
<view class="title-text">泉州宣传</view>
<video style="height: 400rpx;width: 100%;" src="/static/city-video.mp4" controls autoplay="true" loop="true" muted="true"></video>
</view>
<view class="form" >
<view class="title-text">偏好设置</view>
<view class="prefence" >
<view style="margin-right: 20rpx">出行方式:</view>
<radio-group>
<label style="margin-right: 20rpx">
<radio/><text>公交</text>
</label>
<label style="margin-right: 20rpx">
<radio/><text>自驾</text>
</label>
<label>
<radio/><text>步行</text>
</label>
</radio-group>
</view>
<view class="prefence">
<view style="margin-right: 20rpx">显示推荐景点</view>
<switch name="switch" />
</view>
<view >
<view style="margin-right: 20rpx">探索半径</view>
<slider value="50" show-value></slider>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
htmlContent: `
<p>特色文化:拥有
<a href="https://www.ihchina.cn/nanyin.html" style="color: #007AFF; text-decoration: underline;">
南音
</a >
、
<a href="https://www.ihchina.cn/project_details/13429" style="color: #007AFF; text-decoration: underline;">
木偶戏
</a >
和
<a href="https://www.ihchina.cn/project_details/14684.html" style="color: #007AFF; text-decoration: underline;">
闽南建筑
</a >
等丰富的非物质文化遗产
</p >
`,
title: 'picker',
index: 0,
multiArray: [
['中国'],
['福建'],
['泉州']
],
multiIndex: [0, 0, 0],
}
},
methods: {
}
}
</script>
<style>
.first-wrap {
display: flex;
flex-direction: column;
align-items: center;
padding: 30rpx 30rpx;
height: 100vh;
background-color: aliceblue;
}
.form {
display: flex;
flex-direction: column;
width:90%;
padding: 30rpx 30rpx;
background-color: white;
border-radius: 20rpx;
box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}
.title-text{
padding: 10rpx;
font-weight: bolder;
font-size: 60rpx;
}
.second-text{
padding: 10rpx;
font-weight: bolder;
font-size: 50rpx;
}
.main-text{
padding: 10rpx;
font-weight: normal;
font-size: 40rpx;
}
.uni-picker-tips {
font-size: 12px;
color: #666;
margin-bottom: 15px;
padding: 0 15px;
/* text-align: right; */
}
.mp4.wrap{
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
}
.prefence{
display: flex;
flex-direction: row;
border-bottom: 2rpx solid #d8d8d8;
padding: 30rpx 10rpx;
}
</style> | 2401_83220332/SmartUI_wht027 | pages/demos/cityexploration/cityexploration.vue | Vue | unknown | 4,689 |
<template>
<view class="container">
<view class="form">
<text class="title">登录</text>
<input class="input" placeholder="请输入用户名" v-model="username"/>
<input class="input" placeholder="请输入密码" password v-model="password"/>
<button class="btn" type="primary" @click="handleLogin">登录</button>
<view class="link">
<text>没有账号?</text>
<navigator url="/pages/demos/register/register" open-type="navigate">去注册</navigator>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
username: 'wht',
password: '123456'
}
},
methods: {
handleLogin() {
if (!this.username || !this.password) {
uni.showToast({
title: '请输入完整信息',
icon: 'none'
})
return
}
else{
if(this.username==="wht"&&this.password==="123456"){
uni.showToast({
title: '登录成功',
icon: 'success'
})
setTimeout(() => {
uni.switchTab({
// url: "/pages/tabBar/tabcompage/tabcompage"
url: "/news_pages/Tabar/home/home"
})
}, 1500)
}
else{
uni.showToast({
title: '登录失败,账号或密码错误',
icon: 'error'
})
}
}
}
}
}
</script>
<style>
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f5f5f5;
}
.form {
display: flex;
flex-direction: column;
width: 80%;
padding: 40rpx;
background-color: white;
border-radius: 20rpx;
box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}
.title {
font-size: 48rpx;
font-weight: bold;
text-align: center;
margin-bottom: 60rpx;
color: #333;
}
.input {
height: 80rpx;
border: 2rpx solid #e0e0e0;
border-radius: 10rpx;
padding: 0 20rpx;
margin-bottom: 30rpx;
font-size: 28rpx;
}
.input:focus {
border-color: #007AFF;
}
.btn {
height: 80rpx;
border-radius: 10rpx;
margin-top: 20rpx;
font-size: 32rpx;
background-color: #007AFF;
}
.link {
display: flex;
justify-content: center;
align-items: center;
margin-top: 40rpx;
font-size: 28rpx;
}
.link text {
color: #666;
}
.link navigator {
color: #007AFF;
margin-left: 10rpx;
}
</style> | 2401_83220332/SmartUI_wht027 | pages/demos/login/login.vue | Vue | unknown | 2,379 |
<template>
<view style="color:#fbffef">
<view class="tab">
<scroll-view class="scroll-x" scroll-x="true">
<view class="topBar">
<view>要文</view>
<view>推荐</view>
<view>关注流</view>
<view>24小时</view>
<view>娱乐</view>
<view>桂林</view>
<view>财经</view>
<view>军事</view>
<view>科技</view>
<view>汽车</view>
<view>音乐</view>
<view>体育</view>
<view>生活</view>
</view>
</scroll-view>
<view class="weather-search-container" >
<view class="weather-container" @click="getWeather()">
<view class="weather-info"v-if="weatherData">
<view >
<text>{{ weatherData.time}}/</text>
<text>{{ weatherData.cityInfo.city }}/</text>
<text>{{ weatherData.data.wendu }}°/</text>
<text>{{ weatherData.data.forecast[0].type }}/</text>
<text>{{ weatherData.data.quality }}/</text>
<text>{{ weatherData.data.forecast[0].high }}/</text>
<text>{{ weatherData.data.forecast[0].low }}/</text>
<text>{{ weatherData.data.forecast[0].fx }}{{ weatherData.data.forecast[0].fl }}</text>
</view>
</view>
<view class="weather-loading" v-else-if="loading">
<text>获取天气中...</text>
</view>
<view class="weather-placeholder" v-else>
<text>点击获取天气</text>
</view>
</view>
<view class="search-container">
<input type="text" class="search" placeholder="搜索关键词"></input>
</view>
</view>
</view>
<view class="refresh">为您更新了15条内容</view>
<view v-for="item in newsList" style="margin:10rpx">
<cardTopVue :title="item.title" :isTop="item.isTop" :author="item.author" :comments="item.comments"
:time="item.time" :mode="item.newstype" :images="item.imagelist" :showSearch="item.showSearch"
:bgColor="item.bgcolor">
<template v-slot:tips>
<view v-if="item.showSearch" class="slotcontent">
<text>搜索:</text>
<view class="borderbox"><text>今日好价</text></view>
<view class="borderbox"><text>精选好物</text></view>
</view>
</template>
</cardTopVue>
</view>
</view>
</template>
<script>
import cardTopVue from '../../../components/cardViewText.vue'
export default {
components: {
cardTopVue
},
data() {
return {
newsList: [],
weatherData: null,
loading: false
}
},
onLoad() {
this.newsList = getApp().globalData.datalist;
console.log("onLoad--> newsList: " + this.newsList.length);
// 页面加载时自动获取天气
this.getWeather();
},
methods: {
getWeather() {
this.loading = true;
uni.request({
url: 'http://t.weather.sojson.com/api/weather/city/101230501',
success: (res) => {
console.log("success-----" + JSON.stringify(res));
if (res.data.status === 200) {
this.weatherData = res.data;
} else {
uni.showToast({
title: '天气数据获取失败',
icon: 'none'
});
}
this.loading = false;
},
fail: (eMsg) => {
console.log("request fail-----" + eMsg);
uni.showToast({
title: '网络错误,请重试',
icon: 'none'
});
this.loading = false;
}
});
}
}
}
</script>
<style>
.tab {
background-color: #d04500;
width: 100%;
padding: 10rpx;
}
.topBar {
display: flex;
flex-direction: row;
gap: 20rpx;
line-height: 60rpx;
}
.weather-search-container {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
margin-top: 15rpx;
}
.weather-container {
flex: 1;
padding: 15rpx;
background-color: rgba(255, 255, 255, 0.2);
border-radius: 15rpx;
margin-right: 20rpx;
}
.weather-info .city {
font-size: 26rpx;
font-weight: bold;
margin-bottom: 8rpx;
}
.weather-info .temp {
display: flex;
font-size: 36rpx;
font-weight: bold;
margin-bottom: 10rpx;
}
.weather-desc {
display: flex;
flex-direction: row;
align-items: center;
margin-bottom: 10rpx;
}
.weather-type {
font-size: 24rpx;
margin-right: 15rpx;
}
.air-quality {
font-size: 20rpx;
background-color: #4CAF50;
padding: 4rpx 10rpx;
border-radius: 10rpx;
}
.weather-details {
display: flex;
flex-direction: column;
font-size: 20rpx;
color: rgba(255, 255, 255, 0.8);
}
.weather-loading, .weather-placeholder {
font-size: 26rpx;
text-align: center;
padding: 20rpx 0;
}
.refresh {
padding: 15rpx;
background-color: #ffaa7f;
}
.search {
width: 230rpx;
margin-right: 20rpx;
font-size: 25rpx;
text-align: center;
background-color: aliceblue;
border-radius: 20rpx;
}
.slotcontent {
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
text-align: center;
padding-left: 10px;
color: #aaf;
font-size: 20rpx;
}
.borderbox {
margin: 5px;
border-radius: 5px;
border: 1px solid gray;
}
</style> | 2401_83220332/SmartUI_wht027 | pages/demos/news/news.vue | Vue | unknown | 4,976 |
<template>
<view class="container">
<view class="form">
<text class="title">注册</text>
<input class="input" placeholder="请输入用户名" v-model="username"/>
<input class="input" placeholder="请输入密码" password v-model="password"/>
<input class="input" placeholder="请确认密码" password v-model="confirmPassword"/>
<button class="btn" type="primary" @click="handleRegister">注册</button>
<view class="link">
<text>已有账号?</text>
<navigator url="/pages/demos/login/login" open-type="navigateBack">去登录</navigator>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
username: '',
password: '',
confirmPassword: '',
}
},
methods: {
handleRegister() {
if (!this.username || !this.password || !this.confirmPassword) {
uni.showToast({
title: '请输入完整信息',
icon: 'none'
})
return
}
if (this.password !== this.confirmPassword) {
uni.showToast({
title: '两次密码输入不一致',
icon: 'none'
})
return
}
// 这里可以添加实际的注册逻辑
uni.showToast({
title: '注册成功',
icon: 'success'
})
// 注册成功后跳转到登录页
setTimeout(() => {
uni.navigateBack()
}, 1500)
}
}
}
</script>
<style>
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f5f5f5;
}
.form {
display: flex;
flex-direction: column;
width: 80%;
padding: 40rpx;
background-color: white;
border-radius: 20rpx;
box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}
.title {
font-size: 48rpx;
font-weight: bold;
text-align: center;
margin-bottom: 60rpx;
color: #333;
}
.input {
height: 80rpx;
border: 2rpx solid #e0e0e0;
border-radius: 10rpx;
padding: 0 20rpx;
margin-bottom: 30rpx;
font-size: 28rpx;
}
.input:focus {
border-color: #007AFF;
}
.btn {
height: 80rpx;
border-radius: 10rpx;
margin-top: 20rpx;
font-size: 32rpx;
background-color: #007AFF;
}
.link {
display: flex;
justify-content: center;
align-items: center;
margin-top: 40rpx;
font-size: 28rpx;
}
.link text {
color: #666;
}
.link navigator {
color: #007AFF;
margin-left: 10rpx;
}
</style> | 2401_83220332/SmartUI_wht027 | pages/demos/register/register.vue | Vue | unknown | 2,472 |
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{title}}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
},
methods: {
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
| 2401_83220332/SmartUI_wht027 | pages/index/index.vue | Vue | unknown | 694 |
<template>
<view>
<navigator url="/pages/APIpages/LogPage/LogPage"><button>打印日志</button></navigator>
<navigator url="/pages/APIpages/TimePage/TimePage"><button>计时器</button></navigator>
<navigator url="/pages/APIpages/StoragePage/StoragePage"><button>数据缓存</button></navigator>
<navigator url="/pages/APIpages/RefreshPage/RefreshPage">
<button type="primary">页面刷新</button>
</navigator>
</view>
</template>
<script>
export default {
data() {
return {
}
},
onLoad() {
uni.preloadPage({
url:"/pages/APIpages/StoragePage/StoragePage"
})
},
methods: {
goStoPage() {
uni.navigateTo({
url: "/pages/APIpages/StoragePage/StoragePage",
success() {
console.log("navigateTo--->success");
},
fail(e) {
console.log("navigateTo--->fail: " + JSON.stringify(e));
},
complete() {
console.log("navigateTo--->complete");
}
})
}
}
}
</script>
<style>
</style> | 2401_83220332/SmartUI_wht027 | pages/tabBar/api/api.vue | Vue | unknown | 982 |
<template>
<view>
<view class="button-wrap">
<view class="form">
<image :src="iconPath" @click="updateImage()" mode="aspectFill"
style="width: 150rpx; height: 150rpx; margin: 20rpx; border-radius: 75rpx;"></image>
<button @click="chooseImage()">
预览图片
</button>
<button @click="downLoad()">
下载
</button>
</view>
<navigator url="/pages/demos/login/login" open-type="redirect">
<button type="default">登录注册页</button>
</navigator>
<navigator url="/pages/demos/cityexploration/cityexploration" open-type="navigate">
<button type="default">城市探索</button>
</navigator>
<navigator url="/pages/demos/news/news" open-type="navigate">
<button type="default">新闻</button>
</navigator>
<navigator url="/pages/demos/zjcz/IntentPage/IntentPage" open-type="navigate">
<button type="default">组件传值</button>
</navigator>
</view>
</view>
</template>
<script>
export default {
data() {
return {
iconPath: "/static/logo.png",
chooseImages: []
}
},
methods: {
updateImage() {
uni.chooseImage({
count: 1,
sourceType: ['album'],
success: (res) => {
console.log(JSON.stringify(res.tempFilePaths[0]));
this.iconPath = res.tempFilePaths[0];
this.chooseImages = res.tempFilePaths;
uni.previewImage({
urls: res.tempFilePaths,
});
}
});
},
chooseImage() {
uni.chooseImage({
count: 2,
sourceType: ['album'],
success: (res) => {
// 预览图片
uni.previewImage({
urls: res.tempFilePaths,
});
}
});
},
downLoad(){
const imagetask = uni.downloadFile({
url: "https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg",
success: (res) => {
if (res.statusCode === 200) {
console.log('下载成功');
uni.previewImage({
urls: [res.tempFilePath]
});
this.iconFilePath = res.tempFilePath;
}
},
fail: (err) => {
console.error('下载失败:', err);
}
});
// 监听下载进度
imagetask.onProgressUpdate((res) => {
console.log('下载进度:', res.progress + "%"); // 进度百分比
console.log('已下载:', res.totalBytesWritten);
console.log('总大小:', res.totalBytesExpectedToWrite);
});
}
}
}
</script>
<style>
.button-wrap {
padding: 30rpx 30rpx;
}
.form {
border-radius: 30rpx;
background: #00ffff;
}
</style> | 2401_83220332/SmartUI_wht027 | pages/tabBar/demospage/demospage.vue | Vue | unknown | 2,509 |
<template>
<view class="content">
<image :class="className" src="/static/logo.png"></image>
<view class="text-area">
<text class="title" @:click="open">{{title}}</text>
</view>
<view>
<view>{{ number + 1 }}</view>
<view>{{ok?"YES":"NO"}}</view>
<view>{{message.split('').reverse().join('')}}</view>
</view>
<view v-if="!raining">今天天气真好</view>
<view v-if="raining">下雨天,天气很糟糕</view>
<view v-if="state=='vue'">State的值是Vue</view>
<view v-if="state=='vue'">State的值是Vue</view>
<view>State is {{state?'vue':'APP'}}</view>
<view>
<view v-if="state=='vue'"uni-app></view>
<view v-else-if="state=='html'">HTML</view>
<view v-else>APP</view>
</view>
<view class="content">
<view v-for="item in arr" style="color:#00ffff;">
{{item}}
</view>
<view v-for="(item,index) in 4" style="color:#00ff00;">
<view :class="'list-' + index%2">{{index%2}}</view>
</view>
<view v-for="(item,index) in 4" style="color:#ffaaff;">
<view :class="'list-' + index%2">{{index%2}}</view>
</view>
<view v-for="(value,name,index) in object" style="color:#5500ff;">
{{index}}.{{name}}:{{value}}
</view>
<view v-for="(value,name,index) in object" style="color:#5500ff;">
{{index}}---{{name}}---{{value}}
</view>
<view v-for="item in arr" :key="item.id">
<view style="color: #00ffff;">{{item.id}}:{{item.name}}</view>
</view>
</view>
</view>
</template>
<script>
export default {
data() {
return {
title:'Hello UniAPP',
className:'smalllogo',
number:3,
ok:1==2,
message:'Hello Vue!',
raining:false,
state:'vue',
arr:[
{id:1,name:"uni-app"},
{id:2,name:"HTML"}
],
object:{
title:"how to lists in Vue?",
author:"Jane Doe",
publishedAt:'2020-04-10'
}
}
},
methods: {
open(){
this.title="opening a new Page";
this.className = "logo"
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.smalllogo{
height:100rpx;
width:100rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
</style>
| 2401_83220332/SmartUI_wht027 | pages/tabBar/grammar/grammar.vue | Vue | unknown | 2,360 |
<template>
<view>
<view class="smart-container">组件</view>
<view class="smart-panel-title"@click="goDetailPage('cardTop')"><text>置顶卡片组件</text></view>
<view class="smart-panel-title"@click="goDetailPage('IntentPage')"><text>组件传值</text></view>
</view>
<view>
<view class="smart-container">1.容器</view>
<view class="smart-panel-title"@click="goDetailPage('view')"><text>view视图</text></view>
<view class="smart-panel-h"@click="goDetailPage('scroll-view')"><text>scroll-view滚动视图</text></view>
<view class="smart-panel-h"@click="goDetailPage('swiper')"><text>swiper可滑动视图</text></view>
</view>
<view>
<view class="smart-container">2.基础内容</view>
<view class="smart-panel-title"@click="goDetailPage('text')"><text>text文本编辑</text></view>
<view class="smart-panel-h"@click="goDetailPage('icon')"><text>icon图标</text></view>
</view>
<view>
<view class="smart-container">3.表单组件</view>
<view class="smart-panel-title"@click="goDetailPage('button')"><text>button按钮</text></view>
<view class="smart-panel-h"@click="goDetailPage('checkbox')"><text>checkbox复选框</text></view>
<view class="smart-panel-h"@click="goDetailPage('label')"><text>label标签组件</text></view>
<view class="smart-panel-h"@click="goDetailPage('input')"><text>input输入框</text></view>
<view class="smart-panel-h"@click="goDetailPage('textarea')"><text>textarea多文本输入框</text></view>
<view class="smart-panel-h"@click="goDetailPage('from')"><text>from表单</text></view>
</view>
<view>
<view class="smart-container">4.导航组件</view>
<view class="smart-panel-title"@click="goDetailPage('navigator')"><text>navigator</text></view>
</view>
</template>
<script>
export default {
data() {
return {
}
},
methods: {
goDetailPage(e) {
if (typeof e === 'string') {
uni.navigateTo({
url: '/pages/components/' + e + '/' + e
});
} else {
uni.navigateTo({
url: e.url
});
}
}
}
}
</script>
<style>
</style> | 2401_83220332/SmartUI_wht027 | pages/tabBar/tabcompage/tabcompage.vue | Vue | unknown | 2,071 |
uni.addInterceptor({
returnValue (res) {
if (!(!!res && (typeof res === "object" || typeof res === "function") && typeof res.then === "function")) {
return res;
}
return new Promise((resolve, reject) => {
res.then((res) => {
if (!res) return resolve(res)
return res[0] ? reject(res[0]) : resolve(res[1])
});
});
},
}); | 2401_83220332/SmartUI_wht027 | uni.promisify.adaptor.js | JavaScript | unknown | 373 |
/**
* 这里是uni-app内置的常用样式变量
*
* uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量
* 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App
*
*/
/**
* 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能
*
* 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件
*/
/* 颜色变量 */
/* 行为相关颜色 */
$uni-color-primary: #007aff;
$uni-color-success: #4cd964;
$uni-color-warning: #f0ad4e;
$uni-color-error: #dd524d;
/* 文字基本颜色 */
$uni-text-color:#333;//基本色
$uni-text-color-inverse:#fff;//反色
$uni-text-color-grey:#999;//辅助灰色,如加载更多的提示信息
$uni-text-color-placeholder: #808080;
$uni-text-color-disable:#c0c0c0;
/* 背景颜色 */
$uni-bg-color:#ffffff;
$uni-bg-color-grey:#f8f8f8;
$uni-bg-color-hover:#f1f1f1;//点击状态颜色
$uni-bg-color-mask:rgba(0, 0, 0, 0.4);//遮罩颜色
/* 边框颜色 */
$uni-border-color:#c8c7cc;
/* 尺寸变量 */
/* 文字尺寸 */
$uni-font-size-sm:12px;
$uni-font-size-base:14px;
$uni-font-size-lg:16px;
/* 图片尺寸 */
$uni-img-size-sm:20px;
$uni-img-size-base:26px;
$uni-img-size-lg:40px;
/* Border Radius */
$uni-border-radius-sm: 2px;
$uni-border-radius-base: 3px;
$uni-border-radius-lg: 6px;
$uni-border-radius-circle: 50%;
/* 水平间距 */
$uni-spacing-row-sm: 5px;
$uni-spacing-row-base: 10px;
$uni-spacing-row-lg: 15px;
/* 垂直间距 */
$uni-spacing-col-sm: 4px;
$uni-spacing-col-base: 8px;
$uni-spacing-col-lg: 12px;
/* 透明度 */
$uni-opacity-disabled: 0.3; // 组件禁用态的透明度
/* 文章场景相关 */
$uni-color-title: #2C405A; // 文章标题颜色
$uni-font-size-title:20px;
$uni-color-subtitle: #555555; // 二级标题颜色
$uni-font-size-subtitle:26px;
$uni-color-paragraph: #3F536E; // 文章段落颜色
$uni-font-size-paragraph:15px;
| 2401_83220332/SmartUI_wht027 | uni.scss | SCSS | unknown | 2,217 |
import gradio as gr
# 定义 JS 函数:验证输入是否为空 + 修改按钮样式
validate_input_js = """
function(input_value, button_element) {
// input_value:对应 inputs 中传入的 Textbox 值
// button_element:对应触发事件的按钮 DOM 元素
if (!input_value) {
alert("输入不能为空!"); // 弹窗提示
button_element.style.backgroundColor = "red"; // 修改按钮背景色
return false; // 阻止后续 Python 函数执行
} else {
button_element.style.backgroundColor = "green";
console.log("输入有效:", input_value);
return input_value; // 传递值给后续 Python 函数
}
}
"""
with gr.Blocks() as demo:
input_box = gr.Textbox(label="请输入内容")
submit_btn = gr.Button("提交", elem_id="submit-btn") # 给组件加 elem_id,方便 JS 定位
# 按钮点击事件:先执行 JS 验证,再执行 Python 函数
submit_btn.click(
fn=lambda x: f"你输入的是:{x}", # Python 逻辑
inputs=input_box,
outputs=gr.Textbox(label="输出结果"),
js=validate_input_js # 关键:绑定 JS 函数(参数顺序=inputs+触发组件)
)
if __name__ == "__main__":
demo.launch() | 2401_83827989/You-Hack | 1.py | Python | unknown | 1,228 |
"""
失物招领系统主应用文件
此文件使用 Gradio 构建了一个基于 Web 的失物招领系统界面。
用户可以上传失物图片、搜索失物以及认领物品。
系统集成了 AI 图像识别功能,能够自动识别物品标签并建议名称。
主要功能:
- 上传失物:支持图片上传,AI 自动识别标签,生成物品名称和备注
- 查找失物:根据关键词搜索已上传的失物
- 所有失物:查看所有未认领的失物列表
- 认领物品:用户可以认领找到的物品
依赖模块:
- gradio: 用于构建 Web 界面
- db_operations: 数据库操作模块
- image_recognizer: AI 图像识别模块
"""
import gradio as gr
import base64
from db_operations import (
init_db, add_item, search_items, get_all_items,
delete_item, item_exists
)
from image_recognizer import recognize_image_tags
def upload_and_process(image, name, location, note):
"""
处理用户上传的失物图片和信息
此函数接收用户上传的图片和相关信息,使用 AI 识别图片标签,
生成最终的物品名称和备注,然后将物品保存到数据库中。
参数:
image (str): 上传图片的文件路径
name (str): 用户输入的物品名称(可选)
location (str): 物品放置地点
note (str): 用户输入的备注信息(可选)
返回:
str: 处理结果消息,成功时返回确认信息,失败时返回错误提示
处理流程:
1. 检查图片是否上传
2. 调用 AI 识别获取标签
3. 确定最终物品名称(用户输入优先,否则使用 AI 识别结果)
4. 生成备注信息(包含 AI 标签)
5. 将图片读取为二进制数据并保存到数据库
"""
if image is None:
return "请上传图片"
# 👇 核心修改:用户没输名称时,用AI识别结果的第一个词当名称
tags = recognize_image_tags(image) # 获取AI识别的标签(已按逗号分隔、频率排序)
ai_name = ""
if tags: # 如果AI返回了结果
# 提取第一个词作为物品名称(比如AI返回"苹果手机,手机,苹果,电话,iPhone",取"苹果手机")
ai_name = tags[0].strip()
# 最终名称:用户输入优先,没输入则用AI第一个词,还没有就提示错误
final_name = name.strip() if name.strip() else ai_name
if not final_name:
return "请提供物品名称,或确保图片能被AI识别出有效名称"
# 处理备注(保留AI所有标签)
if tags:
ai_note = "AI识别标签: " + ", ".join(tags)
note = f"{note}; {ai_note}" if note else ai_note
else:
note = note if note else "无AI识别结果"
# 保存到数据库
with open(image, 'rb') as f:
image_binary = f.read()
add_item(image_binary, final_name, location, note)
return f"上传成功,物品名称:{final_name}"
def format_items_html(items):
"""
将物品列表格式化为 HTML 表格显示
参数:
items (list): 物品记录列表,每个记录包含 (id, image, name, location, note)
返回:
str: HTML 格式的表格字符串
"""
if not items:
return "<p>未找到匹配的失物</p>"
html = "<table style='border-collapse: collapse; width: 100%;'>"
html += "<tr><th style='border: 1px solid #ddd; padding: 8px;'>ID</th><th style='border: 1px solid #ddd; padding: 8px;'>图片</th><th style='border: 1px solid #ddd; padding: 8px;'>名称</th><th style='border: 1px solid #ddd; padding: 8px;'>地点</th><th style='border: 1px solid #ddd; padding: 8px;'>备注</th></tr>"
for item_id, image_binary, name, location, note in items:
# 将图片二进制数据编码为 base64
image_base64 = base64.b64encode(image_binary).decode('utf-8')
image_html = f"<img src='data:image/jpeg;base64,{image_base64}' style='max-width: 100px; max-height: 100px;'>"
html += f"<tr><td style='border: 1px solid #ddd; padding: 8px;'>{item_id}</td><td style='border: 1px solid #ddd; padding: 8px;'>{image_html}</td><td style='border: 1px solid #ddd; padding: 8px;'>{name}</td><td style='border: 1px solid #ddd; padding: 8px;'>{location}</td><td style='border: 1px solid #ddd; padding: 8px;'>{note}</td></tr>"
html += "</table>"
return html
def search_items_handler(query):
"""
处理用户搜索失物的请求
根据用户输入的查询关键词,在数据库中搜索匹配的失物,
并将结果格式化为 HTML 显示。
参数:
query (str): 用户输入的搜索关键词
返回:
str: HTML 格式的搜索结果
"""
if not query.strip():
return "<p>请输入搜索关键词</p>"
items = search_items(query.strip())
return format_items_html(items)
def claim_item_in_search(item_id_str, search_query):
"""
处理在搜索页面认领物品的请求
当用户在搜索结果中点击认领按钮时,此函数会删除数据库中对应的物品记录,
然后重新执行搜索以更新显示结果。
参数:
item_id_str (str): 要认领的物品 ID 字符串
search_query (str): 当前的搜索查询关键词,用于重新搜索
返回:
tuple: (重新搜索后的结果 HTML, 认领结果消息)
"""
try:
item_id = int(item_id_str.strip())
except ValueError:
return search_items_handler(search_query), "请输入有效的物品 ID"
if item_exists(item_id):
delete_item(item_id)
return search_items_handler(search_query), f"物品 ID {item_id} 已成功认领"
else:
return search_items_handler(search_query), f"物品 ID {item_id} 不存在"
def claim_item_in_all(item_id_str):
"""
处理在所有物品页面认领物品的请求
当用户在所有物品列表中点击认领按钮时,此函数会删除数据库中对应的物品记录,
然后返回更新后的所有物品列表。
参数:
item_id_str (str): 要认领的物品 ID 字符串
返回:
tuple: (更新后的所有物品 HTML 列表, 认领结果消息)
"""
try:
item_id = int(item_id_str.strip())
except ValueError:
items = get_all_items()
return format_items_html(items), "请输入有效的物品 ID"
if item_exists(item_id):
delete_item(item_id)
items = get_all_items()
return format_items_html(items), f"物品 ID {item_id} 已成功认领"
else:
items = get_all_items()
return format_items_html(items), f"物品 ID {item_id} 不存在"
# 初始化数据库
init_db()
# 创建Gradio界面
with gr.Blocks() as demo:
gr.Markdown("### 失物招领系统")
with gr.Tab("上传失物"):
file = gr.Image(type="filepath", label="上传捡到的物品图片")
name = gr.Textbox(label="物品名称")
location = gr.Textbox(label="放置地点")
note = gr.Textbox(label="备注信息")
submit_upload = gr.Button("提交")
upload_output = gr.Textbox(label="处理结果")
submit_upload.click(upload_and_process,
inputs=[file, name, location, note],
outputs=upload_output)
with gr.Tab("查找失物"):
search_query = gr.Textbox(label="搜索关键词")
search_button = gr.Button("搜索")
search_results = gr.HTML(label="搜索结果")
search_button.click(search_items_handler,
inputs=search_query,
outputs=search_results)
claim_id_search = gr.Textbox(label="要认领的物品 ID")
claim_button_search = gr.Button("认领物品")
claim_output_search = gr.Textbox(label="认领结果")
claim_button_search.click(claim_item_in_search,
inputs=[claim_id_search, search_query],
outputs=[search_results, claim_output_search])
with gr.Tab("所有失物"):
all_items_display = gr.HTML(value=format_items_html(get_all_items()), label="所有失物")
claim_id_all = gr.Textbox(label="要认领的物品 ID")
claim_button_all = gr.Button("认领物品")
claim_output_all = gr.Textbox(label="认领结果")
claim_button_all.click(claim_item_in_all,
inputs=claim_id_all,
outputs=[all_items_display, claim_output_all])
if __name__ == "__main__":
demo.launch()
| 2401_83827989/You-Hack | app(2.0).py | Python | unknown | 8,797 |
"""
数据库模块
此模块定义了一个简单的 SQLite 数据库操作类 Database,
用于管理失物招领系统的物品数据存储。
主要功能:
- 连接到 SQLite 数据库
- 获取所有物品记录
- 添加新物品记录
- 关闭数据库连接
依赖:
- sqlite3: Python 内置的 SQLite 数据库模块
"""
import sqlite3
class Database:
"""
SQLite 数据库操作类
提供基本的数据库操作方法,包括连接、查询、插入和关闭连接。
数据库文件默认为 'lost_and_found.db'。
"""
def __init__(self, db_path='lost_and_found.db'):
"""
初始化数据库连接
创建到 SQLite 数据库的连接,并创建游标对象用于执行 SQL 语句。
参数:
db_path (str): 数据库文件路径,默认为 'lost_and_found.db'
"""
self.conn = sqlite3.connect(db_path)
self.cursor = self.conn.cursor()
def get_all_items(self):
"""
获取所有物品记录
执行 SQL 查询获取 items 表中的所有记录。
返回:
list: 包含所有物品记录的列表,每个记录为元组形式
"""
self.cursor.execute('SELECT * FROM items')
return self.cursor.fetchall()
def add_item(self, image_blob, description):
"""
添加新物品记录到数据库
将图片二进制数据和描述信息插入到 items 表中。
参数:
image_blob (bytes): 物品图片的二进制数据
description (str): 物品的描述信息
"""
self.cursor.execute('INSERT INTO items (image, description) VALUES (?, ?)',
(image_blob, description))
self.conn.commit()
def close(self):
"""
关闭数据库连接
关闭游标和数据库连接,释放资源。
"""
self.cursor.close()
self.conn.close()
# 调用示例
if __name__ == '__main__':
db = Database()
items = db.get_all_items()
print(items)
db.close()
| 2401_83827989/You-Hack | database.py | Python | unknown | 2,164 |
"""
数据库操作模块
此模块提供失物招领系统数据库的各种操作函数,
包括数据库初始化、物品的增删改查、搜索和 HTML 格式化等功能。
主要功能:
- 初始化数据库表结构
- 添加、删除、查询物品记录
- 搜索物品(支持名称和备注模糊匹配)
- 将物品列表格式化为 HTML 表格显示
依赖模块:
- sqlite3: SQLite 数据库操作
- base64: 图片数据编码
"""
import sqlite3
import base64
def init_db():
"""
初始化数据库表结构
创建名为 'items' 的 SQLite 表(如果不存在),包含以下字段:
- id: 主键,自增整数
- image: 图片二进制数据
- name: 物品名称
- location: 放置地点
- note: 备注信息
数据库文件:lost_and_found.db
"""
conn = sqlite3.connect('lost_and_found.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS items
(id INTEGER PRIMARY KEY AUTOINCREMENT,
image BLOB,
name TEXT,
location TEXT,
note TEXT)''')
conn.commit()
conn.close()
def add_item(image_binary, name, location, note):
"""
添加物品到数据库
将新的失物信息插入到数据库的 items 表中。
参数:
image_binary (bytes): 物品图片的二进制数据
name (str): 物品名称
location (str): 物品放置地点
note (str): 备注信息
"""
conn = sqlite3.connect('lost_and_found.db')
cursor = conn.cursor()
cursor.execute("INSERT INTO items (image, name, location, note) VALUES (?,?,?,?)",
(image_binary, name, location, note))
conn.commit()
conn.close()
def search_items(query):
"""
搜索物品
根据查询关键词在物品名称和备注中进行模糊搜索(不区分大小写)。
参数:
query (str): 搜索关键词
返回:
list: 匹配的物品记录列表,每个记录包含 (id, image, name, location, note)
"""
conn = sqlite3.connect('lost_and_found.db')
cursor = conn.cursor()
cursor.execute(
"SELECT id, image, name, location, note FROM items WHERE LOWER(name) LIKE LOWER(?) OR LOWER(note) LIKE LOWER(?)",
('%' + query + '%', '%' + query + '%'))
results = cursor.fetchall()
conn.close()
return results
def get_all_items():
"""
获取所有物品
查询数据库中所有的物品记录。
返回:
list: 所有物品记录的列表,每个记录包含 (id, image, name, location, note)
"""
conn = sqlite3.connect('lost_and_found.db')
cursor = conn.cursor()
cursor.execute("SELECT id, image, name, location, note FROM items")
results = cursor.fetchall()
conn.close()
return results
def delete_item(item_id):
"""
删除物品
根据物品 ID 从数据库中删除对应的记录。
参数:
item_id (int): 要删除的物品 ID
"""
conn = sqlite3.connect('lost_and_found.db')
cursor = conn.cursor()
cursor.execute("DELETE FROM items WHERE id = ?", (item_id,))
conn.commit()
conn.close()
def item_exists(item_id):
"""
检查物品是否存在
根据物品 ID 查询数据库,判断该物品是否已存在。
参数:
item_id (int): 要检查的物品 ID
返回:
bool: 如果物品存在返回 True,否则返回 False
"""
conn = sqlite3.connect('lost_and_found.db')
cursor = conn.cursor()
cursor.execute("SELECT name FROM items WHERE id = ?", (item_id,))
result = cursor.fetchone()
conn.close()
return result is not None
if __name__ == '__main__':
# 示例代码
init_db()
print(len(get_all_items()))
delete_item(1)
print(len(get_all_items())) | 2401_83827989/You-Hack | db_operations.py | Python | unknown | 4,003 |
"""
图像识别模块
此模块使用讯飞星火大模型 API 进行图像内容识别,
能够分析上传的图片并返回可能的物品标签列表。
主要功能:
- 连接讯飞星火 WebSocket API
- 上传图片并获取 AI 识别结果
- 解析识别结果,返回物品标签列表
依赖模块:
- websocket: WebSocket 客户端
- PIL: 图像处理
- base64: 数据编码
- hmac, hashlib: 签名生成
- ssl: SSL 连接支持
注意:需要配置正确的 appid, api_key, api_secret 参数
"""
import base64
import json
import time
import ssl
import websocket
from PIL import Image
from io import BytesIO
from datetime import datetime
from time import mktime
from urllib.parse import urlparse, urlencode
from wsgiref.handlers import format_date_time
import hmac
import hashlib
import _thread as thread
# 配置参数
appid = ""
api_secret = ""
api_key = ""
imageunderstanding_url = "wss://spark-api.cn-huabei-1.xf-yun.com/v2.1/image"
# 全局变量存储识别结果
ai_result = ""
is_complete = False
class Ws_Param(object):
"""
WebSocket 参数类
用于生成讯飞星火 API 的认证参数和请求 URL。
处理 API 密钥签名和授权头部的生成。
"""
def __init__(self, APPID, APIKey, APISecret, url):
"""
初始化 WebSocket 参数
参数:
APPID (str): 应用 ID
APIKey (str): API 密钥
APISecret (str): API 密钥
url (str): WebSocket URL
"""
self.APPID = APPID
self.APIKey = APIKey
self.APISecret = APISecret
self.host = urlparse(url).netloc
self.path = urlparse(url).path
self.url = url
def create_url(self):
"""
生成带认证参数的 WebSocket URL
使用 HMAC-SHA256 算法生成签名,并构建包含授权信息的完整 URL。
返回:
str: 带认证参数的 WebSocket URL
"""
now = datetime.now()
date = format_date_time(mktime(now.timetuple()))
signature_origin = f"host: {self.host}\ndate: {date}\nGET {self.path} HTTP/1.1"
signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
digestmod=hashlib.sha256).digest()
signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')
authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'
authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
v = {
"authorization": authorization,
"date": date,
"host": self.host
}
return self.url + '?' + urlencode(v)
def on_error(ws, error):
"""WebSocket 错误回调函数"""
print(f"### 错误: {error}")
def on_close(ws, one, two):
"""WebSocket 关闭回调函数"""
global is_complete
is_complete = True
def on_open(ws):
"""WebSocket 连接建立回调函数"""
thread.start_new_thread(run, (ws,))
def run(ws, *args):
"""发送识别请求到 WebSocket"""
data = json.dumps(gen_params(appid=ws.appid, question=ws.question))
ws.send(data)
def on_message(ws, message):
"""WebSocket 消息接收回调函数"""
global ai_result, is_complete
data = json.loads(message)
code = data['header']['code']
if code != 0:
print(f'请求错误: {code}, {data}')
ws.close()
else:
choices = data["payload"]["choices"]
status = choices["status"]
content = choices["text"][0]["content"]
ai_result += content
if status == 2:
ws.close()
is_complete = True
def gen_params(appid, question):
"""
生成 API 请求参数
构建发送给讯飞星火 API 的参数字典,包含应用 ID、模型参数和消息内容。
参数:
appid (str): 应用 ID
question (list): 消息列表,包含图片和文本内容
返回:
dict: API 请求参数字典
"""
return {
"header": {"app_id": appid},
"parameter": {
"chat": {
"domain": "imagev3",
"temperature": 0.5,
"top_k": 4,
"max_tokens": 2028,
"auditing": "default"
}
},
"payload": {"message": {"text": question}}
}
def recognize_image_tags(image_path):
"""
识别图片内容并返回物品标签列表
此函数接收图片路径,使用讯飞星火大模型 API 进行图像识别,
解析 AI 返回的结果,提取可能的物品名称标签。
处理流程:
1. 读取并预处理图片(转换为 RGB 格式,压缩尺寸,编码为 base64)
2. 构建识别请求消息
3. 建立 WebSocket 连接并发送请求
4. 等待并接收 AI 响应
5. 解析响应结果,返回标签列表(最多 5 个)
参数:
image_path (str): 图片文件的路径
返回:
list: 识别出的物品标签列表,每个标签为字符串。如果识别失败,返回空列表。
"""
global ai_result, is_complete
ai_result = ""
is_complete = False
try:
with Image.open(image_path) as img:
if img.mode in ('RGBA', 'LA', 'P'):
img = img.convert('RGB')
max_size = (1024, 1024)
img.thumbnail(max_size, Image.LANCZOS)
buffered = BytesIO()
img.save(buffered, format="JPEG", quality=90)
img_data = buffered.getvalue()
img_base64 = str(base64.b64encode(img_data), 'utf-8')
question = [
{"role": "user", "content": img_base64, "content_type": "image"},
{"role": "user", "content": "请识别这个物品的名称,要求尽量覆盖可能的叫法,比如(苹果手机,手机,苹果,电话,iPhone),"
"按照逗号分隔,按出现频率排序"
"如果画面中识别出多个物品,首先排除不可能丢失的东西(比如,背景,环境,装饰等),只保留可能丢失的物品"
}
]
wsParam = Ws_Param(appid, api_key, api_secret, imageunderstanding_url)
websocket.enableTrace(False)
wsUrl = wsParam.create_url()
ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)
ws.appid = appid
ws.question = question
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
start_time = time.time()
while not is_complete and (time.time() - start_time) < 10:
time.sleep(0.1)
if ai_result:
return [tag.strip() for tag in ai_result.split(",") if tag.strip()][:5]
else:
print("大模型未返回有效结果")
return []
except Exception as e:
print(f"大模型调用失败: {str(e)}")
return []
| 2401_83827989/You-Hack | image_recognizer.py | Python | unknown | 7,264 |
# This file is part of the openHiTLS project.
#
# openHiTLS is licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
# http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
cmake_minimum_required(VERSION 3.16 FATAL_ERROR)
project(openHiTLS)
set(HiTLS_SOURCE_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR})
if(DEFINED BUILD_DIR)
set(HiTLS_BUILD_DIR ${BUILD_DIR})
else()
set(HiTLS_BUILD_DIR ${HiTLS_SOURCE_ROOT_DIR}/build)
endif()
execute_process(COMMAND python3 ${HiTLS_SOURCE_ROOT_DIR}/configure.py -m --build_dir ${HiTLS_BUILD_DIR})
include(${HiTLS_BUILD_DIR}/modules.cmake)
install(DIRECTORY ${HiTLS_SOURCE_ROOT_DIR}/include/
DESTINATION ${CMAKE_INSTALL_PREFIX}/include/hitls/
FILES_MATCHING PATTERN "*.h")
| 2302_82127028/openHiTLS-examples_5062 | CMakeLists.txt | CMake | unknown | 1,079 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_CONF_H
#define HITLS_APP_CONF_H
#include <stdint.h>
#include "bsl_obj.h"
#include "bsl_conf.h"
#include "hitls_pki_types.h"
#include "hitls_pki_utils.h"
#include "hitls_pki_csr.h"
#include "hitls_pki_cert.h"
#include "hitls_pki_crl.h"
#include "hitls_pki_x509.h"
#include "hitls_pki_pkcs12.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* x509 v3 extensions
*/
#define HITLS_CFG_X509_EXT_AKI "authorityKeyIdentifier"
#define HITLS_CFG_X509_EXT_SKI "subjectKeyIdentifier"
#define HITLS_CFG_X509_EXT_BCONS "basicConstraints"
#define HITLS_CFG_X509_EXT_KU "keyUsage"
#define HITLS_CFG_X509_EXT_EXKU "extendedKeyUsage"
#define HITLS_CFG_X509_EXT_SAN "subjectAltName"
/* Key usage */
#define HITLS_CFG_X509_EXT_KU_DIGITAL_SIGN "digitalSignature"
#define HITLS_CFG_X509_EXT_KU_NON_REPUDIATION "nonRepudiation"
#define HITLS_CFG_X509_EXT_KU_KEY_ENCIPHERMENT "keyEncipherment"
#define HITLS_CFG_X509_EXT_KU_DATA_ENCIPHERMENT "dataEncipherment"
#define HITLS_CFG_X509_EXT_KU_KEY_AGREEMENT "keyAgreement"
#define HITLS_CFG_X509_EXT_KU_KEY_CERT_SIGN "keyCertSign"
#define HITLS_CFG_X509_EXT_KU_CRL_SIGN "cRLSign"
#define HITLS_CFG_X509_EXT_KU_ENCIPHER_ONLY "encipherOnly"
#define HITLS_CFG_X509_EXT_KU_DECIPHER_ONLY "decipherOnly"
/* Extended key usage */
#define HITLS_CFG_X509_EXT_EXKU_SERVER_AUTH "serverAuth"
#define HITLS_CFG_X509_EXT_EXKU_CLIENT_AUTH "clientAuth"
#define HITLS_CFG_X509_EXT_EXKU_CODE_SING "codeSigning"
#define HITLS_CFG_X509_EXT_EXKU_EMAIL_PROT "emailProtection"
#define HITLS_CFG_X509_EXT_EXKU_TIME_STAMP "timeStamping"
#define HITLS_CFG_X509_EXT_EXKU_OCSP_SIGN "OCSPSigning"
/* Subject Alternative Name */
#define HITLS_CFG_X509_EXT_SAN_EMAIL "email"
#define HITLS_CFG_X509_EXT_SAN_DNS "DNS"
#define HITLS_CFG_X509_EXT_SAN_DIR_NAME "dirName"
#define HITLS_CFG_X509_EXT_SAN_URI "URI"
#define HITLS_CFG_X509_EXT_SAN_IP "IP"
/* Authority key identifier */
#define HITLS_CFG_X509_EXT_AKI_KID (1 << 0)
#define HITLS_CFG_X509_EXT_AKI_KID_ALWAYS (1 << 1)
typedef struct {
HITLS_X509_ExtAki aki;
uint32_t flag;
} HITLS_CFG_ExtAki;
/**
* @ingroup apps
*
* @brief Split String by character.
* Remove spaces before and after separators.
*
* @param str [IN] String to be split.
* @param separator [IN] Separator.
* @param allowEmpty [IN] Indicates whether empty substrings can be contained.
* @param strArr [OUT] String array. Only the first string needs to be released after use.
* @param maxArrCnt [IN] String array. Only the first string needs to be released after use.
* @param realCnt [OUT] Number of character strings after splitting。
*
* @retval HITLS_APP_SUCCESS
*/
int32_t HITLS_APP_SplitString(const char *str, char separator, bool allowEmpty, char **strArr, uint32_t maxArrCnt,
uint32_t *realCnt);
/**
* @ingroup apps
*
* @brief Process function of X509 extensions.
*
* @param cid [IN] Cid of extension
* @param val [IN] Data pointer.
* @param ctx [IN] Context.
*
* @retval HITLS_APP_SUCCESS
*/
typedef int32_t (*ProcExtCallBack)(BslCid cid, void *val, void *ctx);
/**
* @ingroup apps
*
* @brief Process function of X509 extensions.
*
* @param value [IN] conf
* @param section [IN] The section name of x509 extension
* @param extCb [IN] Callback function of one extension.
* @param ctx [IN] Context of callback function.
*
* @retval HITLS_APP_SUCCESS
*/
int32_t HITLS_APP_CONF_ProcExt(BSL_CONF *cnf, const char *section, ProcExtCallBack extCb, void *ctx);
/**
* @ingroup apps
*
* @brief The callback function to add distinguish name
*
* @param ctx [IN] The context of callback function
* @param nameList [IN] The linked list of subject name, the type is HITLS_X509_DN
*
* @retval HITLS_APP_SUCCESS
*/
typedef int32_t (*AddDnNameCb)(void *ctx, BslList *nameList);
/**
* @ingroup apps
*
* @brief The callback function to add subject name to csr
*
* @param ctx [IN] The context of callback function
* @param nameList [IN] The linked list of subject name, the type is HITLS_X509_DN
*
* @retval HITLS_APP_SUCCESS
*/
int32_t HiTLS_AddSubjDnNameToCsr(void *csr, BslList *nameList);
/**
* @ingroup apps
*
* @brief Process distinguish name string.
* The distinguish name format is /type0=value0/type1=value1/type2=...
*
* @param nameStr [IN] distinguish name string
* @param cb [IN] The callback function to add distinguish name to csr or cert
* @param ctx [IN] Context of callback function.
*
* @retval HITLS_APP_SUCCESS
*/
int32_t HITLS_APP_CFG_ProcDnName(const char *nameStr, AddDnNameCb cb, void *ctx);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_CONF_H
| 2302_82127028/openHiTLS-examples_5062 | apps/include/app_conf.h | C | unknown | 5,429 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_CRL_H
#define HITLS_APP_CRL_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_CrlMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_5062 | apps/include/app_crl.h | C | unknown | 734 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_DGST_H
#define HITLS_APP_DGST_H
#include <stdint.h>
#include <stddef.h>
#include "crypt_algid.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
const int mdId;
const char *mdAlgName;
} HITLS_AlgList;
int32_t HITLS_DgstMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_5062 | apps/include/app_dgst.h | C | unknown | 866 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_ENC_H
#define HITLS_APP_ENC_H
#include <stdint.h>
#include <linux/limits.h>
#ifdef __cplusplus
extern "C" {
#endif
#define REC_ITERATION_TIMES 10000
#define REC_MAX_FILE_LENGEN 512
#define REC_MAX_FILENAME_LENGTH PATH_MAX
#define REC_MAX_MAC_KEY_LEN 64
#define REC_MAX_KEY_LENGTH 64
#define REC_MAX_IV_LENGTH 16
#define REC_HEX_BASE 16
#define REC_SALT_LEN 8
#define REC_HEX_BUF_LENGTH 8
#define REC_MIN_PRE_LENGTH 6
#define REC_DOUBLE 2
#define MAX_BUFSIZE 4096
#define XTS_MIN_DATALEN 16
#define BUF_SAFE_BLOCK 16
#define BUF_READABLE_BLOCK 32
#define IS_SUPPORT_GET_EOF 1
#define BSL_SUCCESS 0
typedef enum {
HITLS_APP_OPT_CIPHER_ALG = 2,
HITLS_APP_OPT_IN_FILE,
HITLS_APP_OPT_OUT_FILE,
HITLS_APP_OPT_DEC,
HITLS_APP_OPT_ENC,
HITLS_APP_OPT_MD,
HITLS_APP_OPT_PASS,
} HITLS_OptType;
typedef struct {
const int cipherId;
const char *cipherAlgName;
} HITLS_CipherAlgList;
typedef struct {
const int macId;
const char *macAlgName;
} HITLS_MacAlgList;
int32_t HITLS_EncMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_enc.h | C | unknown | 1,853 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_ERRNO_H
#define HITLS_APP_ERRNO_H
#ifdef __cplusplus
extern "C" {
#endif
#define HITLS_APP_SUCCESS 0
// The return value of HITLS APP ranges from 0, 1, 3 to 125.
// 3 to 125 are external error codes.
enum HITLS_APP_ERROR {
HITLS_APP_HELP = 0x1, /* *< the subcommand has the help option */
HITLS_APP_SECUREC_FAIL, /* *< error returned by the safe function */
HITLS_APP_MEM_ALLOC_FAIL, /* *< failed to apply for memory resources */
HITLS_APP_INVALID_ARG, /* *< invalid parameter */
HITLS_APP_INTERNAL_EXCEPTION,
HITLS_APP_ENCODE_FAIL, /* *< encodeing failure */
HITLS_APP_CRYPTO_FAIL,
HITLS_APP_PASSWD_FAIL,
HITLS_APP_UIO_FAIL,
HITLS_APP_STDIN_FAIL, /* *< incorrect stdin input */
HITLS_APP_INFO_CMP_FAIL, /* *< failed to match the received information with the parameter */
HITLS_APP_INVALID_DN_TYPE,
HITLS_APP_INVALID_DN_VALUE,
HITLS_APP_INVALID_GENERAL_NAME_TYPE,
HITLS_APP_INVALID_GENERAL_NAME,
HITLS_APP_INVALID_IP,
HITLS_APP_ERR_CONF_GET_SECTION,
HITLS_APP_NO_EXT,
HITLS_APP_INIT_FAILED,
HITLS_APP_COPY_ARGS_FAILED,
HITLS_APP_OPT_UNKOWN, /* *< option error */
HITLS_APP_OPT_NAME_INVALID, /* *< the subcommand name is invalid */
HITLS_APP_OPT_VALUETYPE_INVALID, /* *< the parameter type of the subcommand is invalid */
HITLS_APP_OPT_TYPE_INVALID, /* *< the subcommand type is invalid */
HITLS_APP_OPT_VALUE_INVALID, /* *< the subcommand parameter value is invalid */
HITLS_APP_DECODE_FAIL, /* *< decoding failure */
HITLS_APP_CERT_VERIFY_FAIL, /* *< certificate verification failed */
HITLS_APP_X509_FAIL, /* *< x509-related error. */
HITLS_APP_SAL_FAIL, /* *< sal-related error. */
HITLS_APP_BSL_FAIL, /* *< bsl-related error. */
HITLS_APP_CONF_FAIL, /* *< conf-related error. */
HITLS_APP_LOAD_CERT_FAIL, /* *< Failed to load the cert. */
HITLS_APP_LOAD_CSR_FAIL, /* *< Failed to load the csr. */
HITLS_APP_LOAD_KEY_FAIL, /* *< Failed to load the public and private keys. */
HITLS_APP_ENCODE_KEY_FAIL, /* *< Failed to encode the public and private keys. */
HITLS_APP_MAX = 126, /* *< maximum of the error code */
};
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_errno.h | C | unknown | 3,087 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_FUNCTION_H
#define HITLS_APP_FUNCTION_H
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
FUNC_TYPE_NONE, // default
FUNC_TYPE_GENERAL, // general command
} HITLS_CmdFuncType;
typedef struct {
const char *name; // second-class command name
HITLS_CmdFuncType type; // type of command
int (*main)(int argc, char *argv[]); // second-class entry function
} HITLS_CmdFunc;
int AppGetProgFunc(const char *proName, HITLS_CmdFunc *func);
void AppPrintFuncList(void);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_function.h | C | unknown | 1,129 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_GENPKEY_H
#define HITLS_APP_GENPKEY_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_GenPkeyMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_Genpkey_H | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_genpkey.h | C | unknown | 769 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_GENRSA_H
#define HITLS_APP_GENRSA_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define REC_MAX_PEM_FILELEN 65537
#define REC_MAX_PKEY_LENGTH 16384
#define REC_MIN_PKEY_LENGTH 512
#define REC_ALG_NUM_EACHLINE 4
typedef struct {
const int id;
const char *algName;
} HITLS_APPAlgList;
int32_t HITLS_GenRSAMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_5062 | apps/include/app_genrsa.h | C | unknown | 967 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_HELP_H
#define HITLS_APP_HELP_H
#ifdef __cplusplus
extern "C" {
#endif
int HITLS_HelpMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_help.h | C | unknown | 714 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_KDF_H
#define HITLS_APP_KDF_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_KdfMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_kdf.h | C | unknown | 734 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_LIST_H
#define HITLS_APP_LIST_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
HITLS_APP_LIST_OPT_ALL_ALG = 2,
HITLS_APP_LIST_OPT_DGST_ALG,
HITLS_APP_LIST_OPT_CIPHER_ALG,
HITLS_APP_LIST_OPT_ASYM_ALG,
HITLS_APP_LIST_OPT_MAC_ALG,
HITLS_APP_LIST_OPT_RAND_ALG,
HITLS_APP_LIST_OPT_KDF_ALG,
HITLS_APP_LIST_OPT_CURVES
} HITLSListOptType;
int HITLS_ListMain(int argc, char *argv[]);
int32_t HITLS_APP_GetCidByName(const char *name, int32_t type);
const char *HITLS_APP_GetNameByCid(int32_t cid, int32_t type);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_LIST_H
| 2302_82127028/openHiTLS-examples_5062 | apps/include/app_list.h | C | unknown | 1,183 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_MAC_H
#define HITLS_APP_MAC_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_MacMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_mac.h | C | unknown | 734 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_OPT_H
#define HITLS_APP_OPT_H
#include <stdint.h>
#include "bsl_uio.h"
#include "bsl_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#define HILTS_APP_FORMAT_UNDEF 0
#define HITLS_APP_FORMAT_PEM BSL_FORMAT_PEM // 1
#define HITLS_APP_FORMAT_ASN1 BSL_FORMAT_ASN1 // 2
#define HITLS_APP_FORMAT_TEXT 3
#define HITLS_APP_FORMAT_BASE64 4
#define HITLS_APP_FORMAT_HEX 5
#define HITLS_APP_FORMAT_BINARY 6
#define HITLS_APP_PROV_ENUM \
HITLS_APP_OPT_PROVIDER, \
HITLS_APP_OPT_PROVIDER_PATH, \
HITLS_APP_OPT_PROVIDER_ATTR \
#define HITLS_APP_PROV_OPTIONS \
{"provider", HITLS_APP_OPT_PROVIDER, HITLS_APP_OPT_VALUETYPE_STRING, \
"Specify the cryptographic service provider"}, \
{"provider-path", HITLS_APP_OPT_PROVIDER_PATH, HITLS_APP_OPT_VALUETYPE_STRING, \
"Set the path to the cryptographic service provider"}, \
{"provider-attr", HITLS_APP_OPT_PROVIDER_ATTR, HITLS_APP_OPT_VALUETYPE_STRING, \
"Set additional attributes for the cryptographic service provider"} \
#define HITLS_APP_PROV_CASES(optType, provider) \
switch (optType) { \
case HITLS_APP_OPT_PROVIDER: \
(provider)->providerName = HITLS_APP_OptGetValueStr(); \
break; \
case HITLS_APP_OPT_PROVIDER_PATH: \
(provider)->providerPath = HITLS_APP_OptGetValueStr(); \
break; \
case HITLS_APP_OPT_PROVIDER_ATTR: \
(provider)->providerAttr = HITLS_APP_OptGetValueStr(); \
break; \
default: \
break; \
}
typedef enum {
HITLS_APP_OPT_VALUETYPE_NONE = 0,
HITLS_APP_OPT_VALUETYPE_NO_VALUE = 1,
HITLS_APP_OPT_VALUETYPE_IN_FILE,
HITLS_APP_OPT_VALUETYPE_OUT_FILE,
HITLS_APP_OPT_VALUETYPE_STRING,
HITLS_APP_OPT_VALUETYPE_PARAMTERS,
HITLS_APP_OPT_VALUETYPE_DIR,
HITLS_APP_OPT_VALUETYPE_INT,
HITLS_APP_OPT_VALUETYPE_UINT,
HITLS_APP_OPT_VALUETYPE_POSITIVE_INT,
HITLS_APP_OPT_VALUETYPE_LONG,
HITLS_APP_OPT_VALUETYPE_ULONG,
HITLS_APP_OPT_VALUETYPE_FMT_PEMDER,
HITLS_APP_OPT_VALUETYPE_FMT_ANY,
HITLS_APP_OPT_VALUETYPE_MAX,
} HITLS_ValueType;
typedef enum {
HITLS_APP_OPT_VALUECLASS_NONE = 0,
HITLS_APP_OPT_VALUECLASS_NO_VALUE = 1,
HITLS_APP_OPT_VALUECLASS_STR,
HITLS_APP_OPT_VALUECLASS_DIR,
HITLS_APP_OPT_VALUECLASS_INT,
HITLS_APP_OPT_VALUECLASS_LONG,
HITLS_APP_OPT_VALUECLASS_FMT,
HITLS_APP_OPT_VALUECLASS_MAX,
} HITLS_ValueClass;
typedef enum {
HITLS_APP_OPT_ERR = -1,
HITLS_APP_OPT_EOF = 0,
HITLS_APP_OPT_PARAM = HITLS_APP_OPT_EOF,
HITLS_APP_OPT_HELP = 1,
} HITLS_OptChoice;
typedef struct {
const char *name; // option name
const int optType; // option type
int valueType; // options with parameters(type)
const char *help; // description of this option
} HITLS_CmdOption;
/**
* @ingroup HITLS_APP
* @brief Initialization of command-line argument parsing (internal function)
*
* @param argc [IN] number of options
* @param argv [IN] pointer to an array of options
* @param opts [IN] command option table
*
* @retval command name of command-line argument
*/
int32_t HITLS_APP_OptBegin(int32_t argc, char **argv, const HITLS_CmdOption *opts);
/**
* @ingroup HITLS_APP
* @brief Parse next command-line argument (internal function)
*
* @param void
*
* @retval int32 option type
*/
int32_t HITLS_APP_OptNext(void);
/**
* @ingroup HITLS_APP
* @brief Finish parsing options
*
* @param void
*
* @retval void
*/
void HITLS_APP_OptEnd(void);
/**
* @ingroup HITLS_APP
* @brief Print command line parsing
*
* @param opts command option table
*
* @retval void
*/
void HITLS_APP_OptHelpPrint(const HITLS_CmdOption *opts);
/**
* @ingroup HITLS_APP
* @brief Get the number of remaining options
*
* @param void
*
* @retval int32 number of remaining options
*/
int32_t HITLS_APP_GetRestOptNum(void);
/**
* @ingroup HITLS_APP
* @brief Get the remaining options
*
* @param void
*
* @retval char** the address of remaining options
*/
char **HITLS_APP_GetRestOpt(void);
/**
* @ingroup HITLS_APP
* @brief Get command option
* @param void
* @retval char* command option
*/
char *HITLS_APP_OptGetValueStr(void);
/**
* @ingroup HITLS_APP
* @brief option string to int
* @param valueS [IN] string value
* @param valueL [OUT] int value
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetInt(const char *valueS, int32_t *valueI);
/**
* @ingroup HITLS_APP
* @brief option string to uint32_t
* @param valueS [IN] string value
* @param valueL [OUT] uint32_t value
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetUint32(const char *valueS, uint32_t *valueU);
/**
* @ingroup HITLS_APP
* @brief Get the name of the current second-class command
*
* @param void
*
* @retval char* command name
*/
char *HITLS_APP_GetProgName(void);
/**
* @ingroup HITLS_APP
* @brief option string to long
*
* @param valueS [IN] string value
* @param valueL [OUT] long value
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetLong(const char *valueS, long *valueL);
/**
* @ingroup HITLS_APP
* @brief Get the format type from the option value
*
* @param valueS [IN] string of value
* @param type [IN] value type
* @param formatType [OUT] format type
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptGetFormatType(const char *valueS, HITLS_ValueType type, BSL_ParseFormat *formatType);
/**
* @ingroup HITLS_APP
* @brief Get UIO type from option value
*
* @param filename [IN] name of input file
* @param mode [IN] method of opening a file
* @param flag [OUT] whether the closing of the standard input/output window is bound to the UIO
*
* @retval BSL_UIO * when succeeded, NULL when failed
*/
BSL_UIO* HITLS_APP_UioOpen(const char* filename, char mode, int32_t flag);
/**
* @ingroup HITLS_APP
* @brief Converts a character string to a character string in Base64 format and output the buf to UIO
*
* @param buf [IN] content to be encoded
* @param inBufLen [IN] the length of content to be encoded
* @param outBuf [IN] Encoded content
* @param outBufLen [IN] the length of encoded content
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptToBase64(uint8_t *buf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen);
/**
* @ingroup HITLS_APP
* @brief Converts a character string to a hexadecimal character string and output the buf to UIO
*
* @param buf [IN] content to be encoded
* @param inBufLen [IN] the length of content to be encoded
* @param outBuf [IN] Encoded content
* @param outBufLen [IN] the length of encoded content
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptToHex(uint8_t *buf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen);
/**
* @ingroup HITLS_APP
* @brief Output the buf to UIO
*
* @param uio [IN] output UIO
* @param buf [IN] output buf
* @param outLen [IN] the length of output buf
* @param format [IN] output format
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptWriteUio(BSL_UIO* uio, uint8_t* buf, uint32_t outLen, int32_t format);
/**
* @ingroup HITLS_APP
* @brief Read the content in the UIO to the readBuf
*
* @param uio [IN] input UIO
* @param readBuf [IN] buf which uio read
* @param readBufLen [IN] the length of readBuf
* @param maxBufLen [IN] the maximum length to be read.
*
* @retval int32_t success or not
*/
int32_t HITLS_APP_OptReadUio(BSL_UIO *uio, uint8_t **readBuf, uint64_t *readBufLen, uint64_t maxBufLen);
/**
* @ingroup HITLS_APP
* @brief Get unknown option name
*
* @retval char*
*/
const char *HITLS_APP_OptGetUnKownOptName();
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_5062 | apps/include/app_opt.h | C | unknown | 8,603 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_PASSWD_H
#define HITLS_APP_PASSWD_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define REC_MAX_ITER_TIMES 999999999
#define REC_DEF_ITER_TIMES 5000
#define REC_MAX_ARRAY_LEN 1025
#define REC_MIN_ITER_TIMES 1000
#define REC_SHA512_BLOCKSIZE 64
#define REC_HASH_BUF_LEN 64
#define REC_MIN_PREFIX_LEN 37
#define REC_MAX_SALTLEN 16
#define REC_SHA512_SALTLEN 16
#define REC_TEN 10
#define REC_PRE_ITER_LEN 8
#define REC_SEVEN 7
#define REC_SHA512_ALGTAG 6
#define REC_SHA256_ALGTAG 5
#define REC_PRE_TAG_LEN 3
#define REC_THREE 3
#define REC_TWO 2
#define REC_MD5_ALGTAG 1
int32_t HITLS_PasswdMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_5062 | apps/include/app_passwd.h | C | unknown | 1,429 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_PKCS12_H
#define HITLS_APP_PKCS12_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_PKCS12Main(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_pkcs12.h | C | unknown | 745 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_PKEY_H
#define HITLS_APP_PKEY_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_PkeyMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_PKEY_H | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_pkey.h | C | unknown | 757 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_LOG_H
#define HITLS_APP_LOG_H
#include <stdio.h>
#include <stdint.h>
#include "bsl_uio.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @ingroup HITLS_APPS
* @brief Print output to UIO
*
* @param uio [IN] UIO to be printed
* @param format [IN] Log format character string
* @param... [IN] format Parameter
* @retval int32_t
*/
int32_t AppPrint(BSL_UIO *uio, const char *format, ...);
/**
* @ingroup HiTLS_APPS
* @brief Print the output to stderr.
*
* @param format [IN] Log format character string
* @param... [IN] format Parameter
* @retval void
*/
void AppPrintError(const char *format, ...);
/**
* @ingroup HiTLS_APPS
* @brief Initialize the PrintErrUIO.
*
* @param fp [IN] File pointer, for example, stderr.
* @retval int32_t
*/
int32_t AppPrintErrorUioInit(FILE *fp);
/**
* @ingroup HiTLS_APPS
* @brief Deinitialize the PrintErrUIO.
*
* @retval void
*/
void AppPrintErrorUioUnInit(void);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_print.h | C | unknown | 1,527 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_PROVIDER_H
#define HITLS_APP_PROVIDER_H
#include <stdint.h>
#include "crypt_types.h"
#include "crypt_eal_provider.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
char *providerName;
char *providerPath;
char *providerAttr;
} AppProvider;
CRYPT_EAL_LibCtx *APP_Create_LibCtx(void);
CRYPT_EAL_LibCtx *APP_GetCurrent_LibCtx(void);
int32_t HITLS_APP_LoadProvider(const char *searchPath, const char *providerName);
#define HITLS_APP_FreeLibCtx CRYPT_EAL_LibCtxFree
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_provider.h | C | unknown | 1,083 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_RAND_H
#define HITLS_APP_RAND_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_RandMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_rand.h | C | unknown | 737 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_REQ_H
#define HITLS_APP_REQ_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_ReqMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_REQ_H | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_req.h | C | unknown | 753 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_RSA_H
#define HITLS_APP_RSA_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_RsaMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_rsa.h | C | unknown | 734 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef APP_UTILS_H
#define APP_UTILS_H
#include <stddef.h>
#include <stdint.h>
#include "bsl_ui.h"
#include "bsl_types.h"
#include "crypt_eal_pkey.h"
#include "app_conf.h"
#include "hitls_csr_local.h"
#ifdef __cplusplus
extern "C" {
#endif
#define APP_MAX_PASS_LENGTH 1024
#define APP_MIN_PASS_LENGTH 1
#define APP_FILE_MAX_SIZE_KB 256
#define APP_FILE_MAX_SIZE (APP_FILE_MAX_SIZE_KB * 1024) // 256KB
#define DEFAULT_SALTLEN 16
#define DEFAULT_ITCNT 2048
void *ExpandingMem(void *oldPtr, size_t newSize, size_t oldSize);
/**
* @ingroup apps
*
* @brief Apps Function for Checking the Validity of Key Characters
*
* @attention If the key length needs to be limited, the caller needs to limit the key length outside the function.
*
* @param password [IN] Key entered by the user
* @param passwordLen [IN] Length of the key entered by the user
*
* @retval The key is valid:HITLS_APP_SUCCESS
* @retval The key is invalid:HITLS_APP_PASSWD_FAIL
*/
int32_t HITLS_APP_CheckPasswd(const uint8_t *password, const uint32_t passwordLen);
/**
* @ingroup apps
*
* @brief Apps Function for Verifying Passwd Received by the BSL_UI_ReadPwdUtil()
*
* @attention callBackData is the default callback structure APP_DefaultPassCBData.
*
* @param ui [IN] Input/Output Stream
* @param buff [IN] Buffer for receiving passwd
* @param buffLen [IN] Length of the buffer for receiving passwd
* @param callBackData [IN] Key verification information.
*
* @retval The key is valid:HITLS_APP_SUCCESS
* @retval The key is invalid:HITLS_APP_PASSWD_FAIL
*/
int32_t HITLS_APP_DefaultPassCB(BSL_UI *ui, char *buff, uint32_t buffLen, void *callBackData);
int32_t HITLS_APP_Passwd(char *buf, int32_t bufMaxLen, int32_t flag, void *userdata);
void HITLS_APP_PrintPassErrlog(void);
/**
* @ingroup apps
*
* @brief Obtain the password from the command line argument.
*
* @attention pass: The memory needs to be released automatically.
*
* @param passArg [IN] Command line password parameters
* @param pass [OUT] Parsed password
*
* @retval The key is valid:HITLS_APP_SUCCESS
* @retval The key is invalid:HITLS_APP_PASSWD_FAIL
*/
int32_t HITLS_APP_ParsePasswd(const char *passArg, char **pass);
int32_t HITLS_APP_GetPasswd(BSL_UI_ReadPwdParam *param, char **passin, uint8_t **pass, uint32_t *passLen);
/**
* @ingroup apps
*
* @brief Load the public key.
*
* @attention If inFilePath is empty, it is read from the standard input.
*
* @param inFilePath [IN] file name
* @param informat [IN] Public Key Format
*
* @retval CRYPT_EAL_PkeyCtx
*/
CRYPT_EAL_PkeyCtx *HITLS_APP_LoadPubKey(const char *inFilePath, BSL_ParseFormat informat);
/**
* @ingroup apps
*
* @brief Load the private key.
*
* @attention If inFilePath or passin is empty, it is read from the standard input.
*
* @param inFilePath [IN] file name
* @param informat [IN] Private Key Format
* @param passin [IN/OUT] Parsed password
*
* @retval CRYPT_EAL_PkeyCtx
*/
CRYPT_EAL_PkeyCtx *HITLS_APP_LoadPrvKey(const char *inFilePath, BSL_ParseFormat informat, char **passin);
/**
* @ingroup apps
*
* @brief Print the public key.
*
* @attention If outFilePath is empty, the standard output is displayed.
*
* @param pkey [IN] key
* @param outFilePath [IN] file name
* @param outformat [IN] Public Key Format
*
* @retval HITLS_APP_SUCCESS
* @retval HITLS_APP_INVALID_ARG
* @retval HITLS_APP_ENCODE_KEY_FAIL
* @retval HITLS_APP_UIO_FAIL
*/
int32_t HITLS_APP_PrintPubKey(CRYPT_EAL_PkeyCtx *pkey, const char *outFilePath, BSL_ParseFormat outformat);
/**
* @ingroup apps
*
* @brief Print the private key.
*
* @attention If outFilePath is empty, the standard output is displayed, If passout is empty, it is read
* from the standard input.
*
* @param pkey [IN] key
* @param outFilePath [IN] file name
* @param outformat [IN] Private Key Format
* @param cipherAlgCid [IN] Encryption algorithm cid
* @param passout [IN/OUT] encryption password
*
* @retval HITLS_APP_SUCCESS
* @retval HITLS_APP_INVALID_ARG
* @retval HITLS_APP_ENCODE_KEY_FAIL
* @retval HITLS_APP_UIO_FAIL
*/
int32_t HITLS_APP_PrintPrvKey(CRYPT_EAL_PkeyCtx *pkey, const char *outFilePath, BSL_ParseFormat outformat,
int32_t cipherAlgCid, char **passout);
typedef struct {
const char *name;
BSL_ParseFormat outformat;
int32_t cipherAlgCid;
bool text;
bool noout;
} AppKeyPrintParam;
int32_t HITLS_APP_PrintPrvKeyByUio(BSL_UIO *uio, CRYPT_EAL_PkeyCtx *pkey, AppKeyPrintParam *printKeyParam,
char **passout);
/**
* @ingroup apps
*
* @brief Obtain and check the encryption algorithm.
*
* @param name [IN] encryption name
* @param symId [IN/OUT] encryption algorithm cid
*
* @retval HITLS_APP_SUCCESS
* @retval HITLS_APP_INVALID_ARG
*/
int32_t HITLS_APP_GetAndCheckCipherOpt(const char *name, int32_t *symId);
/**
* @ingroup apps
*
* @brief Load the cert.
*
* @param inPath [IN] cert path
* @param inform [IN] cert format
*
* @retval HITLS_X509_Cert
*/
HITLS_X509_Cert *HITLS_APP_LoadCert(const char *inPath, BSL_ParseFormat inform);
/**
* @ingroup apps
*
* @brief Load the csr.
*
* @param inPath [IN] csr path
* @param inform [IN] csr format
*
* @retval HITLS_X509_Csr
*/
HITLS_X509_Csr *HITLS_APP_LoadCsr(const char *inPath, BSL_ParseFormat inform);
int32_t HITLS_APP_GetAndCheckHashOpt(const char *name, int32_t *hashId);
int32_t HITLS_APP_PrintText(const BSL_Buffer *csrBuf, const char *outFileName);
int32_t HITLS_APP_HexToByte(const char *hex, uint8_t **bin, uint32_t *len);
CRYPT_EAL_PkeyCtx *HITLS_APP_GenRsaPkeyCtx(uint32_t bits);
#ifdef __cplusplus
}
#endif
#endif // APP_UTILS_H | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_utils.h | C | unknown | 6,401 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_VERIFY_H
#define HITLS_APP_VERIFY_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_VerifyMain(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif
| 2302_82127028/openHiTLS-examples_5062 | apps/include/app_verify.h | C | unknown | 744 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef HITLS_APP_X509_H
#define HITLS_APP_X509_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
int32_t HITLS_X509Main(int argc, char *argv[]);
#ifdef __cplusplus
}
#endif
#endif // HITLS_APP_X509_H | 2302_82127028/openHiTLS-examples_5062 | apps/include/app_x509.h | C | unknown | 757 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_conf.h"
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#if defined(__linux__) || defined(__unix__)
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#else
#error "only support linux"
#endif
#include "securec.h"
#include "app_errno.h"
#include "bsl_sal.h"
#include "bsl_types.h"
#include "bsl_obj.h"
#include "bsl_obj_internal.h"
#include "bsl_list.h"
#include "hitls_pki_errno.h"
#include "hitls_x509_local.h"
#include "app_errno.h"
#include "app_opt.h"
#include "app_print.h"
#include "app_conf.h"
#define MAX_DN_LIST_SIZE 99
#define X509_EXT_SAN_VALUE_MAX_CNT 30 // san
#define IPV4_VALUE_MAX_CNT 4
#define IPV6_VALUE_STR_MAX_CNT 8
#define IPV6_VALUE_MAX_CNT 16
#define IPV6_EACH_VALUE_STR_LEN 4
#define EXT_STR_CRITICAL "critical"
typedef int32_t (*ProcExtCnfFunc)(BSL_CONF *cnf, bool critical, const char *cnfValue, ProcExtCallBack procExt,
void *ctx);
typedef struct {
char *name;
ProcExtCnfFunc func;
} X509ExtInfo;
typedef struct {
char *name;
int32_t keyUsage;
} X509KeyUsageMap;
#define X509_EXT_BCONS_VALUE_MAX_CNT 2 // ca and pathlen
#define X509_EXT_BCONS_SUB_VALUE_MAX_CNT 2 // ca:TRUE|FALSE or pathlen:num
#define X509_EXT_KU_VALUE_MAX_CNT 9 // 9 key usages
#define X509_EXT_EXKU_VALUE_MAX_CNT 6 // 6 extended key usages
#define X509_EXT_SKI_VALUE_MAX_CNT 1 // kid
#define X509_EXT_AKI_VALUE_MAX_CNT 1 // kid
#define X509_EXT_AKI_SUB_VALUE_MAX_CNT 2 // keyid:always
static X509KeyUsageMap g_kuMap[X509_EXT_KU_VALUE_MAX_CNT] = {
{HITLS_CFG_X509_EXT_KU_DIGITAL_SIGN, HITLS_X509_EXT_KU_DIGITAL_SIGN},
{HITLS_CFG_X509_EXT_KU_NON_REPUDIATION, HITLS_X509_EXT_KU_NON_REPUDIATION},
{HITLS_CFG_X509_EXT_KU_KEY_ENCIPHERMENT, HITLS_X509_EXT_KU_KEY_ENCIPHERMENT},
{HITLS_CFG_X509_EXT_KU_DATA_ENCIPHERMENT, HITLS_X509_EXT_KU_DATA_ENCIPHERMENT},
{HITLS_CFG_X509_EXT_KU_KEY_AGREEMENT, HITLS_X509_EXT_KU_KEY_AGREEMENT},
{HITLS_CFG_X509_EXT_KU_KEY_CERT_SIGN, HITLS_X509_EXT_KU_KEY_CERT_SIGN},
{HITLS_CFG_X509_EXT_KU_CRL_SIGN, HITLS_X509_EXT_KU_CRL_SIGN},
{HITLS_CFG_X509_EXT_KU_ENCIPHER_ONLY, HITLS_X509_EXT_KU_ENCIPHER_ONLY},
{HITLS_CFG_X509_EXT_KU_DECIPHER_ONLY, HITLS_X509_EXT_KU_DECIPHER_ONLY},
};
static X509KeyUsageMap g_exKuMap[X509_EXT_EXKU_VALUE_MAX_CNT] = {
{HITLS_CFG_X509_EXT_EXKU_SERVER_AUTH, BSL_CID_KP_SERVERAUTH},
{HITLS_CFG_X509_EXT_EXKU_CLIENT_AUTH, BSL_CID_KP_CLIENTAUTH},
{HITLS_CFG_X509_EXT_EXKU_CODE_SING, BSL_CID_KP_CODESIGNING},
{HITLS_CFG_X509_EXT_EXKU_EMAIL_PROT, BSL_CID_KP_EMAILPROTECTION},
{HITLS_CFG_X509_EXT_EXKU_TIME_STAMP, BSL_CID_KP_TIMESTAMPING},
{HITLS_CFG_X509_EXT_EXKU_OCSP_SIGN, BSL_CID_KP_OCSPSIGNING},
};
static bool isSpace(char c)
{
return c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r' || c == ' ';
}
static void SkipSpace(char **value)
{
char *tmp = *value;
char *end = *value + strlen(*value);
while (isSpace(*tmp) && tmp != end) {
tmp++;
}
*value = tmp;
}
static int32_t FindEndIdx(char *str, char separator, int32_t beginIdx, int32_t currIdx, bool allowEmpty)
{
while (currIdx >= 0 && (isSpace(str[currIdx]) || str[currIdx] == separator)) {
currIdx--;
}
if (beginIdx < currIdx) {
return currIdx + 1;
} else if (str[beginIdx] != separator) {
return beginIdx + 1;
} else if (allowEmpty) {
return beginIdx; // Empty substring
} else { // Empty substrings are not allowed.
return -1;
}
}
int32_t HITLS_APP_SplitString(const char *str, char separator, bool allowEmpty, char **strArr, uint32_t maxArrCnt,
uint32_t *realCnt)
{
if (str == NULL || strlen(str) == 0 || isSpace(separator) || strArr == NULL || maxArrCnt == 0 || realCnt == NULL) {
return HITLS_APP_INVALID_ARG;
}
// Delete leading spaces from input str.
char *tmp = (char *)(uintptr_t)str;
SkipSpace(&tmp);
// split
int32_t ret = HITLS_APP_SUCCESS;
char *res = strdup(tmp);
if (res == NULL) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
int32_t len = strlen(tmp);
int32_t begin;
int32_t end;
bool hasBegin = false;
*realCnt = 0;
for (int32_t i = 0; i < len; i++) {
if (!hasBegin) {
if (isSpace(res[i])) {
continue;
}
if (*realCnt == maxArrCnt) {
ret = HITLS_APP_CONF_FAIL;
break;
}
begin = i;
strArr[(*realCnt)++] = res + begin;
hasBegin = true;
}
if ((i + 1) != len && res[i] != separator) {
continue;
}
end = FindEndIdx(res, separator, begin, i, allowEmpty);
if (end == -1) {
ret = HITLS_APP_CONF_FAIL;
break;
}
res[end] = '\0';
hasBegin = false;
}
if (ret != HITLS_APP_SUCCESS) {
*realCnt = 0;
BSL_SAL_FREE(strArr[0]);
}
return ret;
}
static bool ExtGetCritical(char **value)
{
SkipSpace(value);
uint32_t criticalLen = strlen(EXT_STR_CRITICAL);
if (strlen(*value) < criticalLen || strncmp(*value, EXT_STR_CRITICAL, criticalLen != 0)) {
return false;
}
*value += criticalLen;
SkipSpace(value);
if (**value == ',') {
(*value)++;
}
return true;
}
static int32_t ParseBasicConstraints(char **value, HITLS_X509_ExtBCons *bCons)
{
if (strcmp(value[0], "CA") == 0) {
if (strcmp(value[1], "FALSE") == 0) {
bCons->isCa = false;
} else if (strcmp(value[1], "TRUE") == 0) {
bCons->isCa = true;
} else {
AppPrintError("Illegal value of basicConstraints CA: %s.\n", value[1]);
return HITLS_APP_CONF_FAIL;
}
return HITLS_APP_SUCCESS;
} else if (strcmp(value[0], "pathlen") != 0) {
AppPrintError("Unrecognized value of basicConstraints: %s.\n", value[0]);
return HITLS_APP_CONF_FAIL;
}
int32_t pathLen;
int32_t ret = HITLS_APP_OptGetInt(value[1], &pathLen);
if (ret != HITLS_APP_SUCCESS || pathLen < 0) {
AppPrintError("Illegal value of basicConstraints pathLen(>=0): %s.\n", value[1]);
return HITLS_APP_CONF_FAIL;
}
bCons->maxPathLen = pathLen;
return HITLS_APP_SUCCESS;
}
static int32_t ProcBasicConstraints(BSL_CONF *cnf, bool critical, const char *cnfValue,
ProcExtCallBack procExt, void *ctx)
{
(void)cnf;
HITLS_X509_ExtBCons bCons = {critical, false, -1};
char *valueList[X509_EXT_BCONS_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_BCONS_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split basicConstraints failed: %s.\n", cnfValue);
return ret;
}
for (uint32_t i = 0; i < valueCnt; i++) {
char *subList[X509_EXT_BCONS_VALUE_MAX_CNT] = {0};
uint32_t subCnt = 0;
ret = HITLS_APP_SplitString(valueList[i], ':', false, subList, X509_EXT_BCONS_VALUE_MAX_CNT, &subCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split sub-value of basicConstraints failed: %s.\n", valueList[i]);
BSL_SAL_Free(valueList[0]);
return ret;
}
if (subCnt != X509_EXT_BCONS_SUB_VALUE_MAX_CNT) {
AppPrintError("Illegal value of basicConstraints: %s.\n", valueList[i]);
BSL_SAL_Free(valueList[0]);
BSL_SAL_Free(subList[0]);
return HITLS_APP_CONF_FAIL;
}
ret = ParseBasicConstraints(subList, &bCons);
BSL_SAL_Free(subList[0]);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_Free(valueList[0]);
return ret;
}
}
BSL_SAL_Free(valueList[0]);
return procExt(BSL_CID_CE_BASICCONSTRAINTS, &bCons, ctx);
}
static int32_t ProcKeyUsage(BSL_CONF *cnf, bool critical, const char *cnfValue, ProcExtCallBack procExt, void *ctx)
{
(void)cnf;
HITLS_X509_ExtKeyUsage ku = {critical, 0};
char *valueList[X509_EXT_KU_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_KU_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split value of keyUsage falied: %s.\n", cnfValue);
return ret;
}
bool found;
for (uint32_t i = 0; i < valueCnt; i++) {
found = false;
for (uint32_t j = 0; j < X509_EXT_KU_VALUE_MAX_CNT; j++) {
if (strcmp(g_kuMap[j].name, valueList[i]) == 0) {
ku.keyUsage |= g_kuMap[j].keyUsage;
found = true;
break;
}
}
if (!found) {
AppPrintError("Unrecognized value of keyUsage: %s.\n", valueList[i]);
BSL_SAL_Free(valueList[0]);
return HITLS_APP_CONF_FAIL;
}
}
BSL_SAL_Free(valueList[0]);
return procExt(BSL_CID_CE_KEYUSAGE, &ku, ctx);
}
static int32_t CmpExKeyUsageByOid(const void *pCurr, const void *pOid)
{
const BSL_Buffer *curr = pCurr;
const BslOidString *oid = pOid;
if (curr->dataLen != oid->octetLen) {
return 1;
}
return memcmp(curr->data, oid->octs, curr->dataLen);
}
static int32_t AddExtendKeyUsage(BslOidString *oidStr, BslList *list)
{
BSL_Buffer *oid = BSL_SAL_Malloc(list->dataSize);
if (oid == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
oid->data = (uint8_t *)oidStr->octs;
oid->dataLen = oidStr->octetLen;
if (BSL_LIST_AddElement(list, oid, BSL_LIST_POS_END) != 0) {
BSL_SAL_Free(oid);
return HITLS_APP_SAL_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t ProcExtendedKeyUsage(BSL_CONF *cnf, bool critical, const char *cnfValue, ProcExtCallBack procExt,
void *ctx)
{
(void)cnf;
HITLS_X509_ExtExKeyUsage exku = {critical, NULL};
char *valueList[X509_EXT_EXKU_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_EXKU_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split value of extendedKeyUsage failed: %s.\n", cnfValue);
return ret;
}
exku.oidList = BSL_LIST_New(sizeof(BSL_Buffer));
if (exku.oidList == NULL) {
BSL_SAL_Free(valueList[0]);
AppPrintError("New list of extendedKeyUsage failed.\n");
return HITLS_APP_SAL_FAIL;
}
int32_t cid;
BslOidString *oidStr = NULL;
for (uint32_t i = 0; i < valueCnt; i++) {
cid = BSL_CID_UNKNOWN;
for (uint32_t j = 0; j < X509_EXT_EXKU_VALUE_MAX_CNT; j++) {
if (strcmp(g_exKuMap[j].name, valueList[i]) == 0) {
cid = g_exKuMap[j].keyUsage;
break;
}
}
oidStr = BSL_OBJ_GetOID(cid);
if (oidStr == NULL) {
AppPrintError("Unsupported extendedKeyUsage: %s.\n", valueList[i]);
ret = HITLS_APP_CONF_FAIL;
goto EXIT;
}
if (BSL_LIST_Search(exku.oidList, oidStr, (BSL_LIST_PFUNC_CMP)CmpExKeyUsageByOid, NULL) != NULL) {
continue;
}
ret = AddExtendKeyUsage(oidStr, exku.oidList);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Add extendedKeyUsage failed.\n");
goto EXIT;
}
}
ret = procExt(BSL_CID_CE_EXTKEYUSAGE, &exku, ctx);
EXIT:
BSL_SAL_Free(valueList[0]);
BSL_LIST_FREE(exku.oidList, NULL);
return ret;
}
static int32_t ProcSubjectKeyIdentifier(BSL_CONF *cnf, bool critical, const char *cnfValue, ProcExtCallBack procExt,
void *ctx)
{
(void)cnf;
HITLS_X509_ExtSki ski = {critical, {0}};
char *valueList[X509_EXT_SKI_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_SKI_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split value of subjectKeyIdentifier failed: %s.\n", cnfValue);
return ret;
}
if (strcmp(valueList[0], "hash") != 0) {
BSL_SAL_Free(valueList[0]);
AppPrintError("Illegal value of subjectKeyIdentifier: %s, only \"hash\" current is supported.\n", cnfValue);
return HITLS_APP_CONF_FAIL;
}
BSL_SAL_Free(valueList[0]);
return procExt(BSL_CID_CE_SUBJECTKEYIDENTIFIER, &ski, ctx);
}
static int32_t ParseAuthKeyIdentifier(char **value, uint32_t cnt, uint32_t *flag)
{
if (strcmp(value[0], "keyid") != 0) {
AppPrintError("Illegal type of authorityKeyIdentifier keyid: %s.\n", value[0]);
return HITLS_APP_CONF_FAIL;
}
if (cnt == 1) {
*flag |= HITLS_CFG_X509_EXT_AKI_KID;
return HITLS_APP_SUCCESS;
}
if (strcmp(value[1], "always") != 0) {
AppPrintError("Illegal value of authorityKeyIdentifier keyid: %s.\n", value[1]);
return HITLS_APP_CONF_FAIL;
}
*flag |= HITLS_CFG_X509_EXT_AKI_KID_ALWAYS;
return HITLS_APP_SUCCESS;
}
static int32_t ProcAuthKeyIdentifier(BSL_CONF *cnf, bool critical, const char *cnfValue, ProcExtCallBack procExt,
void *ctx)
{
(void)cnf;
HITLS_CFG_ExtAki aki = {{critical, {0}, NULL, {0}}, 0};
char *valueList[X509_EXT_AKI_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_AKI_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split value of authorityKeyIdentifier failed: %s.\n", cnfValue);
return ret;
}
for (uint32_t i = 0; i < valueCnt; i++) {
char *subList[X509_EXT_AKI_SUB_VALUE_MAX_CNT] = {0};
uint32_t subCnt = 0;
ret = HITLS_APP_SplitString(valueList[i], ':', false, subList, X509_EXT_AKI_SUB_VALUE_MAX_CNT, &subCnt);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Split sub-value of authorityKeyIdentifier failed: %s.\n", valueList[i]);
BSL_SAL_Free(valueList[0]);
return ret;
}
ret = ParseAuthKeyIdentifier(subList, subCnt, &aki.flag);
BSL_SAL_Free(subList[0]);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_Free(valueList[0]);
return ret;
}
}
BSL_SAL_Free(valueList[0]);
return procExt(BSL_CID_CE_AUTHORITYKEYIDENTIFIER, &aki, ctx);
}
typedef struct {
char *name;
HITLS_X509_GeneralNameType genNameType;
} X509GeneralNameMap;
static X509GeneralNameMap g_exSanMap[] = {
{HITLS_CFG_X509_EXT_SAN_EMAIL, HITLS_X509_GN_EMAIL},
{HITLS_CFG_X509_EXT_SAN_DNS, HITLS_X509_GN_DNS},
{HITLS_CFG_X509_EXT_SAN_DIR_NAME, HITLS_X509_GN_DNNAME},
{HITLS_CFG_X509_EXT_SAN_URI, HITLS_X509_GN_URI},
{HITLS_CFG_X509_EXT_SAN_IP, HITLS_X509_GN_IP},
};
static int32_t ParseGeneralSanValue(char *value, HITLS_X509_GeneralName *generalName)
{
generalName->value.data = (uint8_t *)strdup(value);
if (generalName->value.data == NULL) {
AppPrintError("Failed to copy value: %s.\n", value);
return HITLS_APP_MEM_ALLOC_FAIL;
}
generalName->value.dataLen = strlen(value);
return HITLS_APP_SUCCESS;
}
static int32_t ParseDirNamenValue(BSL_CONF *conf, char *value, HITLS_X509_GeneralName *generalName)
{
int32_t ret;
BslList *dirName = BSL_CONF_GetSection(conf, value);
if (dirName == NULL) {
AppPrintError("Failed to get section: %s.\n", value);
return HITLS_APP_ERR_CONF_GET_SECTION;
}
BslList *nameList = BSL_LIST_New(sizeof(HITLS_X509_NameNode *));
if (nameList == NULL) {
AppPrintError("New list of directory name list failed.\n");
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
BSL_CONF_KeyValue *node = BSL_LIST_GET_FIRST(dirName);
while (node != NULL) {
HITLS_X509_DN *dnName = BSL_SAL_Calloc(1, sizeof(HITLS_X509_DN));
if (dnName == NULL) {
AppPrintError("Failed to malloc X509 DN when parsing directory name.\n");
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
const BslAsn1DnInfo *info = BSL_OBJ_GetDnInfoFromShortName(node->key);
if (info == NULL) {
ret = HITLS_APP_INVALID_DN_TYPE;
BSL_SAL_FREE(dnName);
AppPrintError("Invalid short name of distinguish name.\n");
goto EXIT;
}
dnName->data = (uint8_t *)node->value;
dnName->dataLen = (uint32_t)strlen(node->value);
dnName->cid = info->cid;
ret = HITLS_X509_AddDnName(nameList, dnName, 1);
BSL_SAL_FREE(dnName);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("Failed to HITLS_X509_AddDnName.\n");
goto EXIT;
}
node = BSL_LIST_GET_NEXT(dirName);
}
generalName->value.data = (uint8_t *)nameList;
generalName->value.dataLen = (uint32_t)sizeof(BslList *);
return HITLS_APP_SUCCESS;
EXIT:
BSL_LIST_FREE(nameList, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeNameNode);
return ret;
}
static int32_t ParseIPValue(char *value, HITLS_X509_GeneralName *generalName)
{
struct sockaddr_in sockIpv4 = {};
struct sockaddr_in6 sockIpv6 = {};
char *ipv4ValueList[IPV4_VALUE_MAX_CNT] = {0};
uint32_t ipSize = 0;
if (inet_pton(AF_INET, value, &(sockIpv4.sin_addr)) == 1) {
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(value, '.', false, ipv4ValueList, IPV4_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (valueCnt != IPV4_VALUE_MAX_CNT) {
AppPrintError("Failed to split IP string, IP: %s.\n", value);
BSL_SAL_FREE(ipv4ValueList[0]);
return HITLS_APP_INVALID_IP;
}
ipSize = IPV4_VALUE_MAX_CNT;
} else if (inet_pton(AF_INET6, value, &(sockIpv6.sin6_addr)) == 1) {
ipSize = IPV6_VALUE_MAX_CNT;
} else {
AppPrintError("Invalid IP format for directory name, IP: %s.\n", value);
return HITLS_APP_INVALID_IP;
}
generalName->value.data = BSL_SAL_Calloc(ipSize, sizeof(uint8_t));
if (generalName->value.data == NULL) {
AppPrintError("Invalid IP format for directory name, IP: %s.\n", value);
BSL_SAL_FREE(ipv4ValueList[0]);
return HITLS_APP_MEM_ALLOC_FAIL;
}
for (uint32_t i = 0; i < ipSize; i++) {
if (ipSize == IPV4_VALUE_MAX_CNT) {
generalName->value.data[i] = (uint8_t)BSL_SAL_Atoi(ipv4ValueList[i]);
} else {
generalName->value.data[i] = sockIpv6.sin6_addr.s6_addr[i];
}
}
generalName->value.dataLen = ipSize;
BSL_SAL_FREE(ipv4ValueList[0]);
return HITLS_APP_SUCCESS;
}
static int32_t ParseGeneralNameValue(BSL_CONF *conf, HITLS_X509_GeneralNameType type, char *value,
HITLS_X509_GeneralName *generalName)
{
int32_t ret;
generalName->type = type;
switch (type) {
case HITLS_X509_GN_EMAIL:
case HITLS_X509_GN_DNS:
case HITLS_X509_GN_URI:
ret = ParseGeneralSanValue(value, generalName);
break;
case HITLS_X509_GN_DNNAME:
ret = ParseDirNamenValue(conf, value, generalName);
break;
case HITLS_X509_GN_IP:
ret = ParseIPValue(value, generalName);
break;
default:
generalName->type = 0;
AppPrintError("Unsupported the type of general name, type: %u.\n", generalName->type);
return HITLS_APP_INVALID_GENERAL_NAME_TYPE;
}
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return ret;
}
static int32_t ParseGeneralName(BSL_CONF *conf, char *genNameStr, HITLS_X509_GeneralName *generalName)
{
char *key = genNameStr;
char *value = strstr(genNameStr, ":");
if (value == NULL) {
return HITLS_APP_INVALID_GENERAL_NAME_TYPE;
}
key[value - key] = '\0';
for (int i = strlen(key) - 1; i >= 0; i--) {
if (key[i] == ' ') {
key[i] = '\0';
}
}
value++;
while (*value == ' ') {
value++;
}
if (strlen(value) == 0) {
AppPrintError("The value of general name is not set, key: %s.\n", key);
return HITLS_APP_INVALID_GENERAL_NAME;
}
HITLS_X509_GeneralNameType type = HITLS_X509_GN_MAX;
for (uint32_t j = 0; j < sizeof(g_exSanMap) / sizeof(g_exSanMap[0]); j++) {
if (strcmp(g_exSanMap[j].name, key) == 0) {
type = g_exSanMap[j].genNameType;
break;
}
}
return ParseGeneralNameValue(conf, type, value, generalName);
}
static int32_t ProcExtSubjectAltName(BSL_CONF *conf, bool critical, const char *cnfValue, ProcExtCallBack procExt,
void *ctx)
{
HITLS_X509_ExtSan san = {critical, NULL};
char *valueList[X509_EXT_SAN_VALUE_MAX_CNT] = {0};
uint32_t valueCnt = 0;
int32_t ret = HITLS_APP_SplitString(cnfValue, ',', false, valueList, X509_EXT_SAN_VALUE_MAX_CNT, &valueCnt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
san.names = BSL_LIST_New(sizeof(HITLS_X509_GeneralName *));
if (san.names == NULL) {
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
// find type
for (uint32_t i = 0; i < valueCnt; i++) {
HITLS_X509_GeneralName *generalName = BSL_SAL_Calloc(1, sizeof(HITLS_X509_GeneralName));
if (generalName == NULL) {
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
ret = ParseGeneralName(conf, valueList[i], generalName);
if (ret != HITLS_APP_SUCCESS) {
HITLS_X509_FreeGeneralName(generalName);
goto EXIT;
}
ret = BSL_LIST_AddElement(san.names, generalName, BSL_LIST_POS_END);
if (ret != HITLS_APP_SUCCESS) {
HITLS_X509_FreeGeneralName(generalName);
goto EXIT;
}
}
ret = procExt(BSL_CID_CE_SUBJECTALTNAME, &san, ctx);
if (ret != HITLS_APP_SUCCESS) {
goto EXIT;
}
EXIT:
BSL_SAL_FREE(valueList[0]);
BSL_LIST_FREE(san.names, (BSL_LIST_PFUNC_FREE)HITLS_X509_FreeGeneralName);
return ret;
}
static X509ExtInfo g_exts[] = {
{HITLS_CFG_X509_EXT_AKI, (ProcExtCnfFunc)ProcAuthKeyIdentifier},
{HITLS_CFG_X509_EXT_SKI, (ProcExtCnfFunc)ProcSubjectKeyIdentifier},
{HITLS_CFG_X509_EXT_BCONS, (ProcExtCnfFunc)ProcBasicConstraints},
{HITLS_CFG_X509_EXT_KU, (ProcExtCnfFunc)ProcKeyUsage},
{HITLS_CFG_X509_EXT_EXKU, (ProcExtCnfFunc)ProcExtendedKeyUsage},
{HITLS_CFG_X509_EXT_SAN, (ProcExtCnfFunc)ProcExtSubjectAltName},
};
static int32_t AppConfProcExtEntry(BSL_CONF *cnf, BSL_CONF_KeyValue *cnfValue, ProcExtCallBack extCb, void *ctx)
{
if (cnfValue->key == NULL || cnfValue->value == NULL) {
return HITLS_APP_CONF_FAIL;
}
char *value = cnfValue->value;
bool critical = ExtGetCritical(&value);
for (uint32_t i = 0; i < sizeof(g_exts) / sizeof(g_exts[0]); i++) {
if (strcmp(cnfValue->key, g_exts[i].name) == 0) {
return g_exts[i].func(cnf, critical, value, extCb, ctx);
}
}
AppPrintError("Unsupported extension: %s.\n", cnfValue->key);
return HITLS_APP_CONF_FAIL;
}
int32_t HITLS_APP_CONF_ProcExt(BSL_CONF *cnf, const char *section, ProcExtCallBack extCb, void *ctx)
{
if (cnf == NULL || cnf->data == NULL || section == NULL || extCb == NULL) {
AppPrintError("Invalid input parameter.\n");
return HITLS_APP_CONF_FAIL;
}
int32_t ret = HITLS_APP_SUCCESS;
BslList *list = BSL_CONF_GetSection(cnf, section);
if (list == NULL) {
AppPrintError("Failed to get extension section: %s.\n", section);
return HITLS_APP_CONF_FAIL;
}
if (BSL_LIST_EMPTY(list)) {
return HITLS_APP_NO_EXT; // There is no configuration in the section.
}
BSL_CONF_KeyValue *cnfNode = BSL_LIST_GET_FIRST(list);
while (cnfNode != NULL) {
ret = AppConfProcExtEntry(cnf, cnfNode, extCb, ctx);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to process each x509 extension conf.\n");
return ret;
}
cnfNode = BSL_LIST_GET_NEXT(list);
}
return ret;
}
int32_t HiTLS_AddSubjDnNameToCsr(void *csr, BslList *nameList)
{
if (csr == NULL) {
AppPrintError("csr is null when add subject name to csr.\n");
return HITLS_APP_INVALID_ARG;
}
uint32_t count = BSL_LIST_COUNT(nameList);
HITLS_X509_DN *names = BSL_SAL_Calloc(count, sizeof(HITLS_X509_DN));
if (names == NULL) {
AppPrintError("Failed to malloc names when add subject name to csr.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
size_t index = 0;
HITLS_X509_DN *node = BSL_LIST_GET_FIRST(nameList);
while (node != NULL) {
names[index++] = *node;
node = BSL_LIST_GET_NEXT(nameList);
}
int32_t ret = HITLS_X509_CsrCtrl(csr, HITLS_X509_ADD_SUBJECT_NAME, names, count);
BSL_SAL_FREE(names);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("Failed to add subject name to csr.\n");
}
return ret;
}
static int32_t SetDnTypeAndValue(HITLS_X509_DN *name, const char *nameTypeStr, const char *nameValueStr)
{
const BslAsn1DnInfo *asn1DnInfo = BSL_OBJ_GetDnInfoFromShortName(nameTypeStr);
if (asn1DnInfo == NULL) {
AppPrintError("warning: Skip unknow distinguish name, name type: %s.\n", nameTypeStr);
return HITLS_APP_SUCCESS;
}
if (strlen(nameValueStr) == 0) {
AppPrintError("warning: No value provided for name type: %s.\n", nameTypeStr);
return HITLS_APP_SUCCESS;
}
name->cid = asn1DnInfo->cid;
name->dataLen = strlen(nameValueStr);
name->data = BSL_SAL_Dump(nameValueStr, strlen(nameValueStr) + 1);
if (name->data == NULL) {
AppPrintError("Failed to copy name value when process distinguish name: %s.\n", nameValueStr);
return HITLS_APP_MEM_ALLOC_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t GetDnTypeAndValue(const char **nameStr, HITLS_X509_DN *name, bool *isMultiVal)
{
char *nameTypeStr = NULL;
char *nameValueStr = NULL;
const char *p = *nameStr;
if (*p == '\0') {
return HITLS_APP_SUCCESS;
}
char *tmp = BSL_SAL_Dump(p, strlen(p) + 1);
if (tmp == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
nameTypeStr = tmp;
while (*p != '\0' && *p != '=') {
*tmp++ = *p++;
}
*tmp++ = '\0';
if (*p == '\0') {
AppPrintError("The type(%s) must be have value.\n", nameTypeStr);
BSL_SAL_FREE(nameTypeStr);
return HITLS_APP_INVALID_DN_VALUE;
}
p++; // skip '='
nameValueStr = tmp;
while (*p != '\0' && *p != '/') {
if (*p == '+') {
*isMultiVal = true;
break;
}
if (*p == '\\' && *++p == '\0') {
BSL_SAL_FREE(nameTypeStr);
AppPrintError("Error charactor.\n");
return HITLS_APP_INVALID_DN_VALUE;
}
*tmp++ = *p++;
}
if (*p == '/' || *p == '+') {
*tmp++ = '\0';
}
int32_t ret = SetDnTypeAndValue(name, nameTypeStr, nameValueStr);
BSL_SAL_FREE(nameTypeStr);
*nameStr = p;
return ret;
}
static void FreeX509Dn(HITLS_X509_DN *name)
{
if (name == NULL) {
return;
}
BSL_SAL_FREE(name->data);
BSL_SAL_FREE(name);
}
/* distinguish name format is /type0=value0/type1=value1/type2=... */
int32_t HITLS_APP_CFG_ProcDnName(const char *nameStr, AddDnNameCb addCb, void *ctx)
{
if (nameStr == NULL || addCb == NULL || strlen(nameStr) <= 1 || nameStr[0] != '/') {
return HITLS_APP_INVALID_ARG;
}
int32_t ret = HITLS_APP_SUCCESS;
BslList *dnNameList = NULL;
const char *p = nameStr;
bool isMultiVal = false;
while (*p != '\0') {
p++;
if (!isMultiVal) {
BSL_LIST_FREE(dnNameList, (BSL_LIST_PFUNC_FREE)FreeX509Dn);
dnNameList = BSL_LIST_New(sizeof(HITLS_X509_DN *));
if (dnNameList == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
}
HITLS_X509_DN *name = BSL_SAL_Calloc(1, sizeof(HITLS_X509_DN));
if (name == NULL) {
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
ret = GetDnTypeAndValue(&p, name, &isMultiVal);
if (ret != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(name);
goto EXIT;
}
if (name->data == NULL) {
BSL_SAL_FREE(name);
continue;
}
// add to list
ret = BSL_LIST_AddElement(dnNameList, name, BSL_LIST_POS_END);
if (ret != BSL_SUCCESS) {
BSL_SAL_FREE(name->data);
BSL_SAL_FREE(name);
goto EXIT;
}
if (*p == '/' || *p == '\0') {
// add to csr or cert
ret = addCb(ctx, dnNameList);
BSL_LIST_FREE(dnNameList, (BSL_LIST_PFUNC_FREE)FreeX509Dn);
if (ret != HITLS_APP_SUCCESS) {
goto EXIT;
}
isMultiVal = false;
}
}
if (ret == HITLS_APP_SUCCESS && dnNameList != NULL && BSL_LIST_COUNT(dnNameList) != 0) {
ret = addCb(ctx, dnNameList);
}
EXIT:
BSL_LIST_FREE(dnNameList, (BSL_LIST_PFUNC_FREE)FreeX509Dn);
return ret;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_conf.c | C | unknown | 29,842 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_crl.h"
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <linux/limits.h>
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_types.h"
#include "bsl_errno.h"
#include "hitls_pki_errno.h"
#include "crypt_eal_pkey.h"
#include "crypt_eal_rand.h"
#include "crypt_errno.h"
#include "app_opt.h"
#include "app_function.h"
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_conf.h"
#include "app_utils.h"
#define MAX_CRLFILE_SIZE (256 * 1024)
#define DEFAULT_CERT_SIZE 1024U
typedef enum OptionChoice {
HITLS_APP_OPT_CRL_ERR = -1,
HITLS_APP_OPT_CRL_EOF = 0,
// The first opt of each option is help and is equal to 1. The following opt can be customized.
HITLS_APP_OPT_CRL_HELP = 1,
HITLS_APP_OPT_CRL_IN,
HITLS_APP_OPT_CRL_NOOUT,
HITLS_APP_OPT_CRL_OUT,
HITLS_APP_OPT_CRL_NEXTUPDATE,
HITLS_APP_OPT_CRL_CAFILE,
HITLS_APP_OPT_CRL_INFORM,
HITLS_APP_OPT_CRL_OUTFORM,
} HITLSOptType;
const HITLS_CmdOption g_crlOpts[] = {
{"help", HITLS_APP_OPT_CRL_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"in", HITLS_APP_OPT_CRL_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file"},
{"noout", HITLS_APP_OPT_CRL_NOOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "No CRL output "},
{"out", HITLS_APP_OPT_CRL_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"nextupdate", HITLS_APP_OPT_CRL_NEXTUPDATE, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print CRL nextupdate"},
{"CAfile", HITLS_APP_OPT_CRL_CAFILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Verify CRL using CAFile"},
{"inform", HITLS_APP_OPT_CRL_INFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Input crl file format"},
{"outform", HITLS_APP_OPT_CRL_OUTFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Output crl file format"},
{NULL}
};
typedef struct {
BSL_ParseFormat inform;
BSL_ParseFormat outform;
char *infile;
char *cafile;
char *outfile;
bool noout;
bool nextupdate;
BSL_UIO *uio;
} CrlInfo;
static int32_t DecodeCertFile(uint8_t *infileBuf, uint64_t infileBufLen, HITLS_X509_Cert **tmp)
{
// The input parameter inBufLen is uint64_t, and PEM_decode requires bufLen of uint32_t. Check whether the
// conversion precision is lost.
uint32_t bufLen = (uint32_t)infileBufLen;
if ((uint64_t)bufLen != infileBufLen) {
return HITLS_APP_DECODE_FAIL;
}
BSL_Buffer encode = {infileBuf, bufLen};
return HITLS_X509_CertParseBuff(BSL_FORMAT_UNKNOWN, &encode, tmp);
}
static int32_t VerifyCrlFile(const char *caFile, const HITLS_X509_Crl *crl)
{
BSL_UIO *readUio = HITLS_APP_UioOpen(caFile, 'r', 0);
if (readUio == NULL) {
AppPrintError("Failed to open the file <%s>, No such file or directory\n", caFile);
return HITLS_APP_UIO_FAIL;
}
uint8_t *caFileBuf = NULL;
uint64_t caFileBufLen = 0;
int32_t ret = HITLS_APP_OptReadUio(readUio, &caFileBuf, &caFileBufLen, MAX_CRLFILE_SIZE);
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
BSL_UIO_Free(readUio);
if (ret != HITLS_APP_SUCCESS || caFileBuf == NULL || caFileBufLen == 0) {
BSL_SAL_FREE(caFileBuf);
AppPrintError("Failed to read CAfile from <%s>\n", caFile);
return HITLS_APP_UIO_FAIL;
}
HITLS_X509_Cert *cert = NULL;
ret = DecodeCertFile(caFileBuf, caFileBufLen, &cert); // Decode the CAfile content.
BSL_SAL_FREE(caFileBuf);
if (ret != HITLS_APP_SUCCESS) {
HITLS_X509_CertFree(cert);
AppPrintError("Failed to decode the CAfile <%s>\n", caFile);
return HITLS_APP_DECODE_FAIL;
}
CRYPT_EAL_PkeyCtx *pubKey = NULL;
// Obtaining the Public Key of the CA Certificate
ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_PUBKEY, &pubKey, sizeof(CRYPT_EAL_PkeyCtx *));
HITLS_X509_CertFree(cert);
if (pubKey == NULL) {
AppPrintError("Failed to getting CRL issuer certificate\n");
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CrlVerify(pubKey, crl);
CRYPT_EAL_PkeyFreeCtx((CRYPT_EAL_PkeyCtx *)pubKey);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("The verification result: failed\n");
return HITLS_APP_CERT_VERIFY_FAIL;
}
AppPrintError("The verification result: OK\n");
return HITLS_APP_SUCCESS;
}
static int32_t GetCrlInfoByStd(uint8_t **infileBuf, uint64_t *infileBufLen)
{
(void)AppPrintError("Please enter the key content\n");
size_t crlDataCapacity = DEFAULT_CERT_SIZE;
void *crlData = BSL_SAL_Calloc(crlDataCapacity, sizeof(uint8_t));
if (crlData == NULL) { return HITLS_APP_MEM_ALLOC_FAIL; }
size_t crlDataSize = 0;
bool isMatchCrlData = false;
while (true) {
char *buf = NULL;
size_t bufLen = 0;
ssize_t readLen = getline(&buf, &bufLen, stdin);
if (readLen <= 0) {
free(buf);
(void)AppPrintError("Failed to obtain the standard input.\n");
break;
}
if ((crlDataSize + readLen) > MAX_CRLFILE_SIZE) {
free(buf);
BSL_SAL_FREE(crlData);
AppPrintError("The stdin supports a maximum of %zu bytes.\n", MAX_CRLFILE_SIZE);
return HITLS_APP_STDIN_FAIL;
}
if ((crlDataSize + readLen) > crlDataCapacity) {
// If the space is insufficient, expand the capacity by twice.
size_t newCrlDataCapacity = crlDataCapacity << 1;
/* If the space is insufficient for two times of capacity expansion,
expand the capacity based on the actual length. */
if ((crlDataSize + readLen) > newCrlDataCapacity) {
newCrlDataCapacity = crlDataSize + readLen;
}
crlData = ExpandingMem(crlData, newCrlDataCapacity, crlDataCapacity);
crlDataCapacity = newCrlDataCapacity;
}
if (memcpy_s(crlData + crlDataSize, crlDataCapacity - crlDataSize, buf, readLen) != 0) {
free(buf);
BSL_SAL_FREE(crlData);
return HITLS_APP_SECUREC_FAIL;
}
crlDataSize += readLen;
if (strcmp(buf, "-----BEGIN X509 CRL-----\n") == 0) {
isMatchCrlData = true;
}
if (isMatchCrlData && (strcmp(buf, "-----END X509 CRL-----\n") == 0)) {
free(buf);
break;
}
free(buf);
}
*infileBuf = crlData;
*infileBufLen = crlDataSize;
return (crlDataSize > 0) ? HITLS_APP_SUCCESS : HITLS_APP_STDIN_FAIL;
}
static int32_t GetCrlInfoByFile(char *infile, uint8_t **infileBuf, uint64_t *infileBufLen)
{
int32_t readRet = HITLS_APP_SUCCESS;
BSL_UIO *uio = HITLS_APP_UioOpen(infile, 'r', 0);
if (uio == NULL) {
AppPrintError("Failed to open the CRL from <%s>, No such file or directory\n", infile);
return HITLS_APP_UIO_FAIL;
}
readRet = HITLS_APP_OptReadUio(uio, infileBuf, infileBufLen, MAX_CRLFILE_SIZE);
BSL_UIO_SetIsUnderlyingClosedByUio(uio, true);
BSL_UIO_Free(uio);
if (readRet != HITLS_APP_SUCCESS) {
AppPrintError("Failed to read the CRL from <%s>\n", infile);
return readRet;
}
return HITLS_APP_SUCCESS;
}
static int32_t GetCrlInfo(char *infile, uint8_t **infileBuf, uint64_t *infileBufLen)
{
int32_t getRet = HITLS_APP_SUCCESS;
if (infile == NULL) {
getRet = GetCrlInfoByStd(infileBuf, infileBufLen);
} else {
getRet = GetCrlInfoByFile(infile, infileBuf, infileBufLen);
}
return getRet;
}
static int32_t GetAndDecCRL(CrlInfo *outInfo, uint8_t **infileBuf, uint64_t *infileBufLen, HITLS_X509_Crl **crl)
{
int32_t ret = GetCrlInfo(outInfo->infile, infileBuf, infileBufLen); // Obtaining the CRL File Content
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to obtain the content of the CRL file.\n");
return ret;
}
BSL_Buffer buff = {*infileBuf, *infileBufLen};
ret = HITLS_X509_CrlParseBuff(outInfo->inform, &buff, crl);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("Failed to decode the CRL file.\n");
return HITLS_APP_DECODE_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t OutCrlFileInfo(BSL_UIO *uio, HITLS_X509_Crl *crl, uint32_t format)
{
BSL_Buffer encode = {0};
int32_t ret = HITLS_X509_CrlGenBuff(format, crl, &encode);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("Failed to convert the CRL.\n");
return HITLS_APP_ENCODE_FAIL;
}
ret = HITLS_APP_OptWriteUio(uio, encode.data, encode.dataLen, HITLS_APP_FORMAT_PEM);
BSL_SAL_FREE(encode.data);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("Failed to print the CRL content\n");
}
return ret;
}
static int32_t PrintNextUpdate(BSL_UIO *uio, HITLS_X509_Crl *crl)
{
BSL_TIME time = {0};
int32_t ret = HITLS_X509_CrlCtrl(crl, HITLS_X509_GET_AFTER_TIME, &time, sizeof(BSL_TIME));
if (ret != HITLS_PKI_SUCCESS && ret != HITLS_X509_ERR_CRL_NEXTUPDATE_UNEXIST) {
(void)AppPrintError("Failed to get character string\n");
return HITLS_APP_X509_FAIL;
}
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_NEXTUPDATE, &time, sizeof(BSL_TIME), uio);
if (ret != HITLS_PKI_SUCCESS) {
(void)AppPrintError("Failed to get print string\n");
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t OptParse(CrlInfo *outInfo)
{
HITLSOptType optType;
int ret = HITLS_APP_SUCCESS;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_CRL_EOF) {
switch (optType) {
case HITLS_APP_OPT_CRL_EOF:
case HITLS_APP_OPT_CRL_ERR:
ret = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("crl: Use -help for summary.\n");
return ret;
case HITLS_APP_OPT_CRL_HELP:
ret = HITLS_APP_HELP;
(void)HITLS_APP_OptHelpPrint(g_crlOpts);
return ret;
case HITLS_APP_OPT_CRL_OUT:
outInfo->outfile = HITLS_APP_OptGetValueStr();
if (outInfo->outfile == NULL || strlen(outInfo->outfile) >= PATH_MAX) {
AppPrintError("The length of outfile error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_CRL_NOOUT:
outInfo->noout = true;
break;
case HITLS_APP_OPT_CRL_IN:
outInfo->infile = HITLS_APP_OptGetValueStr();
if (outInfo->infile == NULL || strlen(outInfo->infile) >= PATH_MAX) {
AppPrintError("The length of input file error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_CRL_CAFILE:
outInfo->cafile = HITLS_APP_OptGetValueStr();
if (outInfo->cafile == NULL || strlen(outInfo->cafile) >= PATH_MAX) {
AppPrintError("The length of CA file error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_CRL_NEXTUPDATE:
outInfo->nextupdate = true;
break;
case HITLS_APP_OPT_CRL_INFORM:
if (HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_PEMDER,
&outInfo->inform) != HITLS_APP_SUCCESS) {
AppPrintError("The informat of crl file error.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_CRL_OUTFORM:
if (HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_PEMDER,
&outInfo->outform) != HITLS_APP_SUCCESS) {
AppPrintError("The format of crl file error.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
default:
return HITLS_APP_OPT_UNKOWN;
}
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_CrlMain(int argc, char *argv[])
{
CrlInfo crlInfo = {0, BSL_FORMAT_PEM, NULL, NULL, NULL, false, false, NULL};
HITLS_X509_Crl *crl = NULL;
uint8_t *infileBuf = NULL;
uint64_t infileBufLen = 0;
int32_t mainRet = HITLS_APP_OptBegin(argc, argv, g_crlOpts);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("error in opt begin.\n");
goto end;
}
mainRet = OptParse(&crlInfo);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
int unParseParamNum = HITLS_APP_GetRestOptNum();
if (unParseParamNum != 0) { // The input parameters are not completely parsed.
(void)AppPrintError("Extra arguments given.\n");
(void)AppPrintError("crl: Use -help for summary.\n");
mainRet = HITLS_APP_OPT_UNKOWN;
goto end;
}
mainRet = GetAndDecCRL(&crlInfo, &infileBuf, &infileBufLen, &crl);
if (mainRet != HITLS_APP_SUCCESS) {
HITLS_X509_CrlFree(crl);
goto end;
}
crlInfo.uio = HITLS_APP_UioOpen(crlInfo.outfile, 'w', 0);
if (crlInfo.uio == NULL) {
(void)AppPrintError("Failed to open the standard output.");
mainRet = HITLS_APP_UIO_FAIL;
goto end;
}
BSL_UIO_SetIsUnderlyingClosedByUio(crlInfo.uio, !(crlInfo.outfile == NULL));
if (crlInfo.nextupdate == true) {
mainRet = PrintNextUpdate(crlInfo.uio, crl);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
}
if (crlInfo.cafile != NULL) {
mainRet = VerifyCrlFile(crlInfo.cafile, crl);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
}
if (crlInfo.noout == false) {
mainRet = OutCrlFileInfo(crlInfo.uio, crl, crlInfo.outform);
}
end:
HITLS_X509_CrlFree(crl);
BSL_SAL_FREE(infileBuf);
BSL_UIO_Free(crlInfo.uio);
HITLS_APP_OptEnd();
return mainRet;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_crl.c | C | unknown | 14,575 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_dgst.h"
#include <linux/limits.h>
#include "string.h"
#include "securec.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_eal_md.h"
#include "bsl_errno.h"
#include "app_opt.h"
#include "app_function.h"
#include "app_list.h"
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#define MAX_BUFSIZE (1024 * 8) // Indicates the length of a single digest during digest calculation.
#define IS_SUPPORT_GET_EOF 1
#define DEFAULT_SHAKE256_SIZE 32
#define DEFAULT_SHAKE128_SIZE 16
typedef enum OptionChoice {
HITLS_APP_OPT_DGST_ERR = -1,
HITLS_APP_OPT_DGST_EOF = 0,
HITLS_APP_OPT_DGST_FILE = HITLS_APP_OPT_DGST_EOF,
HITLS_APP_OPT_DGST_HELP =
1, // The value of the help type of each opt option is 1. The following can be customized.
HITLS_APP_OPT_DGST_ALG,
HITLS_APP_OPT_DGST_OUT,
} HITLSOptType;
const HITLS_CmdOption g_dgstOpts[] = {
{"help", HITLS_APP_OPT_DGST_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"md", HITLS_APP_OPT_DGST_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Digest algorithm"},
{"out", HITLS_APP_OPT_DGST_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output the summary result to a file"},
{"file...", HITLS_APP_OPT_DGST_FILE, HITLS_APP_OPT_VALUETYPE_PARAMTERS, "Files to be digested"},
{NULL}};
typedef struct {
char *algName;
int32_t algId;
uint32_t digestSize; // the length of default hash value of the algorithm
} AlgInfo;
static AlgInfo g_dgstInfo = {"sha256", CRYPT_MD_SHA256, 0};
static int32_t g_argc = 0;
static char **g_argv;
static int32_t OptParse(char **outfile);
static CRYPT_EAL_MdCTX *InitAlgDigest(CRYPT_MD_AlgId id);
static int32_t ReadFileToBuf(CRYPT_EAL_MdCTX *ctx, const char *filename);
static int32_t HashValToFinal(
uint8_t *hashBuf, uint32_t hashBufLen, uint8_t **buf, uint32_t *bufLen, const char *filename);
static int32_t MdFinalToBuf(CRYPT_EAL_MdCTX *ctx, uint8_t **buf, uint32_t *bufLen, const char *filename);
static int32_t BufOutToUio(const char *outfile, BSL_UIO *fileWriteUio, uint8_t *outBuf, uint32_t outBufLen);
static int32_t MultiFileSetCtx(CRYPT_EAL_MdCTX *ctx);
static int32_t StdSumAndOut(CRYPT_EAL_MdCTX *ctx, const char *outfile);
static int32_t FileSumOutFile(CRYPT_EAL_MdCTX *ctx, const char *outfile);
static int32_t FileSumOutStd(CRYPT_EAL_MdCTX *ctx);
static int32_t FileSumAndOut(CRYPT_EAL_MdCTX *ctx, const char *outfile);
int32_t HITLS_DgstMain(int argc, char *argv[])
{
char *outfile = NULL;
int32_t mainRet = HITLS_APP_SUCCESS;
CRYPT_EAL_MdCTX *ctx = NULL;
mainRet = HITLS_APP_OptBegin(argc, argv, g_dgstOpts);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("error in opt begin.\n");
goto end;
}
mainRet = OptParse(&outfile);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
g_argc = HITLS_APP_GetRestOptNum();
g_argv = HITLS_APP_GetRestOpt();
ctx = InitAlgDigest(g_dgstInfo.algId);
if (ctx == NULL) {
mainRet = HITLS_APP_CRYPTO_FAIL;
goto end;
}
if (g_dgstInfo.algId == CRYPT_MD_SHAKE128) {
g_dgstInfo.digestSize = DEFAULT_SHAKE128_SIZE;
} else if (g_dgstInfo.algId == CRYPT_MD_SHAKE256) {
g_dgstInfo.digestSize = DEFAULT_SHAKE256_SIZE;
} else {
g_dgstInfo.digestSize = CRYPT_EAL_MdGetDigestSize(g_dgstInfo.algId);
if (g_dgstInfo.digestSize == 0) {
mainRet = HITLS_APP_CRYPTO_FAIL;
(void)AppPrintError("Failed to obtain the default length of the algorithm(%s)\n", g_dgstInfo.algName);
goto end;
}
}
mainRet = (g_argc == 0) ? StdSumAndOut(ctx, outfile) : FileSumAndOut(ctx, outfile);
CRYPT_EAL_MdDeinit(ctx); // algorithm release
end:
CRYPT_EAL_MdFreeCtx(ctx);
HITLS_APP_OptEnd();
return mainRet;
}
static int32_t StdSumAndOut(CRYPT_EAL_MdCTX *ctx, const char *outfile)
{
int32_t stdRet = HITLS_APP_SUCCESS;
BSL_UIO *readUio = HITLS_APP_UioOpen(NULL, 'r', 1);
if (readUio == NULL) {
AppPrintError("Failed to open the stdin\n");
return HITLS_APP_UIO_FAIL;
}
uint32_t readLen = MAX_BUFSIZE;
uint8_t readBuf[MAX_BUFSIZE] = {0};
bool isEof = false;
while (BSL_UIO_Ctrl(readUio, BSL_UIO_FILE_GET_EOF, IS_SUPPORT_GET_EOF, &isEof) == BSL_SUCCESS && !isEof) {
if (BSL_UIO_Read(readUio, readBuf, MAX_BUFSIZE, &readLen) != BSL_SUCCESS) {
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to obtain the content from the STDIN\n");
return HITLS_APP_STDIN_FAIL;
}
if (readLen == 0) {
break;
}
stdRet = CRYPT_EAL_MdUpdate(ctx, readBuf, readLen);
if (stdRet != CRYPT_SUCCESS) {
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to continuously summarize the STDIN content\n");
return HITLS_APP_CRYPTO_FAIL;
}
}
BSL_UIO_Free(readUio);
uint8_t *outBuf = NULL;
uint32_t outBufLen = 0;
// reads the final hash value to the buffer
stdRet = MdFinalToBuf(ctx, &outBuf, &outBufLen, "stdin");
if (stdRet != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(outBuf);
return stdRet;
}
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(outfile, 'w', 1);
if (fileWriteUio == NULL) {
BSL_UIO_Free(fileWriteUio);
BSL_SAL_FREE(outBuf);
AppPrintError("Failed to open the <%s>\n", outfile);
return HITLS_APP_UIO_FAIL;
}
// outputs the hash value to the UIO
stdRet = BufOutToUio(outfile, fileWriteUio, (uint8_t *)outBuf, outBufLen);
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
BSL_SAL_FREE(outBuf);
return stdRet;
}
static int32_t ReadFileToBuf(CRYPT_EAL_MdCTX *ctx, const char *filename)
{
int32_t readRet = HITLS_APP_SUCCESS;
BSL_UIO *readUio = HITLS_APP_UioOpen(filename, 'r', 0);
if (readUio == NULL) {
(void)AppPrintError("Failed to open the file <%s>, No such file or directory\n", filename);
return HITLS_APP_UIO_FAIL;
}
uint64_t readFileLen = 0;
readRet = BSL_UIO_Ctrl(readUio, BSL_UIO_PENDING, sizeof(readFileLen), &readFileLen);
if (readRet != BSL_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to obtain the content length\n");
return HITLS_APP_UIO_FAIL;
}
while (readFileLen > 0) {
uint8_t readBuf[MAX_BUFSIZE] = {0};
uint32_t bufLen = (readFileLen > MAX_BUFSIZE) ? MAX_BUFSIZE : (uint32_t)readFileLen;
uint32_t readLen = 0;
readRet = BSL_UIO_Read(readUio, readBuf, bufLen, &readLen); // read content to memory
if (readRet != BSL_SUCCESS || bufLen != readLen) {
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to read the input content\n");
return HITLS_APP_UIO_FAIL;
}
readRet = CRYPT_EAL_MdUpdate(ctx, readBuf, bufLen); // continuously enter summary content
if (readRet != CRYPT_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to continuously summarize the file content\n");
return HITLS_APP_CRYPTO_FAIL;
}
readFileLen -= bufLen;
}
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
BSL_UIO_Free(readUio);
return HITLS_APP_SUCCESS;
}
static int32_t BufOutToUio(const char *outfile, BSL_UIO *fileWriteUio, uint8_t *outBuf, uint32_t outBufLen)
{
int32_t outRet = HITLS_APP_SUCCESS;
if (outfile == NULL) {
BSL_UIO *stdOutUio = HITLS_APP_UioOpen(NULL, 'w', 0);
if (stdOutUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
outRet = HITLS_APP_OptWriteUio(stdOutUio, outBuf, outBufLen, HITLS_APP_FORMAT_TEXT);
BSL_UIO_Free(stdOutUio);
if (outRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("Failed to output the content to the screen\n");
return HITLS_APP_UIO_FAIL;
}
} else {
outRet = HITLS_APP_OptWriteUio(fileWriteUio, outBuf, outBufLen, HITLS_APP_FORMAT_TEXT);
if (outRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("Failed to export data to the file path: <%s>\n", outfile);
return HITLS_APP_UIO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t HashValToFinal(
uint8_t *hashBuf, uint32_t hashBufLen, uint8_t **buf, uint32_t *bufLen, const char *filename)
{
int32_t outRet = HITLS_APP_SUCCESS;
uint32_t hexBufLen = hashBufLen * 2 + 1;
uint8_t *hexBuf = (uint8_t *)BSL_SAL_Calloc(hexBufLen, sizeof(uint8_t)); // save the hexadecimal hash value
if (hexBuf == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
outRet = HITLS_APP_OptToHex(hashBuf, hashBufLen, (char *)hexBuf, hexBufLen);
if (outRet != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(hexBuf);
return HITLS_APP_ENCODE_FAIL;
}
uint32_t outBufLen;
if (g_argc == 0) {
// standard input(stdin) = hashValue,
// 5 indicates " " + "()" + "=" + "\n"
outBufLen = strlen("stdin") + hexBufLen + 5;
} else {
// 5: " " + "()" + "=" + "\n", and concatenate the string alg_name(filename1)=hash.
outBufLen = strlen(g_dgstInfo.algName) + strlen(filename) + hexBufLen + 5;
}
char *outBuf = (char *)BSL_SAL_Calloc(outBufLen, sizeof(char)); // save the concatenated hash value
if (outBuf == NULL) {
(void)AppPrintError("Failed to open the format control content space\n");
BSL_SAL_FREE(hexBuf);
return HITLS_APP_MEM_ALLOC_FAIL;
}
if (g_argc == 0) { // standard input
outRet = snprintf_s(outBuf, outBufLen, outBufLen - 1, "(%s)= %s\n", "stdin", (char *)hexBuf);
} else {
outRet = snprintf_s(
outBuf, outBufLen, outBufLen - 1, "%s(%s)= %s\n", g_dgstInfo.algName, filename, (char *)hexBuf);
}
uint32_t len = strlen(outBuf);
BSL_SAL_FREE(hexBuf);
if (outRet == -1) {
BSL_SAL_FREE(outBuf);
(void)AppPrintError("Failed to combine the output content\n");
return HITLS_APP_SECUREC_FAIL;
}
char *finalOutBuf = (char *)BSL_SAL_Calloc(len, sizeof(char));
if (memcpy_s(finalOutBuf, len, outBuf, strlen(outBuf)) != EOK) {
BSL_SAL_FREE(outBuf);
BSL_SAL_FREE(finalOutBuf);
return HITLS_APP_SECUREC_FAIL;
}
BSL_SAL_FREE(outBuf);
*buf = (uint8_t *)finalOutBuf;
*bufLen = len;
return HITLS_APP_SUCCESS;
}
static int32_t MdFinalToBuf(CRYPT_EAL_MdCTX *ctx, uint8_t **buf, uint32_t *bufLen, const char *filename)
{
int32_t outRet = HITLS_APP_SUCCESS;
// save the initial hash value
uint8_t *hashBuf = (uint8_t *)BSL_SAL_Calloc(g_dgstInfo.digestSize + 1, sizeof(uint8_t));
if (hashBuf == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
uint32_t hashBufLen = g_dgstInfo.digestSize;
outRet = CRYPT_EAL_MdFinal(ctx, hashBuf, &hashBufLen); // complete the digest and output the final digest to the buf
if (outRet != CRYPT_SUCCESS || hashBufLen < g_dgstInfo.digestSize) {
BSL_SAL_FREE(hashBuf);
(void)AppPrintError("filename: %s Failed to complete the final summary\n", filename);
return HITLS_APP_CRYPTO_FAIL;
}
outRet = HashValToFinal(hashBuf, hashBufLen, buf, bufLen, filename);
BSL_SAL_FREE(hashBuf);
return outRet;
}
static int32_t FileSumOutStd(CRYPT_EAL_MdCTX *ctx)
{
int32_t outRet = HITLS_APP_SUCCESS;
// Traverse the files that need to be digested, obtain the file content, calculate the file content digest,
// and output the digest to the UIO.
for (int i = 0; i < g_argc; ++i) {
outRet = CRYPT_EAL_MdDeinit(ctx); // md release
if (outRet != CRYPT_SUCCESS) {
(void)AppPrintError("Summary context deinit failed.\n");
return HITLS_APP_CRYPTO_FAIL;
}
outRet = CRYPT_EAL_MdInit(ctx); // md initialization
if (outRet != CRYPT_SUCCESS) {
(void)AppPrintError("Summary context creation failed.\n");
return HITLS_APP_CRYPTO_FAIL;
}
outRet = ReadFileToBuf(ctx, g_argv[i]); // read the file content by block and calculate the hash value
if (outRet != HITLS_APP_SUCCESS) {
return HITLS_APP_UIO_FAIL;
}
uint8_t *outBuf = NULL;
uint32_t outBufLen = 0;
outRet = MdFinalToBuf(ctx, &outBuf, &outBufLen, g_argv[i]); // read the final hash value to the buffer
if (outRet != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(outBuf);
(void)AppPrintError("Failed to output the final summary value\n");
return outRet;
}
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(NULL, 'w', 0); // the standard output is required for each file
if (fileWriteUio == NULL) {
BSL_SAL_FREE(outBuf);
(void)AppPrintError("Failed to open the stdout\n");
return HITLS_APP_UIO_FAIL;
}
outRet = BufOutToUio(NULL, fileWriteUio, (uint8_t *)outBuf, outBufLen); // output the hash value to the UIO
BSL_SAL_FREE(outBuf);
BSL_UIO_Free(fileWriteUio);
if (outRet != HITLS_APP_SUCCESS) { // Released after the standard output is complete
(void)AppPrintError("Failed to output the hash value\n");
return outRet;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t MultiFileSetCtx(CRYPT_EAL_MdCTX *ctx)
{
int32_t outRet = CRYPT_EAL_MdDeinit(ctx); // md release
if (outRet != CRYPT_SUCCESS) {
(void)AppPrintError("Summary context deinit failed.\n");
return HITLS_APP_CRYPTO_FAIL;
}
outRet = CRYPT_EAL_MdInit(ctx); // md initialization
if (outRet != CRYPT_SUCCESS) {
(void)AppPrintError("Summary context creation failed.\n");
return HITLS_APP_CRYPTO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t FileSumOutFile(CRYPT_EAL_MdCTX *ctx, const char *outfile)
{
int32_t outRet = HITLS_APP_SUCCESS;
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(outfile, 'w', 0); // overwrite the original content
if (fileWriteUio == NULL) {
(void)AppPrintError("Failed to open the file path: %s\n", outfile);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
fileWriteUio = HITLS_APP_UioOpen(outfile, 'a', 0);
if (fileWriteUio == NULL) {
(void)AppPrintError("Failed to open the file path: %s\n", outfile);
return HITLS_APP_UIO_FAIL;
}
for (int i = 0; i < g_argc; ++i) {
// Traverse the files that need to be digested, obtain the file content, calculate the file content digest,
// and output the digest to the UIO.
outRet = MultiFileSetCtx(ctx);
if (outRet != HITLS_APP_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
return outRet;
}
outRet = ReadFileToBuf(ctx, g_argv[i]); // read the file content by block and calculate the hash value
if (outRet != HITLS_APP_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
(void)AppPrintError("Failed to read the file content by block and calculate the hash value\n");
return HITLS_APP_UIO_FAIL;
}
uint8_t *outBuf = NULL;
uint32_t outBufLen = 0;
outRet = MdFinalToBuf(ctx, &outBuf, &outBufLen, g_argv[i]); // read the final hash value to the buffer
if (outRet != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(outBuf);
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
(void)AppPrintError("Failed to output the final summary value\n");
return outRet;
}
outRet = BufOutToUio(outfile, fileWriteUio, (uint8_t *)outBuf, outBufLen); // output the hash value to the UIO
BSL_SAL_FREE(outBuf);
if (outRet != HITLS_APP_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
return outRet;
}
}
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
BSL_UIO_Free(fileWriteUio);
return HITLS_APP_SUCCESS;
}
static int32_t FileSumAndOut(CRYPT_EAL_MdCTX *ctx, const char *outfile)
{
int32_t outRet = HITLS_APP_SUCCESS;
if (outfile == NULL) {
// standard output, w overwriting mode
outRet = FileSumOutStd(ctx);
} else {
// file output appending mode
outRet = FileSumOutFile(ctx, outfile);
}
return outRet;
}
static CRYPT_EAL_MdCTX *InitAlgDigest(CRYPT_MD_AlgId id)
{
CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_ProviderMdNewCtx(NULL, id, "provider=default"); // creating an MD Context
if (ctx == NULL) {
(void)AppPrintError("Failed to create the algorithm(%s) context\n", g_dgstInfo.algName);
return NULL;
}
int32_t ret = CRYPT_EAL_MdInit(ctx); // md initialization
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("Summary context creation failed\n");
CRYPT_EAL_MdFreeCtx(ctx);
return NULL;
}
return ctx;
}
static int32_t OptParse(char **outfile)
{
HITLSOptType optType;
int ret = HITLS_APP_SUCCESS;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_DGST_EOF) {
switch (optType) {
case HITLS_APP_OPT_DGST_EOF:
case HITLS_APP_OPT_DGST_ERR:
ret = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("dgst: Use -help for summary.\n");
return ret;
case HITLS_APP_OPT_DGST_HELP:
ret = HITLS_APP_HELP;
(void)HITLS_APP_OptHelpPrint(g_dgstOpts);
return ret;
case HITLS_APP_OPT_DGST_OUT:
*outfile = HITLS_APP_OptGetValueStr();
if (*outfile == NULL || strlen(*outfile) >= PATH_MAX) {
AppPrintError("The length of outfile error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_DGST_ALG:
g_dgstInfo.algName = HITLS_APP_OptGetValueStr();
if (g_dgstInfo.algName == NULL) {
return HITLS_APP_OPT_VALUE_INVALID;
}
g_dgstInfo.algId = HITLS_APP_GetCidByName(g_dgstInfo.algName, HITLS_APP_LIST_OPT_DGST_ALG);
if (g_dgstInfo.algId == BSL_CID_UNKNOWN) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
default:
return HITLS_APP_OPT_UNKOWN;
}
}
return HITLS_APP_SUCCESS;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_dgst.c | C | unknown | 19,488 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_enc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <termios.h>
#include <unistd.h>
#include <sys/stat.h>
#include <securec.h>
#include "bsl_uio.h"
#include "app_utils.h"
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_opt.h"
#include "bsl_sal.h"
#include "sal_file.h"
#include "ui_type.h"
#include "bsl_ui.h"
#include "bsl_errno.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_kdf.h"
#include "crypt_algid.h"
#include "crypt_errno.h"
#include "crypt_params_key.h"
static const HITLS_CmdOption g_encOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"cipher", HITLS_APP_OPT_CIPHER_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Cipher algorthm"},
{"in", HITLS_APP_OPT_IN_FILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file"},
{"out", HITLS_APP_OPT_OUT_FILE, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"dec", HITLS_APP_OPT_DEC, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Encryption operation"},
{"enc", HITLS_APP_OPT_ENC, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Decryption operation"},
{"md", HITLS_APP_OPT_MD, HITLS_APP_OPT_VALUETYPE_STRING, "Specified digest to create a key"},
{"pass", HITLS_APP_OPT_PASS, HITLS_APP_OPT_VALUETYPE_STRING, "Passphrase source, such as stdin ,file etc"},
{NULL}
};
static const HITLS_CipherAlgList g_cIdList[] = {
{CRYPT_CIPHER_AES128_CBC, "aes128_cbc"},
{CRYPT_CIPHER_AES192_CBC, "aes192_cbc"},
{CRYPT_CIPHER_AES256_CBC, "aes256_cbc"},
{CRYPT_CIPHER_AES128_CTR, "aes128_ctr"},
{CRYPT_CIPHER_AES192_CTR, "aes192_ctr"},
{CRYPT_CIPHER_AES256_CTR, "aes256_ctr"},
{CRYPT_CIPHER_AES128_ECB, "aes128_ecb"},
{CRYPT_CIPHER_AES192_ECB, "aes192_ecb"},
{CRYPT_CIPHER_AES256_ECB, "aes256_ecb"},
{CRYPT_CIPHER_AES128_XTS, "aes128_xts"},
{CRYPT_CIPHER_AES256_XTS, "aes256_xts"},
{CRYPT_CIPHER_AES128_GCM, "aes128_gcm"},
{CRYPT_CIPHER_AES192_GCM, "aes192_gcm"},
{CRYPT_CIPHER_AES256_GCM, "aes256_gcm"},
{CRYPT_CIPHER_CHACHA20_POLY1305, "chacha20_poly1305"},
{CRYPT_CIPHER_SM4_CBC, "sm4_cbc"},
{CRYPT_CIPHER_SM4_ECB, "sm4_ecb"},
{CRYPT_CIPHER_SM4_CTR, "sm4_ctr"},
{CRYPT_CIPHER_SM4_GCM, "sm4_gcm"},
{CRYPT_CIPHER_SM4_CFB, "sm4_cfb"},
{CRYPT_CIPHER_SM4_OFB, "sm4_ofb"},
{CRYPT_CIPHER_AES128_CFB, "aes128_cfb"},
{CRYPT_CIPHER_AES192_CFB, "aes192_cfb"},
{CRYPT_CIPHER_AES256_CFB, "aes256_cfb"},
{CRYPT_CIPHER_AES128_OFB, "aes128_ofb"},
{CRYPT_CIPHER_AES192_OFB, "aes192_ofb"},
{CRYPT_CIPHER_AES256_OFB, "aes256_ofb"},
};
static const HITLS_MacAlgList g_mIdList[] = {
{CRYPT_MAC_HMAC_MD5, "md5"},
{CRYPT_MAC_HMAC_SHA1, "sha1"},
{CRYPT_MAC_HMAC_SHA224, "sha224"},
{CRYPT_MAC_HMAC_SHA256, "sha256"},
{CRYPT_MAC_HMAC_SHA384, "sha384"},
{CRYPT_MAC_HMAC_SHA512, "sha512"},
{CRYPT_MAC_HMAC_SM3, "sm3"},
{CRYPT_MAC_HMAC_SHA3_224, "sha3_224"},
{CRYPT_MAC_HMAC_SHA3_256, "sha3_256"},
{CRYPT_MAC_HMAC_SHA3_384, "sha3_384"},
{CRYPT_MAC_HMAC_SHA3_512, "sha3_512"}
};
static const uint32_t CIPHER_IS_BlOCK[] = {
CRYPT_CIPHER_AES128_CBC,
CRYPT_CIPHER_AES192_CBC,
CRYPT_CIPHER_AES256_CBC,
CRYPT_CIPHER_AES128_ECB,
CRYPT_CIPHER_AES192_ECB,
CRYPT_CIPHER_AES256_ECB,
CRYPT_CIPHER_SM4_CBC,
CRYPT_CIPHER_SM4_ECB,
};
static const uint32_t CIPHER_IS_XTS[] = {
CRYPT_CIPHER_AES128_XTS,
CRYPT_CIPHER_AES256_XTS,
};
typedef struct {
char *pass;
uint32_t passLen;
unsigned char *salt;
uint32_t saltLen;
unsigned char *iv;
uint32_t ivLen;
unsigned char *dKey;
uint32_t dKeyLen;
CRYPT_EAL_CipherCtx *ctx;
uint32_t blockSize;
} EncKeyParam;
typedef struct {
BSL_UIO *rUio;
BSL_UIO *wUio;
} EncUio;
typedef struct {
uint32_t version;
char *inFile;
char *outFile;
char *passOptStr; // Indicates the following value of the -pass option entered by the user.
int32_t cipherId; // Indicates the symmetric encryption algorithm ID entered by the user.
int32_t mdId; // Indicates the HMAC algorithm ID entered by the user.
int32_t encTag; // Indicates the encryption/decryption flag entered by the user.
uint32_t iter; // Indicates the number of iterations entered by the user.
EncKeyParam *keySet;
EncUio *encUio;
} EncCmdOpt;
static int32_t GetPwdFromFile(const char *fileArg, char *tmpPass);
static int32_t Str2HexStr(const unsigned char *buf, uint32_t bufLen, char *hexBuf, uint32_t hexBufLen);
static int32_t HexToStr(const char *hexBuf, unsigned char *buf);
static int32_t Int2Hex(uint32_t num, char *hexBuf);
static uint32_t Hex2Uint(char *hexBuf, int32_t *num);
static void PrintHMacAlgList(void);
static void PrintCipherAlgList(void);
static int32_t HexAndWrite(EncCmdOpt *encOpt, uint32_t decData, char *buf);
static int32_t ReadAndDec(EncCmdOpt *encOpt, char *hexBuf, uint32_t hexBufLen, int32_t *decData);
static int32_t GetCipherId(const char *name);
static int32_t GetHMacId(const char *mdName);
static int32_t GetPasswd(const char *arg, bool mode, char *resPass);
static int32_t CheckPasswd(const char *passwd);
// process for the ENC to receive subordinate options
static int32_t HandleOpt(EncCmdOpt *encOpt)
{
int32_t encOptType;
while ((encOptType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
switch (encOptType) {
case HITLS_APP_OPT_EOF:
break;
case HITLS_APP_OPT_ERR:
AppPrintError("enc: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_OPT_HELP:
HITLS_APP_OptHelpPrint(g_encOpts);
return HITLS_APP_HELP;
case HITLS_APP_OPT_ENC:
encOpt->encTag = 1;
break;
case HITLS_APP_OPT_DEC:
encOpt->encTag = 0;
break;
case HITLS_APP_OPT_IN_FILE:
encOpt->inFile = HITLS_APP_OptGetValueStr();
break;
case HITLS_APP_OPT_OUT_FILE:
encOpt->outFile = HITLS_APP_OptGetValueStr();
break;
case HITLS_APP_OPT_PASS:
encOpt->passOptStr = HITLS_APP_OptGetValueStr();
break;
case HITLS_APP_OPT_MD:
if ((encOpt->mdId = GetHMacId(HITLS_APP_OptGetValueStr())) == -1) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_CIPHER_ALG:
if ((encOpt->cipherId = GetCipherId(HITLS_APP_OptGetValueStr())) == -1) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
default:
break;
}
}
// Obtain the number of parameters that cannot be parsed in the current version
// and print the error information and help list.
if (HITLS_APP_GetRestOptNum() != 0) {
AppPrintError("Extra arguments given.\n");
AppPrintError("enc: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
// enc check the validity of option parameters
static int32_t CheckParam(EncCmdOpt *encOpt)
{
// if the -cipher option is not specified, an error is returned
if (encOpt->cipherId < 0) {
AppPrintError("The cipher algorithm is not specified.\n");
AppPrintError("enc: Use -help for summary.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
// if the user does not specify the encryption or decryption mode,
// an error is reported and the user is prompted to enter the following information
if (encOpt->encTag != 1 && encOpt->encTag != 0) {
AppPrintError("You have not entered the -enc or -dec option.\n");
AppPrintError("enc: Use -help for summary.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
// if the number of iterations is not set, the default value is 10000
if (encOpt->iter == 0) {
encOpt->iter = REC_ITERATION_TIMES;
}
// if the user does not transfer the digest algorithm, SHA256 is used by default to generate the derived key Dkey
if (encOpt->mdId < 0) {
encOpt->mdId = CRYPT_MAC_HMAC_SHA256;
}
// determine an ivLen based on the cipher ID entered by the user
if (CRYPT_EAL_CipherGetInfo(encOpt->cipherId, CRYPT_INFO_IV_LEN, &encOpt->keySet->ivLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to get the iv length from cipher ID.\n");
return HITLS_APP_CRYPTO_FAIL;
}
if (encOpt->inFile != NULL && strlen(encOpt->inFile) > REC_MAX_FILENAME_LENGTH) {
AppPrintError("The input file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (encOpt->outFile != NULL && strlen(encOpt->outFile) > REC_MAX_FILENAME_LENGTH) {
AppPrintError("The output file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
// enc determines the input and output paths
static int32_t HandleIO(EncCmdOpt *encOpt)
{
// Obtain the last value of the IN option.
// If there is no last value or this option does not exist, the standard input is used.
// If the file fails to be read, the process ends.
if (encOpt->inFile == NULL) {
// User doesn't input file upload path. Read the content directly entered by the user from the standard input.
encOpt->encUio->rUio = HITLS_APP_UioOpen(NULL, 'r', 1);
if (encOpt->encUio->rUio == NULL) {
AppPrintError("Failed to open the stdin.\n");
return HITLS_APP_UIO_FAIL;
}
} else {
// user inputs the file path and reads the content in the file from the file
encOpt->encUio->rUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (BSL_UIO_Ctrl(encOpt->encUio->rUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_READ, encOpt->inFile) != BSL_SUCCESS) {
AppPrintError("Failed to set infile mode.\n");
return HITLS_APP_UIO_FAIL;
}
if (encOpt->encUio->rUio == NULL) {
AppPrintError("Sorry, the file content fails to be read. Please check the file path.\n");
return HITLS_APP_UIO_FAIL;
}
}
// Obtain the post-value of the OUT option.
// If there is no post-value or the option does not exist, the standard output is used.
if (encOpt->outFile == NULL) {
encOpt->encUio->wUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (BSL_UIO_Ctrl(encOpt->encUio->wUio, BSL_UIO_FILE_PTR, 0, (void *)stdout) != BSL_SUCCESS) {
AppPrintError("Failed to set stdout mode.\n");
return HITLS_APP_UIO_FAIL;
}
} else {
// The file path transferred by the user is bound to the output file.
encOpt->encUio->wUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (BSL_UIO_Ctrl(encOpt->encUio->wUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_WRITE, encOpt->outFile) != BSL_SUCCESS ||
chmod(encOpt->outFile, S_IRUSR | S_IWUSR) != 0) {
AppPrintError("Failed to set outfile mode.\n");
return HITLS_APP_UIO_FAIL;
}
}
if (encOpt->encUio->wUio == NULL) {
AppPrintError("Failed to create the output pipeline.\n");
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static void FreeEnc(EncCmdOpt *encOpt)
{
if (encOpt->keySet->pass != NULL) {
BSL_SAL_ClearFree(encOpt->keySet->pass, encOpt->keySet->passLen);
}
if (encOpt->keySet->dKey != NULL) {
BSL_SAL_ClearFree(encOpt->keySet->dKey, encOpt->keySet->dKeyLen);
}
if (encOpt->keySet->salt != NULL) {
BSL_SAL_ClearFree(encOpt->keySet->salt, encOpt->keySet->saltLen);
}
if (encOpt->keySet->iv != NULL) {
BSL_SAL_ClearFree(encOpt->keySet->iv, encOpt->keySet->ivLen);
}
if (encOpt->keySet->ctx != NULL) {
CRYPT_EAL_CipherFreeCtx(encOpt->keySet->ctx);
}
if (encOpt->encUio->rUio != NULL) {
if (encOpt->inFile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(encOpt->encUio->rUio, true);
}
BSL_UIO_Free(encOpt->encUio->rUio);
}
if (encOpt->encUio->wUio != NULL) {
if (encOpt->outFile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(encOpt->encUio->wUio, true);
}
BSL_UIO_Free(encOpt->encUio->wUio);
}
return;
}
static int32_t ApplyForSpace(EncCmdOpt *encOpt)
{
if (encOpt == NULL || encOpt->keySet == NULL) {
return HITLS_APP_INVALID_ARG;
}
encOpt->keySet->pass = (char *)BSL_SAL_Calloc(APP_MAX_PASS_LENGTH + 1, sizeof(char));
if (encOpt->keySet->pass == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
encOpt->keySet->salt = (unsigned char *)BSL_SAL_Calloc(REC_SALT_LEN + 1, sizeof(unsigned char));
if (encOpt->keySet->salt == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
encOpt->keySet->saltLen = REC_SALT_LEN;
encOpt->keySet->iv = (unsigned char *)BSL_SAL_Calloc(REC_MAX_IV_LENGTH + 1, sizeof(unsigned char));
if (encOpt->keySet->iv == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
encOpt->keySet->dKey = (unsigned char *)BSL_SAL_Calloc(REC_MAX_MAC_KEY_LEN + 1, sizeof(unsigned char));
if (encOpt->keySet->dKey == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
return HITLS_APP_SUCCESS;
}
// enc parses the password entered by the user
static int32_t HandlePasswd(EncCmdOpt *encOpt)
{
// If the user enters the last value of -pass, the system parses the value directly.
// If the user does not enter the value, the system reads the value from the standard input.
if (encOpt->passOptStr != NULL) {
// Parse the password, starting with "file:" or "pass:" can be parsed.
// Others cannot be parsed and an error is reported.
bool parsingMode = 1; // enable the parsing mode
if (GetPasswd(encOpt->passOptStr, parsingMode, encOpt->keySet->pass) != HITLS_APP_SUCCESS) {
AppPrintError("The password cannot be recognized. Enter '-pass file:filePath' or '-pass pass:passwd'.\n");
return HITLS_APP_PASSWD_FAIL;
}
} else {
AppPrintError("The password can contain the following characters:\n");
AppPrintError("a~z A~Z 0~9 ! \" # $ %% & ' ( ) * + , - . / : ; < = > ? @ [ \\ ] ^ _ ` { | } ~\n");
AppPrintError("The space is not supported.\n");
char buf[APP_MAX_PASS_LENGTH + 1] = {0};
uint32_t bufLen = APP_MAX_PASS_LENGTH + 1;
BSL_UI_ReadPwdParam param = {"passwd", NULL, true};
int32_t ret = BSL_UI_ReadPwdUtil(¶m, buf, &bufLen, HITLS_APP_DefaultPassCB, NULL);
if (ret == BSL_UI_READ_BUFF_TOO_LONG || ret == BSL_UI_READ_LEN_TOO_SHORT) {
HITLS_APP_PrintPassErrlog();
return HITLS_APP_PASSWD_FAIL;
}
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to read passwd from stdin.\n");
return HITLS_APP_PASSWD_FAIL;
}
bufLen -= 1;
buf[bufLen] = '\0';
bool parsingMode = 0; // close the parsing mode
if (GetPasswd(buf, parsingMode, encOpt->keySet->pass) != HITLS_APP_SUCCESS) {
(void)memset_s(buf, APP_MAX_PASS_LENGTH, 0, APP_MAX_PASS_LENGTH);
AppPrintError("The password cannot be recognized.Enter '-pass file:filePath' or '-pass pass:passwd'.\n");
return HITLS_APP_PASSWD_FAIL;
}
}
if (encOpt->keySet->pass == NULL) {
AppPrintError("Failed to get the passwd.\n");
return HITLS_APP_PASSWD_FAIL;
}
encOpt->keySet->passLen = strlen(encOpt->keySet->pass);
return HITLS_APP_SUCCESS;
}
static int32_t GenSaltAndIv(EncCmdOpt *encOpt)
{
// During encryption, salt and iv are randomly generated.
// use the random number API to generate the salt value
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default", NULL, 0, NULL) != CRYPT_SUCCESS ||
CRYPT_EAL_RandbytesEx(NULL, encOpt->keySet->salt, encOpt->keySet->saltLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to generate the salt value.\n");
return HITLS_APP_CRYPTO_FAIL;
}
// use the random number API to generate the iv value
if (encOpt->keySet->ivLen > 0) {
if (CRYPT_EAL_RandbytesEx(NULL, encOpt->keySet->iv, encOpt->keySet->ivLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to generate the iv value.\n");
return HITLS_APP_CRYPTO_FAIL;
}
}
CRYPT_EAL_RandDeinitEx(NULL);
return HITLS_APP_SUCCESS;
}
// The enc encryption mode writes information to the file header.
static int32_t WriteEncFileHeader(EncCmdOpt *encOpt)
{
char hexDataBuf[REC_HEX_BUF_LENGTH + 1] = {0}; // Hexadecimal Data Generic Buffer
// Write the version, derived algorithm ID, salt information, iteration times, and IV information to the output file
// (Convert the character string to hexadecimal and eliminate '\0' after the character string.)
// convert and write the version number
int32_t ret;
if ((ret = HexAndWrite(encOpt, encOpt->version, hexDataBuf)) != HITLS_APP_SUCCESS) {
return ret;
}
// convert and write the ID of the derived algorithm
if ((ret = HexAndWrite(encOpt, encOpt->cipherId, hexDataBuf)) != HITLS_APP_SUCCESS) {
return ret;
}
// convert and write the saltlen
if ((ret = HexAndWrite(encOpt, encOpt->keySet->saltLen, hexDataBuf)) != HITLS_APP_SUCCESS) {
return ret;
}
// convert and write the salt value
char hSaltBuf[REC_SALT_LEN * REC_DOUBLE + 1] = {0}; // Hexadecimal salt buffer
if (Str2HexStr(encOpt->keySet->salt, REC_HEX_BUF_LENGTH, hSaltBuf, sizeof(hSaltBuf)) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
uint32_t writeLen = 0;
if (BSL_UIO_Write(encOpt->encUio->wUio, hSaltBuf, REC_SALT_LEN * REC_DOUBLE, &writeLen) != BSL_SUCCESS ||
writeLen != REC_SALT_LEN * REC_DOUBLE) {
return HITLS_APP_UIO_FAIL;
}
// convert and write the iteration times
if ((ret = HexAndWrite(encOpt, encOpt->iter, hexDataBuf)) != HITLS_APP_SUCCESS) {
return ret;
}
if (encOpt->keySet->ivLen > 0) {
// convert and write the ivlen
if ((ret = HexAndWrite(encOpt, encOpt->keySet->ivLen, hexDataBuf)) != HITLS_APP_SUCCESS) {
return ret;
}
// convert and write the iv
char hIvBuf[REC_MAX_IV_LENGTH * REC_DOUBLE + 1] = {0}; // hexadecimal iv buffer
if (Str2HexStr(encOpt->keySet->iv, encOpt->keySet->ivLen, hIvBuf, sizeof(hIvBuf)) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
if (BSL_UIO_Write(encOpt->encUio->wUio, hIvBuf, encOpt->keySet->ivLen * REC_DOUBLE, &writeLen) != BSL_SUCCESS ||
writeLen != encOpt->keySet->ivLen * REC_DOUBLE) {
return HITLS_APP_UIO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t HandleDecFileIv(EncCmdOpt *encOpt)
{
char hexDataBuf[REC_HEX_BUF_LENGTH + 1] = {0}; // hexadecimal data buffer
uint32_t hexBufLen = sizeof(hexDataBuf);
int32_t ret = HITLS_APP_SUCCESS;
// Read the length of the IV, convert it into decimal, and store it.
uint32_t tmpIvLen = 0;
if ((ret = ReadAndDec(encOpt, hexDataBuf, hexBufLen, (int32_t*)&tmpIvLen)) != HITLS_APP_SUCCESS) {
return ret;
}
if (tmpIvLen != encOpt->keySet->ivLen) {
AppPrintError("Iv length is error, iv length read from file is %u.\n", tmpIvLen);
return HITLS_APP_INFO_CMP_FAIL;
}
// Read iv based on ivLen, convert it into a decimal character string, and store it.
uint32_t readLen = 0;
char hIvBuf[REC_MAX_IV_LENGTH * REC_DOUBLE + 1] = {0}; // Hexadecimal iv buffer
if (BSL_UIO_Read(encOpt->encUio->rUio, hIvBuf, encOpt->keySet->ivLen * REC_DOUBLE, &readLen) != BSL_SUCCESS ||
readLen != encOpt->keySet->ivLen * REC_DOUBLE) {
return HITLS_APP_UIO_FAIL;
}
if (HexToStr(hIvBuf, encOpt->keySet->iv) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
return ret;
}
// The ENC decryption mode parses the file header data and receives the ciphertext in the input file.
static int32_t HandleDecFileHeader(EncCmdOpt *encOpt)
{
char hexDataBuf[REC_HEX_BUF_LENGTH + 1] = {0}; // hexadecimal data buffer
uint32_t hexBufLen = sizeof(hexDataBuf);
// Read the version, derived algorithm ID, salt information, iteration times, and IV information from the input file
// convert them into decimal and store for later decryption.
// The read data is in hexadecimal format and needs to be converted to decimal format.
// Read the version number, convert it to decimal, and compare it.
int32_t ret = HITLS_APP_SUCCESS;
uint32_t rVersion = 0; // Version number in the ciphertext
if ((ret = ReadAndDec(encOpt, hexDataBuf, hexBufLen, (int32_t *)&rVersion)) != HITLS_APP_SUCCESS) {
return ret;
}
// Compare the file version input by the user with the current ENC version.
// If the file version does not match, an error is reported.
if (rVersion != encOpt->version) {
AppPrintError("Error version. The enc version is %u, the file version is %u.\n", encOpt->version, rVersion);
return HITLS_APP_INFO_CMP_FAIL;
}
// Read the derived algorithm in the ciphertext, convert it to decimal and compare.
int32_t rCipherId = -1; // Decimal cipherID read from the file
if ((ret = ReadAndDec(encOpt, hexDataBuf, hexBufLen, &rCipherId)) != HITLS_APP_SUCCESS) {
return ret;
}
// Compare the algorithm entered by the user from the command line with the algorithm read.
// If the algorithm is incorrect, an error is reported.
if (encOpt->cipherId != rCipherId) {
AppPrintError("Cipher ID is %d, cipher ID read from file is %d.\n", encOpt->cipherId, rCipherId);
return HITLS_APP_INFO_CMP_FAIL;
}
// Read the salt length in the ciphertext, convert the salt length into decimal, and store the salt length.
if ((ret = ReadAndDec(encOpt, hexDataBuf, hexBufLen, (int32_t *)&encOpt->keySet->saltLen)) != HITLS_APP_SUCCESS) {
return ret;
}
if (encOpt->keySet->saltLen != REC_SALT_LEN) {
AppPrintError("Salt length is error, Salt length read from file is %u.\n", encOpt->keySet->saltLen);
return HITLS_APP_INFO_CMP_FAIL;
}
// Read the salt value in the ciphertext, convert the salt value into a decimal string, and store the string.
uint32_t readLen = 0;
char hSaltBuf[REC_SALT_LEN * REC_DOUBLE + 1] = {0}; // Hexadecimal salt buffer
if (BSL_UIO_Read(encOpt->encUio->rUio, hSaltBuf, REC_SALT_LEN * REC_DOUBLE, &readLen) != BSL_SUCCESS ||
readLen != REC_SALT_LEN * REC_DOUBLE) {
return HITLS_APP_UIO_FAIL;
}
if (HexToStr(hSaltBuf, encOpt->keySet->salt) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
// Read the times of iteration, convert the number to decimal, and store the number.
if ((ret = ReadAndDec(encOpt, hexDataBuf, hexBufLen, (int32_t *)&encOpt->iter)) != HITLS_APP_SUCCESS) {
return ret;
}
if (encOpt->keySet->ivLen > 0) {
if ((ret = HandleDecFileIv(encOpt)) != HITLS_APP_SUCCESS) {
return ret;
}
}
return ret;
}
static int32_t DriveKey(EncCmdOpt *encOpt)
{
if (CRYPT_EAL_CipherGetInfo(encOpt->cipherId, CRYPT_INFO_KEY_LEN, &encOpt->keySet->dKeyLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_KdfNewCtx(CRYPT_KDF_PBKDF2);
if (ctx == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END};
(void)BSL_PARAM_InitValue(¶ms[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &encOpt->mdId,
sizeof(encOpt->mdId));
(void)BSL_PARAM_InitValue(¶ms[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS,
encOpt->keySet->pass, encOpt->keySet->passLen);
(void)BSL_PARAM_InitValue(¶ms[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS,
encOpt->keySet->salt, encOpt->keySet->saltLen);
(void)BSL_PARAM_InitValue(¶ms[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32,
&encOpt->iter, sizeof(encOpt->iter));
uint32_t ret = CRYPT_EAL_KdfSetParam(ctx, params);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_KdfFreeCtx(ctx);
return ret;
}
ret = CRYPT_EAL_KdfDerive(ctx, encOpt->keySet->dKey, encOpt->keySet->dKeyLen);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_KdfFreeCtx(ctx);
return ret;
}
// Delete sensitive information after the key is used.
CRYPT_EAL_KdfFreeCtx(ctx);
return BSL_SUCCESS;
}
static bool CipherIdIsValid(uint32_t id, const uint32_t *list, uint32_t num)
{
for (uint32_t i = 0; i < num; i++) {
if (id == list[i]) {
return true;
}
}
return false;
}
static bool IsBlockCipher(CRYPT_CIPHER_AlgId id)
{
if (CipherIdIsValid(id, CIPHER_IS_BlOCK, sizeof(CIPHER_IS_BlOCK) / sizeof(CIPHER_IS_BlOCK[0]))) {
return true;
}
return false;
}
static bool IsXtsCipher(CRYPT_CIPHER_AlgId id)
{
if (CipherIdIsValid(id, CIPHER_IS_XTS, sizeof(CIPHER_IS_XTS) / sizeof(CIPHER_IS_XTS[0]))) {
return true;
}
return false;
}
static int32_t XTSCipherUpdate(EncCmdOpt *encOpt, uint8_t *buf, uint32_t bufLen, uint8_t *res, uint32_t resLen)
{
uint32_t updateLen = bufLen;
if (CRYPT_EAL_CipherUpdate(encOpt->keySet->ctx, buf, bufLen, res, &updateLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to update the cipher.\n");
return HITLS_APP_CRYPTO_FAIL;
}
if (updateLen > resLen) {
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t writeLen = 0;
if (updateLen != 0 &&
(BSL_UIO_Write(encOpt->encUio->wUio, res, updateLen, &writeLen) != BSL_SUCCESS || writeLen != updateLen)) {
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t StreamCipherUpdate(EncCmdOpt *encOpt, uint8_t *readBuf, uint32_t readLen, uint8_t *resBuf,
uint32_t resLen)
{
uint32_t updateLen = 0;
uint32_t hBuffLen = readLen + encOpt->keySet->blockSize;
uint32_t blockNum = readLen / encOpt->keySet->blockSize;
uint32_t remainLen = readLen % encOpt->keySet->blockSize;
for (uint32_t i = 0; i < blockNum; ++i) {
hBuffLen = readLen + encOpt->keySet->blockSize - i * encOpt->keySet->blockSize;
if (CRYPT_EAL_CipherUpdate(encOpt->keySet->ctx, readBuf + (i * encOpt->keySet->blockSize),
encOpt->keySet->blockSize, resBuf + (i * encOpt->keySet->blockSize), &hBuffLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to update the cipher.\n");
return HITLS_APP_CRYPTO_FAIL;
}
updateLen += hBuffLen;
}
if (remainLen > 0) {
hBuffLen = readLen + encOpt->keySet->blockSize - updateLen;
if (CRYPT_EAL_CipherUpdate(encOpt->keySet->ctx, readBuf + updateLen, remainLen,
resBuf + updateLen, &hBuffLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to update the cipher.\n");
return HITLS_APP_CRYPTO_FAIL;
}
updateLen += hBuffLen;
}
if (updateLen > resLen) {
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t writeLen = 0;
if (updateLen != 0 &&
(BSL_UIO_Write(encOpt->encUio->wUio, resBuf, updateLen, &writeLen) != BSL_SUCCESS || writeLen != updateLen)) {
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t UpdateEncStdinEnd(EncCmdOpt *encOpt, uint8_t *cache, uint32_t cacheLen, uint8_t *resBuf, uint32_t resLen)
{
if (IsXtsCipher(encOpt->cipherId)) {
if (cacheLen < XTS_MIN_DATALEN) {
AppPrintError("The XTS algorithm does not support data less than 16 bytes.\n");
return HITLS_APP_CRYPTO_FAIL;
}
return XTSCipherUpdate(encOpt, cache, cacheLen, resBuf, resLen);
} else {
return StreamCipherUpdate(encOpt, cache, cacheLen, resBuf, resLen);
}
}
static int32_t UpdateEncStdin(EncCmdOpt *encOpt)
{
// now readFileLen == 0
int32_t ret = HITLS_APP_SUCCESS;
// Because the standard input is read in each 4K, the data required by the XTS update cannot be less than 16.
// Therefore, the remaining data cannot be less than 16 bytes. The buffer behavior is required.
// In the common buffer logic, the remaining data may be less than 16. As a result, the XTS algorithm update fails.
// Set the cacheArea, the size is maximum data length of each row (4 KB) plus the readable block size (32 bytes).
// If the length of the read data exceeds 32 bytes, the length of the last 16-byte secure block is reserved,
// the rest of the data is updated to avoid the failure of updating the rest and tail data.
uint8_t cacheArea[MAX_BUFSIZE + BUF_READABLE_BLOCK] = {0};
uint32_t cacheLen = 0;
uint8_t readBuf[MAX_BUFSIZE] = {0};
uint8_t resBuf[MAX_BUFSIZE + BUF_READABLE_BLOCK] = {0};
uint32_t readLen = MAX_BUFSIZE;
bool isEof = false;
while (BSL_UIO_Ctrl(encOpt->encUio->rUio, BSL_UIO_FILE_GET_EOF, IS_SUPPORT_GET_EOF, &isEof) == BSL_SUCCESS) {
readLen = MAX_BUFSIZE;
if (isEof) {
// End stdin. Update the remaining data. If the remaining data size is 16 ≤ dataLen < 32, the XTS is valid.
ret = UpdateEncStdinEnd(encOpt, cacheArea, cacheLen, resBuf, sizeof(resBuf));
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
break;
}
if (BSL_UIO_Read(encOpt->encUio->rUio, readBuf, MAX_BUFSIZE, &readLen) != BSL_SUCCESS) {
(void)AppPrintError("Failed to obtain the content from the STDIN\n");
return HITLS_APP_UIO_FAIL;
}
if (readLen == 0) {
AppPrintError("Failed to read the input content\n");
return HITLS_APP_STDIN_FAIL;
}
if (memcpy_s(cacheArea + cacheLen, MAX_BUFSIZE + BUF_READABLE_BLOCK - cacheLen, readBuf, readLen) != EOK) {
return HITLS_APP_COPY_ARGS_FAILED;
}
cacheLen += readLen;
if (cacheLen < BUF_READABLE_BLOCK) {
continue;
}
uint32_t readableLen = cacheLen - BUF_SAFE_BLOCK;
if (IsXtsCipher(encOpt->cipherId)) {
ret = XTSCipherUpdate(encOpt, cacheArea, readableLen, resBuf, sizeof(resBuf));
} else {
ret = StreamCipherUpdate(encOpt, cacheArea, readableLen, resBuf, sizeof(resBuf));
}
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// Place the secure block data in the cacheArea at the top and reset cacheLen.
if (memcpy_s(cacheArea, sizeof(cacheArea) - BUF_SAFE_BLOCK, cacheArea + readableLen, BUF_SAFE_BLOCK) != EOK) {
return HITLS_APP_COPY_ARGS_FAILED;
}
cacheLen = BUF_SAFE_BLOCK;
}
return HITLS_APP_SUCCESS;
}
static int32_t UpdateEncFile(EncCmdOpt *encOpt, uint64_t readFileLen)
{
if (readFileLen < XTS_MIN_DATALEN && IsXtsCipher(encOpt->cipherId)) {
AppPrintError("The XTS algorithm does not support data less than 16 bytes.\n");
return HITLS_APP_CRYPTO_FAIL;
}
// now readFileLen != 0
int32_t ret = HITLS_APP_SUCCESS;
uint8_t readBuf[MAX_BUFSIZE * REC_DOUBLE] = {0};
uint8_t resBuf[MAX_BUFSIZE * REC_DOUBLE] = {0};
uint32_t readLen = MAX_BUFSIZE * REC_DOUBLE;
uint32_t bufLen = MAX_BUFSIZE * REC_DOUBLE;
while (readFileLen > 0) {
if (readFileLen < MAX_BUFSIZE * REC_DOUBLE) {
bufLen = readFileLen;
readLen = readFileLen;
}
if (readFileLen >= MAX_BUFSIZE * REC_DOUBLE) {
bufLen = MAX_BUFSIZE;
readLen = MAX_BUFSIZE;
}
if (!IsXtsCipher(encOpt->cipherId)) {
bufLen = (readFileLen > MAX_BUFSIZE) ? MAX_BUFSIZE : readFileLen;
readLen = bufLen;
}
if (BSL_UIO_Read(encOpt->encUio->rUio, readBuf, bufLen, &readLen) != BSL_SUCCESS || bufLen != readLen) {
AppPrintError("Failed to read the input content\n");
return HITLS_APP_UIO_FAIL;
}
readFileLen -= readLen;
if (IsXtsCipher(encOpt->cipherId)) {
ret = XTSCipherUpdate(encOpt, readBuf, readLen, resBuf, sizeof(resBuf));
} else {
ret = StreamCipherUpdate(encOpt, readBuf, readLen, resBuf, sizeof(resBuf));
}
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t DoCipherUpdateEnc(EncCmdOpt *encOpt, uint64_t readFileLen)
{
int32_t updateRet = HITLS_APP_SUCCESS;
if (readFileLen > 0) {
updateRet = UpdateEncFile(encOpt, readFileLen);
} else {
updateRet = UpdateEncStdin(encOpt);
}
if (updateRet != HITLS_APP_SUCCESS) {
return updateRet;
}
return HITLS_APP_SUCCESS;
}
static int32_t DoCipherUpdateDec(EncCmdOpt *encOpt, uint64_t readFileLen)
{
if (readFileLen == 0 && encOpt->inFile == NULL) {
AppPrintError("In decryption mode, the standard input cannot be used to obtain the ciphertext.\n");
return HITLS_APP_STDIN_FAIL;
}
if (readFileLen < XTS_MIN_DATALEN && IsXtsCipher(encOpt->cipherId)) {
AppPrintError("The XTS algorithm does not support ciphertext less than 16 bytes.\n");
return HITLS_APP_CRYPTO_FAIL;
}
// now readFileLen != 0
uint8_t readBuf[MAX_BUFSIZE * REC_DOUBLE] = {0};
uint8_t resBuf[MAX_BUFSIZE * REC_DOUBLE] = {0};
uint32_t readLen = MAX_BUFSIZE * REC_DOUBLE;
uint32_t bufLen = MAX_BUFSIZE * REC_DOUBLE;
while (readFileLen > 0) {
if (readFileLen < MAX_BUFSIZE * REC_DOUBLE) {
bufLen = readFileLen;
}
if (readFileLen >= MAX_BUFSIZE * REC_DOUBLE) {
bufLen = MAX_BUFSIZE;
}
if (!IsXtsCipher(encOpt->cipherId)) {
bufLen = (readFileLen >= MAX_BUFSIZE) ? MAX_BUFSIZE : readFileLen;
}
readLen = 0;
if (BSL_UIO_Read(encOpt->encUio->rUio, readBuf, bufLen, &readLen) != BSL_SUCCESS || bufLen != readLen) {
AppPrintError("Failed to read the input content\n");
return HITLS_APP_UIO_FAIL;
}
readFileLen -= readLen;
uint32_t updateLen = readLen + encOpt->keySet->blockSize;
if (CRYPT_EAL_CipherUpdate(encOpt->keySet->ctx, readBuf, readLen, resBuf, &updateLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to update the cipher.\n");
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t writeLen = 0;
if (updateLen != 0 &&
(BSL_UIO_Write(encOpt->encUio->wUio, resBuf, updateLen, &writeLen) != BSL_SUCCESS ||
writeLen != updateLen)) {
AppPrintError("Failed to write the cipher text.\n");
return HITLS_APP_UIO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t DoCipherUpdate(EncCmdOpt *encOpt)
{
const uint32_t AES_BLOCK_SIZE = 16;
encOpt->keySet->blockSize = AES_BLOCK_SIZE;
uint64_t readFileLen = 0;
if (encOpt->inFile != NULL &&
BSL_UIO_Ctrl(encOpt->encUio->rUio, BSL_UIO_PENDING, sizeof(readFileLen), &readFileLen) != BSL_SUCCESS) {
(void)AppPrintError("Failed to obtain the content length\n");
return HITLS_APP_UIO_FAIL;
}
if (encOpt->inFile == NULL) {
AppPrintError("You have not entered the -in option. Please directly enter the file content on the terminal.\n");
}
int32_t updateRet = (encOpt->encTag == 0) ? DoCipherUpdateDec(encOpt, readFileLen)
: DoCipherUpdateEnc(encOpt, readFileLen);
if (updateRet != HITLS_APP_SUCCESS) {
return updateRet;
}
// The Aead algorithm does not perform final processing.
uint32_t isAeadId = 0;
if (CRYPT_EAL_CipherGetInfo(encOpt->cipherId, CRYPT_INFO_IS_AEAD, &isAeadId) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (isAeadId == 1) {
return HITLS_APP_SUCCESS;
}
uint32_t finLen = AES_BLOCK_SIZE;
uint8_t resBuf[MAX_BUFSIZE] = {0};
// Fill the data whose size is less than the block size and output the crypted data.
if (CRYPT_EAL_CipherFinal(encOpt->keySet->ctx, resBuf, &finLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to final the cipher.\n");
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t writeLen = 0;
if (finLen != 0 && (BSL_UIO_Write(encOpt->encUio->wUio, resBuf, finLen, &writeLen) != BSL_SUCCESS ||
writeLen != finLen)) {
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
// Enc encryption or decryption process
static int32_t EncOrDecProc(EncCmdOpt *encOpt)
{
if (DriveKey(encOpt) != BSL_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
// Create a cipher context.
encOpt->keySet->ctx = CRYPT_EAL_ProviderCipherNewCtx(NULL, encOpt->cipherId, "provider=default");
if (encOpt->keySet->ctx == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
// Initialize the symmetric encryption and decryption handle.
if (CRYPT_EAL_CipherInit(encOpt->keySet->ctx, encOpt->keySet->dKey, encOpt->keySet->dKeyLen, encOpt->keySet->iv,
encOpt->keySet->ivLen, encOpt->encTag) != CRYPT_SUCCESS) {
AppPrintError("Failed to init the cipher.\n");
(void)memset_s(encOpt->keySet->dKey, encOpt->keySet->dKeyLen, 0, encOpt->keySet->dKeyLen);
return HITLS_APP_CRYPTO_FAIL;
}
(void)memset_s(encOpt->keySet->dKey, encOpt->keySet->dKeyLen, 0, encOpt->keySet->dKeyLen);
if (IsBlockCipher(encOpt->cipherId)) {
if (CRYPT_EAL_CipherSetPadding(encOpt->keySet->ctx, CRYPT_PADDING_PKCS7) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
int32_t ret = HITLS_APP_SUCCESS;
if (encOpt->encTag == 1) {
if ((ret = WriteEncFileHeader(encOpt)) != HITLS_APP_SUCCESS) {
return ret;
}
}
if ((ret = DoCipherUpdate(encOpt)) != HITLS_APP_SUCCESS) {
return ret;
}
return HITLS_APP_SUCCESS;
}
// enc main function
int32_t HITLS_EncMain(int argc, char *argv[])
{
int32_t encRet = -1; // return value of enc
EncKeyParam keySet = {NULL, 0, NULL, 0, NULL, 0, NULL, 0, NULL, 0};
EncUio encUio = {NULL, NULL};
EncCmdOpt encOpt = {1, NULL, NULL, NULL, -1, -1, -1, 0, &keySet, &encUio};
if ((encRet = HITLS_APP_OptBegin(argc, argv, g_encOpts)) != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
goto End;
}
// Process of receiving the lower-level option of the ENC.
if ((encRet = HandleOpt(&encOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
// Check the validity of the lower-level option receiving parameter.
if ((encRet = CheckParam(&encOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
if ((encRet = HandleIO(&encOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
if ((encRet = ApplyForSpace(&encOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
if ((encRet = HandlePasswd(&encOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
// The ciphertext format is
// [g_version:uint32][derived algID:uint32][saltlen:uint32][salt][iter times:uint32][ivlen:uint32][iv][ciphertext]
// If the user identifier is encrypted
if (encOpt.encTag == 1) {
// Random salt and IV are generated in encryption mode.
if ((encRet = GenSaltAndIv(&encOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
}
// If the user identifier is decrypted
if (encOpt.encTag == 0) {
// Decryption mode: Parse the file header data and receive the ciphertext in the input file.
if ((encRet = HandleDecFileHeader(&encOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
}
// Final encryption or decryption process
if ((encRet = EncOrDecProc(&encOpt)) != HITLS_APP_SUCCESS) {
goto End;
}
encRet = HITLS_APP_SUCCESS;
End:
FreeEnc(&encOpt);
return encRet;
}
static int32_t GetCipherId(const char *name)
{
for (size_t i = 0; i < sizeof(g_cIdList) / sizeof(g_cIdList[0]); i++) {
if (strcmp(g_cIdList[i].cipherAlgName, name) == 0) {
return g_cIdList[i].cipherId;
}
}
PrintCipherAlgList();
return -1;
}
static int32_t GetHMacId(const char *mdName)
{
for (size_t i = 0; i < sizeof(g_mIdList) / sizeof(g_mIdList[0]); i++) {
if (strcmp(g_mIdList[i].macAlgName, mdName) == 0) {
return g_mIdList[i].macId;
}
}
PrintHMacAlgList();
return -1;
}
static void PrintHMacAlgList(void)
{
AppPrintError("The current version supports only the following digest algorithms:\n");
for (size_t i = 0; i < sizeof(g_mIdList) / sizeof(g_mIdList[0]); i++) {
AppPrintError("%-19s", g_mIdList[i].macAlgName);
// 4 algorithm names are displayed in each row
if ((i + 1) % 4 == 0 && i != sizeof(g_mIdList) - 1) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return;
}
static void PrintCipherAlgList(void)
{
AppPrintError("The current version supports only the following cipher algorithms:\n");
for (size_t i = 0; i < sizeof(g_cIdList) / sizeof(g_cIdList[0]); i++) {
AppPrintError("%-19s", g_cIdList[i].cipherAlgName);
// 4 algorithm names are displayed in each row
if ((i + 1) % 4 == 0 && i != sizeof(g_cIdList) - 1) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return;
}
static int32_t GetPasswd(const char *arg, bool mode, char *resPass)
{
const char filePrefix[] = "file:"; // Prefix of the file path
const char passPrefix[] = "pass:"; // Prefix of password form
if (mode) {
// Parsing mode. The prefix needs to be parsed. The parseable format starts with "file:" or "pass:".
// Other parameters cannot be parsed and an error is returned.
// Apply for a new memory and copy the unprocessed character string.
char tmpPassArg[APP_MAX_PASS_LENGTH * REC_DOUBLE] = {0};
if (strlen(arg) < APP_MIN_PASS_LENGTH ||
strcpy_s(tmpPassArg, sizeof(tmpPassArg) - 1, arg) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
if (strncmp(tmpPassArg, filePrefix, REC_MIN_PRE_LENGTH - 1) == 0) {
// In this case, the password mode is read from the file.
int32_t res;
if ((res = GetPwdFromFile(tmpPassArg, resPass)) != HITLS_APP_SUCCESS) {
AppPrintError("Failed to obtain the password from the file.\n");
return res;
}
} else if (strncmp(tmpPassArg, passPrefix, REC_MIN_PRE_LENGTH - 1) == 0) {
// In this case, the password mode is read from the user input.
// Obtain the password after the ':'.
char *context = NULL;
char *tmpPass = strtok_s(tmpPassArg, ":", &context);
tmpPass = strtok_s(NULL, ":", &context);
if (tmpPass == NULL) {
return HITLS_APP_SECUREC_FAIL;
}
// Check whether the password is correct. Unsupported characters are not allowed.
if (CheckPasswd(tmpPass) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
if (memcpy_s(resPass, APP_MAX_PASS_LENGTH, tmpPass, strlen(tmpPass)) != EOK) {
return HITLS_APP_COPY_ARGS_FAILED;
}
} else {
// The prefix format is invalid. An error is returned.
AppPrintError("Invalid prefix format.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
} else {
// In non-parse mode, the format is directly determined.
// The value can be 1 byte ≤ password ≤ 1024 bytes, and only specified characters are supported.
// If the operation is successful, the password is received. If the operation fails, an error is returned.
if (CheckPasswd(arg) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
if (memcpy_s(resPass, APP_MAX_PASS_LENGTH, arg, strlen(arg)) != EOK) {
return HITLS_APP_COPY_ARGS_FAILED;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t GetPwdFromFile(const char *fileArg, char *tmpPass)
{
// Apply for a new memory and copy the unprocessed character string.
char tmpFileArg[REC_MAX_FILENAME_LENGTH + REC_MIN_PRE_LENGTH + 1] = {0};
if (strcpy_s(tmpFileArg, REC_MAX_FILENAME_LENGTH + REC_MIN_PRE_LENGTH, fileArg) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
// Obtain the file path after the ':'.
char *filePath = NULL;
char *context = NULL;
filePath = strtok_s(tmpFileArg, ":", &context);
filePath = strtok_s(NULL, ":", &context);
if (filePath == NULL) {
return HITLS_APP_SECUREC_FAIL;
}
// Bind the password file UIO.
BSL_UIO *passUio = BSL_UIO_New(BSL_UIO_FileMethod());
char tmpPassBuf[APP_MAX_PASS_LENGTH * REC_DOUBLE] = {0};
if (BSL_UIO_Ctrl(passUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_READ, filePath) != BSL_SUCCESS) {
AppPrintError("Failed to set infile mode for passwd.\n");
BSL_UIO_SetIsUnderlyingClosedByUio(passUio, true);
BSL_UIO_Free(passUio);
return HITLS_APP_UIO_FAIL;
}
uint32_t rPassLen = 0;
if (BSL_UIO_Read(passUio, tmpPassBuf, sizeof(tmpPassBuf), &rPassLen) != BSL_SUCCESS || rPassLen <= 0) {
AppPrintError("Failed to read passwd from file.\n");
BSL_UIO_SetIsUnderlyingClosedByUio(passUio, true);
BSL_UIO_Free(passUio);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(passUio, true);
BSL_UIO_Free(passUio);
if (tmpPassBuf[rPassLen - 1] == '\n') {
tmpPassBuf[rPassLen - 1] = '\0';
rPassLen -= 1;
}
if (rPassLen > APP_MAX_PASS_LENGTH) {
HITLS_APP_PrintPassErrlog();
return HITLS_APP_PASSWD_FAIL;
}
// Check whether the password is correct. Unsupported characters are not allowed.
if (HITLS_APP_CheckPasswd((uint8_t *)tmpPassBuf, rPassLen) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
if (memcpy_s(tmpPass, APP_MAX_PASS_LENGTH, tmpPassBuf, strlen(tmpPassBuf)) != EOK) {
return HITLS_APP_COPY_ARGS_FAILED;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckPasswd(const char *passwd)
{
// Check the key length. The key length must be greater than or equal to 1 byte and less than or equal to 1024
// bytes.
int32_t passLen = strlen(passwd);
if (passLen > APP_MAX_PASS_LENGTH) {
HITLS_APP_PrintPassErrlog();
return HITLS_APP_PASSWD_FAIL;
}
return HITLS_APP_CheckPasswd((const uint8_t *)passwd, (uint32_t)passLen);
}
static int32_t Str2HexStr(const unsigned char *buf, uint32_t bufLen, char *hexBuf, uint32_t hexBufLen)
{
if (hexBufLen < bufLen * REC_DOUBLE + 1) {
return HITLS_APP_INVALID_ARG;
}
for (uint32_t i = 0; i < bufLen; i++) {
if (sprintf_s(hexBuf + i * REC_DOUBLE, bufLen * REC_DOUBLE + 1, "%02x", buf[i]) == -1) {
AppPrintError("BSL_SAL_Calloc Failed.\n");
return HITLS_APP_ENCODE_FAIL;
}
}
hexBuf[bufLen * REC_DOUBLE] = '\0';
return HITLS_APP_SUCCESS;
}
static int32_t HexToStr(const char *hexBuf, unsigned char *buf)
{
// Convert hexadecimal character string data into ASCII character data.
int len = strlen(hexBuf) / 2;
for (int i = 0; i < len; i++) {
uint32_t val;
if (sscanf_s(hexBuf + i * REC_DOUBLE, "%2x", &val) == -1) {
AppPrintError("error in converting hex str to str.\n");
return HITLS_APP_ENCODE_FAIL;
}
buf[i] = (unsigned char)val;
}
return HITLS_APP_SUCCESS;
}
static int32_t Int2Hex(uint32_t num, char *hexBuf)
{
int ret = snprintf_s(hexBuf, REC_HEX_BUF_LENGTH + 1, REC_HEX_BUF_LENGTH, "%08X", num);
if (strlen(hexBuf) != REC_HEX_BUF_LENGTH || ret == -1) {
AppPrintError("error in uint to hex.\n");
return HITLS_APP_ENCODE_FAIL;
}
return HITLS_APP_SUCCESS;
}
static uint32_t Hex2Uint(char *hexBuf, int32_t *num)
{
if (hexBuf == NULL) {
AppPrintError("No hex buffer here.\n");
return HITLS_APP_INVALID_ARG;
}
char *endptr = NULL;
*num = strtoul(hexBuf, &endptr, REC_HEX_BASE);
return HITLS_APP_SUCCESS;
}
static int32_t HexAndWrite(EncCmdOpt *encOpt, uint32_t decData, char *buf)
{
uint32_t writeLen = 0;
if (Int2Hex(decData, buf) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
if (BSL_UIO_Write(encOpt->encUio->wUio, buf, REC_HEX_BUF_LENGTH, &writeLen) != BSL_SUCCESS ||
writeLen != REC_HEX_BUF_LENGTH) {
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t ReadAndDec(EncCmdOpt *encOpt, char *hexBuf, uint32_t hexBufLen, int32_t *decData)
{
if (hexBufLen < REC_HEX_BUF_LENGTH + 1) {
return HITLS_APP_INVALID_ARG;
}
uint32_t readLen = 0;
if (BSL_UIO_Read(encOpt->encUio->rUio, hexBuf, REC_HEX_BUF_LENGTH, &readLen) != BSL_SUCCESS ||
readLen != REC_HEX_BUF_LENGTH) {
return HITLS_APP_UIO_FAIL;
}
if (Hex2Uint(hexBuf, decData) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
return HITLS_APP_SUCCESS;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_enc.c | C | unknown | 49,952 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_function.h"
#include <string.h>
#include <stddef.h>
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_rand.h"
#include "app_enc.h"
#include "app_pkcs12.h"
#include "app_x509.h"
#include "app_list.h"
#include "app_rsa.h"
#include "app_dgst.h"
#include "app_crl.h"
#include "app_genrsa.h"
#include "app_verify.h"
#include "app_passwd.h"
#include "app_pkey.h"
#include "app_genpkey.h"
#include "app_req.h"
#include "app_mac.h"
#include "app_kdf.h"
HITLS_CmdFunc g_cmdFunc[] = {
{"help", FUNC_TYPE_GENERAL, HITLS_HelpMain},
{"rand", FUNC_TYPE_GENERAL, HITLS_RandMain},
{"enc", FUNC_TYPE_GENERAL, HITLS_EncMain},
{"pkcs12", FUNC_TYPE_GENERAL, HITLS_PKCS12Main},
{"rsa", FUNC_TYPE_GENERAL, HITLS_RsaMain},
{"x509", FUNC_TYPE_GENERAL, HITLS_X509Main},
{"list", FUNC_TYPE_GENERAL, HITLS_ListMain},
{"dgst", FUNC_TYPE_GENERAL, HITLS_DgstMain},
{"crl", FUNC_TYPE_GENERAL, HITLS_CrlMain},
{"genrsa", FUNC_TYPE_GENERAL, HITLS_GenRSAMain},
{"verify", FUNC_TYPE_GENERAL, HITLS_VerifyMain},
{"passwd", FUNC_TYPE_GENERAL, HITLS_PasswdMain},
{"pkey", FUNC_TYPE_GENERAL, HITLS_PkeyMain},
{"genpkey", FUNC_TYPE_GENERAL, HITLS_GenPkeyMain},
{"req", FUNC_TYPE_GENERAL, HITLS_ReqMain},
{"mac", FUNC_TYPE_GENERAL, HITLS_MacMain},
{"kdf", FUNC_TYPE_GENERAL, HITLS_KdfMain},
{NULL, FUNC_TYPE_NONE, NULL}
};
static void AppGetFuncPrintfLen(size_t *maxLen)
{
size_t len = 0;
for (size_t i = 0; g_cmdFunc[i].name != NULL; i++) {
len = (len > strlen(g_cmdFunc[i].name)) ? len : strlen(g_cmdFunc[i].name);
}
*maxLen = len + 5; // The relative maximum length is filled with 5 spaces.
}
void AppPrintFuncList(void)
{
AppPrintError("HiTLS supports the following commands:\n");
size_t maxLen = 0;
AppGetFuncPrintfLen(&maxLen);
for (size_t i = 0; g_cmdFunc[i].name != NULL; i++) {
if (((i % 4) == 0) && (i != 0)) { // Print 4 functions in one line
AppPrintError("\n");
}
AppPrintError("%-*s", maxLen, g_cmdFunc[i].name);
}
AppPrintError("\n");
}
int AppGetProgFunc(const char *proName, HITLS_CmdFunc *func)
{
for (size_t i = 0; g_cmdFunc[i].name != NULL; i++) {
if (strcmp(proName, g_cmdFunc[i].name) == 0) {
func->type = g_cmdFunc[i].type;
func->main = g_cmdFunc[i].main;
break;
}
}
if (func->main == NULL) {
AppPrintError("Can not find the function : %s. ", proName);
return HITLS_APP_OPT_NAME_INVALID;
}
return HITLS_APP_SUCCESS;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_function.c | C | unknown | 3,240 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_genpkey.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <securec.h>
#include <linux/limits.h>
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_list.h"
#include "app_utils.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_rand.h"
#define RSA_KEYGEN_BITS_STR "rsa_keygen_bits:"
#define EC_PARAMGEN_CURVE_STR "ec_paramgen_curve:"
#define RSA_KEYGEN_BITS_STR_LEN ((int)(sizeof(RSA_KEYGEN_BITS_STR) - 1))
#define EC_PARAMGEN_CURVE_LEN ((int)(sizeof(EC_PARAMGEN_CURVE_STR) - 1))
#define MAX_PKEY_OPT_ARG 10U
#define DEFAULT_RSA_KEYGEN_BITS 2048U
typedef enum {
HITLS_APP_OPT_ALGORITHM = 2,
HITLS_APP_OPT_PKEYOPT,
HITLS_APP_OPT_CIPHER_ALG,
HITLS_APP_OPT_PASS,
HITLS_APP_OPT_OUT,
} HITLSOptType;
const HITLS_CmdOption g_genPkeyOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"algorithm", HITLS_APP_OPT_ALGORITHM, HITLS_APP_OPT_VALUETYPE_STRING, "Key algorithm"},
{"pkeyopt", HITLS_APP_OPT_PKEYOPT, HITLS_APP_OPT_VALUETYPE_STRING, "Set key options"},
{"", HITLS_APP_OPT_CIPHER_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Any supported cipher"},
{"pass", HITLS_APP_OPT_PASS, HITLS_APP_OPT_VALUETYPE_STRING, "Output file pass phrase source"},
{"out", HITLS_APP_OPT_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{NULL},
};
typedef struct {
char *algorithm;
char *pkeyOptArg[MAX_PKEY_OPT_ARG];
uint32_t pkeyOptArgNum;
} InputGenKeyPara;
typedef struct {
char *outFilePath;
char *passOutArg;
} OutPutGenKeyPara;
typedef struct {
uint32_t bits;
uint32_t pkeyParaId;
} GenPkeyOptPara;
typedef CRYPT_EAL_PkeyCtx *(*GenPkeyCtxFunc)(const GenPkeyOptPara *);
typedef struct {
CRYPT_EAL_PkeyCtx *pkey;
GenPkeyCtxFunc genPkeyCtxFunc;
GenPkeyOptPara genPkeyOptPara;
char *passout;
int32_t cipherAlgCid;
InputGenKeyPara inPara;
OutPutGenKeyPara outPara;
} GenPkeyOptCtx;
typedef int32_t (*GenPkeyOptHandleFunc)(GenPkeyOptCtx *);
typedef struct {
int optType;
GenPkeyOptHandleFunc func;
} GenPkeyOptHandleTable;
static int32_t GenPkeyOptErr(GenPkeyOptCtx *optCtx)
{
(void)optCtx;
AppPrintError("genpkey: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t GenPkeyOptHelp(GenPkeyOptCtx *optCtx)
{
(void)optCtx;
HITLS_APP_OptHelpPrint(g_genPkeyOpts);
return HITLS_APP_HELP;
}
static CRYPT_EAL_PkeyCtx *GenRsaPkeyCtx(const GenPkeyOptPara *optPara)
{
return HITLS_APP_GenRsaPkeyCtx(optPara->bits);
}
static CRYPT_EAL_PkeyCtx *GenEcPkeyCtx(const GenPkeyOptPara *optPara)
{
CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_ECDSA,
CRYPT_EAL_PKEY_UNKNOWN_OPERATE, "provider=default");
if (pkey == NULL) {
AppPrintError("genpkey: Failed to initialize the EC private key.\n");
return NULL;
}
if (CRYPT_EAL_PkeySetParaById(pkey, optPara->pkeyParaId) != CRYPT_SUCCESS) {
AppPrintError("genpkey: Failed to set EC parameters.\n");
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
if (CRYPT_EAL_PkeyGen(pkey) != CRYPT_SUCCESS) {
AppPrintError("genpkey: Failed to generate the EC private key.\n");
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
return pkey;
}
static int32_t GetRsaKeygenBits(const char *algorithm, const char *pkeyOptArg, uint32_t *bits)
{
uint32_t numBits = 0;
if ((strcasecmp(algorithm, "RSA") != 0) || (strlen(pkeyOptArg) <= RSA_KEYGEN_BITS_STR_LEN) ||
(HITLS_APP_OptGetUint32(pkeyOptArg + RSA_KEYGEN_BITS_STR_LEN, &numBits) != HITLS_APP_SUCCESS)) {
(void)AppPrintError("genpkey: The %s algorithm parameter %s is incorrect.\n", algorithm, pkeyOptArg);
return HITLS_APP_INVALID_ARG;
}
static const uint32_t numBitsArray[] = {1024, 2048, 3072, 4096};
for (size_t i = 0; i < sizeof(numBitsArray) / sizeof(numBitsArray[0]); i++) {
if (numBits == numBitsArray[i]) {
*bits = numBits;
return HITLS_APP_SUCCESS;
}
}
AppPrintError("genpkey: The RSA key length is error, supporting 1024、2048、3072、4096.\n");
return HITLS_APP_INVALID_ARG;
}
static int32_t GetParamGenCurve(const char *algorithm, const char *pkeyOptArg, uint32_t *pkeyParaId)
{
if ((strcasecmp(algorithm, "EC") != 0) || (strlen(pkeyOptArg) <= EC_PARAMGEN_CURVE_LEN)) {
(void)AppPrintError("genpkey: The %s algorithm parameter %s is incorrect.\n", algorithm, pkeyOptArg);
return HITLS_APP_INVALID_ARG;
}
const char *curesName = pkeyOptArg + EC_PARAMGEN_CURVE_LEN;
int32_t cid = HITLS_APP_GetCidByName(curesName, HITLS_APP_LIST_OPT_CURVES);
if (cid == CRYPT_PKEY_PARAID_MAX) {
(void)AppPrintError("genpkey: The %s algorithm parameter %s is incorrect, Use the [list -all-curves] command "
"to view supported curves.\n",
algorithm, pkeyOptArg);
return HITLS_APP_INVALID_ARG;
}
*pkeyParaId = cid;
return HITLS_APP_SUCCESS;
}
static int32_t SetPkeyPara(GenPkeyOptCtx *optCtx)
{
if (optCtx->genPkeyCtxFunc == NULL) {
(void)AppPrintError("genpkey: Algorithm not specified.\n");
return HITLS_APP_INVALID_ARG;
}
for (uint32_t i = 0; i < optCtx->inPara.pkeyOptArgNum; ++i) {
if (optCtx->inPara.pkeyOptArg[i] == NULL) {
return HITLS_APP_INVALID_ARG;
}
char *algorithm = optCtx->inPara.algorithm;
char *pkeyOptArg = optCtx->inPara.pkeyOptArg[i];
// rsa_keygen_bits:numbits
if (strncmp(pkeyOptArg, RSA_KEYGEN_BITS_STR, RSA_KEYGEN_BITS_STR_LEN) == 0) {
return GetRsaKeygenBits(algorithm, pkeyOptArg, &optCtx->genPkeyOptPara.bits);
} else if (strncmp(pkeyOptArg, EC_PARAMGEN_CURVE_STR, EC_PARAMGEN_CURVE_LEN) == 0) {
// ec_paramgen_curve:curve
return GetParamGenCurve(algorithm, pkeyOptArg, &optCtx->genPkeyOptPara.pkeyParaId);
} else {
(void)AppPrintError("genpkey: The %s algorithm parameter %s is incorrect.\n", algorithm, pkeyOptArg);
return HITLS_APP_INVALID_ARG;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t GenPkeyOptAlgorithm(GenPkeyOptCtx *optCtx)
{
optCtx->inPara.algorithm = HITLS_APP_OptGetValueStr();
if (strcasecmp(optCtx->inPara.algorithm, "RSA") == 0) {
optCtx->genPkeyCtxFunc = GenRsaPkeyCtx;
} else if (strcasecmp(optCtx->inPara.algorithm, "EC") == 0) {
optCtx->genPkeyCtxFunc = GenEcPkeyCtx;
} else {
(void)AppPrintError("genpkey: The %s algorithm is not supported.\n", optCtx->inPara.algorithm);
return HITLS_APP_INVALID_ARG;
}
return HITLS_APP_SUCCESS;
}
static int32_t GenPkeyOpt(GenPkeyOptCtx *optCtx)
{
if (optCtx->inPara.pkeyOptArgNum >= MAX_PKEY_OPT_ARG) {
return HITLS_APP_INVALID_ARG;
}
optCtx->inPara.pkeyOptArg[optCtx->inPara.pkeyOptArgNum] = HITLS_APP_OptGetValueStr();
++(optCtx->inPara.pkeyOptArgNum);
return HITLS_APP_SUCCESS;
}
static int32_t GenPkeyOptCipher(GenPkeyOptCtx *optCtx)
{
const char *name = HITLS_APP_OptGetUnKownOptName();
return HITLS_APP_GetAndCheckCipherOpt(name, &optCtx->cipherAlgCid);
}
static int32_t GenPkeyOptPassout(GenPkeyOptCtx *optCtx)
{
optCtx->outPara.passOutArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t GenPkeyOptOut(GenPkeyOptCtx *optCtx)
{
optCtx->outPara.outFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static const GenPkeyOptHandleTable g_genPkeyOptHandleTable[] = {
{HITLS_APP_OPT_ERR, GenPkeyOptErr},
{HITLS_APP_OPT_HELP, GenPkeyOptHelp},
{HITLS_APP_OPT_ALGORITHM, GenPkeyOptAlgorithm},
{HITLS_APP_OPT_PKEYOPT, GenPkeyOpt},
{HITLS_APP_OPT_CIPHER_ALG, GenPkeyOptCipher},
{HITLS_APP_OPT_PASS, GenPkeyOptPassout},
{HITLS_APP_OPT_OUT, GenPkeyOptOut},
};
static int32_t ParseGenPkeyOpt(GenPkeyOptCtx *optCtx)
{
int32_t ret = HITLS_APP_SUCCESS;
int optType = HITLS_APP_OPT_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF)) {
for (size_t i = 0; i < (sizeof(g_genPkeyOptHandleTable) / sizeof(g_genPkeyOptHandleTable[0])); ++i) {
if (optType == g_genPkeyOptHandleTable[i].optType) {
ret = g_genPkeyOptHandleTable[i].func(optCtx);
break;
}
}
}
// Obtain the number of parameters that cannot be parsed in the current version,
// and print the error inFormation and help list.
if ((ret == HITLS_APP_SUCCESS) && (HITLS_APP_GetRestOptNum() != 0)) {
AppPrintError("Extra arguments given.\n");
AppPrintError("genpkey: Use -help for summary.\n");
ret = HITLS_APP_OPT_UNKOWN;
}
return ret;
}
static int32_t HandleGenPkeyOpt(GenPkeyOptCtx *optCtx)
{
int32_t ret = ParseGenPkeyOpt(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// 1. SetPkeyPara
if (SetPkeyPara(optCtx) != HITLS_APP_SUCCESS) {
return HITLS_APP_INVALID_ARG;
}
// 2. Read Password
if (HITLS_APP_ParsePasswd(optCtx->outPara.passOutArg, &optCtx->passout) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
// 3. Gen private key
optCtx->pkey = optCtx->genPkeyCtxFunc(&optCtx->genPkeyOptPara);
if (optCtx->pkey == NULL) {
return HITLS_APP_LOAD_KEY_FAIL;
}
// 4. Output the private key.
return HITLS_APP_PrintPrvKey(optCtx->pkey, optCtx->outPara.outFilePath, BSL_FORMAT_PEM, optCtx->cipherAlgCid,
&optCtx->passout);
}
static void InitGenPkeyOptCtx(GenPkeyOptCtx *optCtx)
{
optCtx->pkey = NULL;
optCtx->genPkeyCtxFunc = NULL;
optCtx->genPkeyOptPara.bits = DEFAULT_RSA_KEYGEN_BITS;
optCtx->genPkeyOptPara.pkeyParaId = CRYPT_PKEY_PARAID_MAX;
optCtx->passout = NULL;
optCtx->cipherAlgCid = CRYPT_CIPHER_MAX;
optCtx->inPara.algorithm = NULL;
memset_s(optCtx->inPara.pkeyOptArg, MAX_PKEY_OPT_ARG, 0, MAX_PKEY_OPT_ARG);
optCtx->inPara.pkeyOptArgNum = 0;
optCtx->outPara.outFilePath = NULL;
optCtx->outPara.passOutArg = NULL;
}
static void UnInitGenPkeyOptCtx(GenPkeyOptCtx *optCtx)
{
CRYPT_EAL_PkeyFreeCtx(optCtx->pkey);
optCtx->pkey = NULL;
if (optCtx->passout != NULL) {
BSL_SAL_ClearFree(optCtx->passout, strlen(optCtx->passout));
}
}
// genpkey main function
int32_t HITLS_GenPkeyMain(int argc, char *argv[])
{
GenPkeyOptCtx optCtx = {};
InitGenPkeyOptCtx(&optCtx);
int32_t ret = HITLS_APP_SUCCESS;
do {
ret = HITLS_APP_OptBegin(argc, argv, g_genPkeyOpts);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
break;
}
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR,
"provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) {
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = HandleGenPkeyOpt(&optCtx);
} while (false);
CRYPT_EAL_RandDeinitEx(NULL);
HITLS_APP_OptEnd();
UnInitGenPkeyOptCtx(&optCtx);
return ret;
} | 2302_82127028/openHiTLS-examples_5062 | apps/src/app_genpkey.c | C | unknown | 11,840 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_genrsa.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <termios.h>
#include <unistd.h>
#include <securec.h>
#include <linux/limits.h>
#include "bsl_ui.h"
#include "bsl_uio.h"
#include "app_utils.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_errno.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_algid.h"
#include "crypt_types.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_pkey.h"
#include "crypt_util_rand.h"
#include "crypt_eal_codecs.h"
typedef enum {
HITLS_APP_OPT_NUMBITS = 0,
HITLS_APP_OPT_CIPHER = 2,
HITLS_APP_OPT_OUT_FILE,
} HITLSOptType;
typedef struct {
char *outFile;
long numBits; // Indicates the length of the private key entered by the user.
int32_t cipherId; // Indicates the symmetric encryption algorithm ID entered by the user.
} GenrsaInOpt;
const HITLS_CmdOption g_genrsaOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"cipher", HITLS_APP_OPT_CIPHER, HITLS_APP_OPT_VALUETYPE_STRING, "Secret key cryptography"},
{"out", HITLS_APP_OPT_OUT_FILE, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output the rsa key to specified file"},
{"numbits", HITLS_APP_OPT_NUMBITS, HITLS_APP_OPT_VALUETYPE_PARAMTERS, "RSA key length, command line tail value"},
{NULL}
};
uint8_t g_e[] = {0x01, 0x00, 0x01}; // Default E value
const uint32_t g_numBitsArray[] = {1024, 2048, 3072, 4096};
const HITLS_APPAlgList g_IdList[] = {
{CRYPT_CIPHER_AES128_CBC, "aes128-cbc"},
{CRYPT_CIPHER_AES192_CBC, "aes192-cbc"},
{CRYPT_CIPHER_AES256_CBC, "aes256-cbc"},
{CRYPT_CIPHER_AES128_XTS, "aes128-xts"},
{CRYPT_CIPHER_AES256_XTS, "aes256-xts"},
{CRYPT_CIPHER_SM4_XTS, "sm4-xts"},
{CRYPT_CIPHER_SM4_CBC, "sm4-cbc"},
{CRYPT_CIPHER_SM4_CTR, "sm4-ctr"},
{CRYPT_CIPHER_SM4_CFB, "sm4-cfb"},
{CRYPT_CIPHER_SM4_OFB, "sm4-ofb"},
{CRYPT_CIPHER_AES128_CFB, "aes128-cfb"},
{CRYPT_CIPHER_AES192_CFB, "aes192-cfb"},
{CRYPT_CIPHER_AES256_CFB, "aes256-cfb"},
{CRYPT_CIPHER_AES128_OFB, "aes128-ofb"},
{CRYPT_CIPHER_AES192_OFB, "aes192-ofb"},
{CRYPT_CIPHER_AES256_OFB, "aes256-ofb"},
};
static void PrintAlgList(void)
{
AppPrintError("The current version supports only the following Pkey algorithms:\n");
for (size_t i = 0; i < sizeof(g_IdList) / sizeof(g_IdList[0]); i++) {
AppPrintError("%-19s", g_IdList[i].algName);
// Four algorithm names are displayed in each row.
if ((i + 1) % REC_ALG_NUM_EACHLINE == 0 && i != sizeof(g_IdList) - 1) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return;
}
static int32_t GetAlgId(const char *name)
{
for (size_t i = 0; i < sizeof(g_IdList) / sizeof(g_IdList[0]); i++) {
if (strcmp(g_IdList[i].algName, name) == 0) {
return g_IdList[i].id;
}
}
(void)PrintAlgList();
return -1;
}
int32_t HITLS_APP_Passwd(char *buf, int32_t bufMaxLen, int32_t flag, void *userdata)
{
int32_t errLen = -1;
if (buf == NULL) {
return errLen;
}
int32_t cbRet = HITLS_APP_SUCCESS;
uint32_t bufLen = bufMaxLen;
BSL_UI_ReadPwdParam param = {"password", NULL, flag};
if (userdata == NULL) {
cbRet = BSL_UI_ReadPwdUtil(¶m, buf, &bufLen, HITLS_APP_DefaultPassCB, NULL);
if (cbRet == BSL_UI_READ_BUFF_TOO_LONG || cbRet == BSL_UI_READ_LEN_TOO_SHORT) {
(void)memset_s(buf, bufMaxLen, 0, bufMaxLen);
HITLS_APP_PrintPassErrlog();
return errLen;
}
if (cbRet != BSL_SUCCESS) {
(void)memset_s(buf, bufMaxLen, 0, bufMaxLen);
return errLen;
}
bufLen -= 1;
buf[bufLen] = '\0';
cbRet = HITLS_APP_CheckPasswd((uint8_t *)buf, bufLen);
if (cbRet != HITLS_APP_SUCCESS) {
(void)memset_s(buf, bufMaxLen, 0, bufMaxLen);
return errLen;
}
} else if (userdata != NULL) {
if (strlen(userdata) > APP_MAX_PASS_LENGTH) {
HITLS_APP_PrintPassErrlog();
return errLen;
}
cbRet = HITLS_APP_CheckPasswd((uint8_t *)userdata, strlen(userdata));
if (cbRet != HITLS_APP_SUCCESS) {
return errLen;
}
if (strncpy_s(buf, bufMaxLen, (char *)userdata, strlen(userdata)) != EOK) {
(void)memset_s(buf, bufMaxLen, 0, bufMaxLen);
return errLen;
}
bufLen = strlen(buf);
}
return bufLen;
}
static int32_t HandleOpt(GenrsaInOpt *opt)
{
int32_t optType;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
switch (optType) {
case HITLS_APP_OPT_EOF:
break;
case HITLS_APP_OPT_ERR:
AppPrintError("genrsa: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_OPT_HELP:
HITLS_APP_OptHelpPrint(g_genrsaOpts);
return HITLS_APP_HELP;
case HITLS_APP_OPT_CIPHER:
if ((opt->cipherId = GetAlgId(HITLS_APP_OptGetValueStr())) == -1) {
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_OUT_FILE:
opt->outFile = HITLS_APP_OptGetValueStr();
break;
default:
break;
}
}
// Obtains the value of the last digit numbits.
int32_t restOptNum = HITLS_APP_GetRestOptNum();
if (restOptNum == 1) {
char **numbits = HITLS_APP_GetRestOpt();
if (HITLS_APP_OptGetLong(numbits[0], &opt->numBits) != HITLS_APP_SUCCESS) {
return HITLS_APP_OPT_VALUE_INVALID;
}
} else {
if (restOptNum > 1) {
(void)AppPrintError("Extra arguments given.\n");
} else {
(void)AppPrintError("The command is incorrectly used.\n");
}
AppPrintError("genrsa: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
static bool IsNumBitsValid(long num)
{
for (size_t i = 0; i < sizeof(g_numBitsArray) / sizeof(g_numBitsArray[0]); i++) {
if (num == g_numBitsArray[i]) {
return true;
}
}
return false;
}
static int32_t CheckPara(GenrsaInOpt *opt, BSL_UIO *outUio)
{
if (opt->cipherId == -1) {
AppPrintError("The command is incorrectly used.\n");
AppPrintError("genrsa: Use -help for summary.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
// Check whether the RSA key length (in bits) of the private key complies with the specifications.
// The length must be greater than or equal to 1024.
if (!IsNumBitsValid(opt->numBits)) {
AppPrintError("Your RSA key length is %ld.\n", opt->numBits);
AppPrintError("The RSA key length is error, supporting 1024、2048、3072、4096.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
// Obtains the post-value of the OUT option. If there is no post-value or this option, stdout.
if (opt->outFile == NULL) {
if (BSL_UIO_Ctrl(outUio, BSL_UIO_FILE_PTR, 0, (void *)stdout) != BSL_SUCCESS) {
AppPrintError("Failed to set stdout mode.\n");
return HITLS_APP_UIO_FAIL;
}
} else {
// User input file path, which is bound to the output file.
if (strlen(opt->outFile) >= PATH_MAX || strlen(opt->outFile) == 0) {
AppPrintError("The length of outfile error, range is (0, 4096].\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (BSL_UIO_Ctrl(outUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_WRITE, opt->outFile) != BSL_SUCCESS) {
AppPrintError("Failed to set outfile mode.\n");
return HITLS_APP_UIO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
static CRYPT_EAL_PkeyPara *PkeyNewRsaPara(uint8_t *e, uint32_t eLen, uint32_t bits)
{
CRYPT_EAL_PkeyPara *para = malloc(sizeof(CRYPT_EAL_PkeyPara));
if (para == NULL) {
return NULL;
}
para->id = CRYPT_PKEY_RSA;
para->para.rsaPara.bits = bits;
para->para.rsaPara.e = e;
para->para.rsaPara.eLen = eLen;
return para;
}
static int32_t HandlePkey(GenrsaInOpt *opt, char *resBuf, uint32_t bufLen)
{
int32_t ret = HITLS_APP_SUCCESS;
// Setting the Entropy Source
(void)CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default", NULL, 0, NULL);
CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_RSA,
CRYPT_EAL_PKEY_UNKNOWN_OPERATE, "provider=default");
if (pkey == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_PkeyPara *pkeyParam = NULL;
pkeyParam = PkeyNewRsaPara(g_e, sizeof(g_e), opt->numBits);
if (pkeyParam == NULL) {
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto hpEnd;
}
if (CRYPT_EAL_PkeySetPara(pkey, pkeyParam) != CRYPT_SUCCESS) {
ret = HITLS_APP_CRYPTO_FAIL;
goto hpEnd;
}
if (CRYPT_EAL_PkeyGen(pkey) != CRYPT_SUCCESS) {
ret = HITLS_APP_CRYPTO_FAIL;
goto hpEnd;
}
char pwd[APP_MAX_PASS_LENGTH + 1] = {0};
int32_t pwdLen = HITLS_APP_Passwd(pwd, APP_MAX_PASS_LENGTH + 1, 1, NULL);
if (pwdLen == -1) {
ret = HITLS_APP_PASSWD_FAIL;
goto hpEnd;
}
CRYPT_Pbkdf2Param pbkdfParam = {BSL_CID_PBES2, BSL_CID_PBKDF2, CRYPT_MAC_HMAC_SHA1,
opt->cipherId, 16, (uint8_t *)pwd, pwdLen, 2048};
CRYPT_EncodeParam encodeParam = {CRYPT_DERIVE_PBKDF2, &pbkdfParam};
BSL_Buffer encode = {0};
ret = CRYPT_EAL_EncodeBuffKey(pkey, &encodeParam, BSL_FORMAT_PEM, CRYPT_PRIKEY_PKCS8_ENCRYPT, &encode);
(void)memset_s(pwd, APP_MAX_PASS_LENGTH, 0, APP_MAX_PASS_LENGTH);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("Encode failed.\n");
ret = HITLS_APP_ENCODE_FAIL;
goto hpEnd;
}
if (memcpy_s(resBuf, bufLen, encode.data, encode.dataLen) != EOK) {
ret = HITLS_APP_SECUREC_FAIL;
}
BSL_SAL_FREE(encode.data);
hpEnd:
CRYPT_EAL_RandDeinitEx(NULL);
BSL_SAL_ClearFree(pkeyParam, sizeof(CRYPT_EAL_PkeyPara));
CRYPT_EAL_PkeyFreeCtx(pkey);
return ret;
}
int32_t HITLS_GenRSAMain(int argc, char *argv[])
{
GenrsaInOpt opt = {NULL, -1, -1};
BSL_UIO *outUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (outUio == NULL) {
AppPrintError("Failed to create the output UIO.\n");
return HITLS_APP_UIO_FAIL;
}
int32_t ret = HITLS_APP_SUCCESS;
if ((ret = HITLS_APP_OptBegin(argc, argv, g_genrsaOpts)) != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
goto GenRsaEnd;
}
if ((ret = HandleOpt(&opt)) != HITLS_APP_SUCCESS) {
goto GenRsaEnd;
}
if ((ret = CheckPara(&opt, outUio)) != HITLS_APP_SUCCESS) {
goto GenRsaEnd;
}
char resBuf[REC_MAX_PEM_FILELEN] = {0};
uint32_t bufLen = sizeof(resBuf);
uint32_t writeLen = 0;
if ((ret = HandlePkey(&opt, resBuf, bufLen)) != HITLS_APP_SUCCESS) {
goto GenRsaEnd;
}
if (BSL_UIO_Write(outUio, resBuf, strlen(resBuf), &writeLen) != BSL_SUCCESS || writeLen == 0) {
ret = HITLS_APP_UIO_FAIL;
goto GenRsaEnd;
}
ret = HITLS_APP_SUCCESS;
GenRsaEnd:
if (opt.outFile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(outUio, true);
}
BSL_UIO_Free(outUio);
HITLS_APP_OptEnd();
return ret;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_genrsa.c | C | unknown | 12,019 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_help.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_function.h"
HITLS_CmdOption g_helpOptions[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Usage: help [options]"},
{NULL}
};
int HITLS_HelpMain(int argc, char *argv[])
{
if (argc == 1) {
AppPrintFuncList();
return HITLS_APP_SUCCESS;
}
HITLS_OptChoice oc;
int32_t ret = HITLS_APP_OptBegin(argc, argv, g_helpOptions);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
HITLS_APP_OptEnd();
return ret;
}
while ((oc = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
switch (oc) {
case HITLS_APP_OPT_ERR:
AppPrintError("help: Use -help for summary.\n");
HITLS_APP_OptEnd();
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_OPT_HELP:
HITLS_APP_OptHelpPrint(g_helpOptions);
HITLS_APP_OptEnd();
return HITLS_APP_SUCCESS;
default:
AppPrintError("help: Use -help for summary.\n");
HITLS_APP_OptEnd();
return HITLS_APP_OPT_UNKOWN;
}
}
if (HITLS_APP_GetRestOptNum() != 1) {
AppPrintError("Please enter help to obtain the support list.\n");
HITLS_APP_OptEnd();
return HITLS_APP_OPT_VALUE_INVALID;
}
HITLS_CmdFunc func = { 0 };
char *proName = HITLS_APP_GetRestOpt()[0];
HITLS_APP_OptEnd();
ret = AppGetProgFunc(proName, &func);
if (ret != 0) {
AppPrintError("Please enter help to obtain the support list.\n");
return ret;
}
char *newArgv[3] = {proName, "--help", NULL};
int newArgc = 2;
return func.main(newArgc, newArgv);
} | 2302_82127028/openHiTLS-examples_5062 | apps/src/app_help.c | C | unknown | 2,358 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_kdf.h"
#include <linux/limits.h>
#include "string.h"
#include "securec.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_eal_kdf.h"
#include "crypt_params_key.h"
#include "bsl_errno.h"
#include "bsl_params.h"
#include "app_opt.h"
#include "app_function.h"
#include "app_list.h"
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_provider.h"
#include "app_utils.h"
typedef enum OptionChoice {
HITLS_APP_OPT_KDF_ERR = -1,
HITLS_APP_OPT_KDF_EOF = 0,
HITLS_APP_OPT_KDF_ALG = HITLS_APP_OPT_KDF_EOF,
HITLS_APP_OPT_KDF_HELP = 1, // The value of the help type of each opt option is 1. The following can be customized.
HITLS_APP_OPT_KDF_KEYLEN,
HITLS_APP_OPT_KDF_MAC_ALG,
HITLS_APP_OPT_KDF_OUT,
HITLS_APP_OPT_KDF_PASS,
HITLS_APP_OPT_KDF_HEXPASS,
HITLS_APP_OPT_KDF_SALT,
HITLS_APP_OPT_KDF_HEXSALT,
HITLS_APP_OPT_KDF_ITER,
HITLS_APP_OPT_KDF_BINARY,
HITLS_APP_PROV_ENUM
} HITLSOptType;
const HITLS_CmdOption g_kdfOpts[] = {
{"help", HITLS_APP_OPT_KDF_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Show usage information for KDF command."},
{"mac", HITLS_APP_OPT_KDF_MAC_ALG, HITLS_APP_OPT_VALUETYPE_STRING,
"Specify MAC algorithm used in KDF (e.g.: hmac-sha256)."},
{"out", HITLS_APP_OPT_KDF_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE,
"Set output file for derived key (default: stdout, hex format)."},
{"binary", HITLS_APP_OPT_KDF_BINARY, HITLS_APP_OPT_VALUETYPE_NO_VALUE,
"Output derived key in binary format."},
{"keylen", HITLS_APP_OPT_KDF_KEYLEN, HITLS_APP_OPT_VALUETYPE_UINT, "Length of derived key in bytes."},
{"pass", HITLS_APP_OPT_KDF_PASS, HITLS_APP_OPT_VALUETYPE_STRING, "Input password as a string."},
{"hexpass", HITLS_APP_OPT_KDF_HEXPASS, HITLS_APP_OPT_VALUETYPE_STRING,
"Input password in hexadecimal format (e.g.: 0x1234ABCD)."},
{"salt", HITLS_APP_OPT_KDF_SALT, HITLS_APP_OPT_VALUETYPE_STRING, "Input salt as a string."},
{"hexsalt", HITLS_APP_OPT_KDF_HEXSALT, HITLS_APP_OPT_VALUETYPE_STRING,
"Input salt in hexadecimal format (e.g.: 0xAABBCCDD)."},
{"iter", HITLS_APP_OPT_KDF_ITER, HITLS_APP_OPT_VALUETYPE_UINT, "Number of iterations for KDF computation."},
HITLS_APP_PROV_OPTIONS,
{"kdfalg...", HITLS_APP_OPT_KDF_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Specify KDF algorithm (e.g.: pbkdf2)."},
{NULL}};
typedef struct {
int32_t macId;
char *kdfName;
int32_t kdfId;
uint32_t keyLen;
char *outFile;
char *pass;
char *hexPass;
char *salt;
char *hexSalt;
uint32_t iter;
AppProvider *provider;
uint32_t isBinary;
} KdfOpt;
typedef int32_t (*KdfOptHandleFunc)(KdfOpt *);
typedef struct {
int optType;
KdfOptHandleFunc func;
} KdfOptHandleFuncMap;
static int32_t HandleKdfErr(KdfOpt *kdfOpt)
{
(void)kdfOpt;
AppPrintError("kdf: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t HandleKdfHelp(KdfOpt *kdfOpt)
{
(void)kdfOpt;
HITLS_APP_OptHelpPrint(g_kdfOpts);
return HITLS_APP_HELP;
}
static int32_t HandleKdfOut(KdfOpt *kdfOpt)
{
kdfOpt->outFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfPass(KdfOpt *kdfOpt)
{
kdfOpt->pass = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfHexPass(KdfOpt *kdfOpt)
{
kdfOpt->hexPass = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfSalt(KdfOpt *kdfOpt)
{
kdfOpt->salt = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfHexSalt(KdfOpt *kdfOpt)
{
kdfOpt->hexSalt = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfIter(KdfOpt *kdfOpt)
{
int32_t ret = HITLS_APP_OptGetUint32(HITLS_APP_OptGetValueStr(), &(kdfOpt->iter));
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("kdf: Invalid iter value.\n");
}
return ret;
}
static int32_t HandleKdfKeyLen(KdfOpt *kdfOpt)
{
int32_t ret = HITLS_APP_OptGetUint32(HITLS_APP_OptGetValueStr(), &(kdfOpt->keyLen));
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("kdf: Invalid keylen value.\n");
}
return ret;
}
static int32_t HandleKdfBinary(KdfOpt *kdfOpt)
{
kdfOpt->isBinary = 1;
return HITLS_APP_SUCCESS;
}
static int32_t HandleKdfMacAlg(KdfOpt *kdfOpt)
{
char *macName = HITLS_APP_OptGetValueStr();
if (macName == NULL) {
AppPrintError("kdf: MAC algorithm is NULL.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
kdfOpt->macId = HITLS_APP_GetCidByName(macName, HITLS_APP_LIST_OPT_MAC_ALG);
if (kdfOpt->macId == BSL_CID_UNKNOWN) {
AppPrintError("kdf: Unsupported MAC algorithm: %s\n", macName);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static const KdfOptHandleFuncMap g_kdfOptHandleFuncMap[] = {
{HITLS_APP_OPT_KDF_ERR, HandleKdfErr},
{HITLS_APP_OPT_KDF_HELP, HandleKdfHelp},
{HITLS_APP_OPT_KDF_OUT, HandleKdfOut},
{HITLS_APP_OPT_KDF_PASS, HandleKdfPass},
{HITLS_APP_OPT_KDF_HEXPASS, HandleKdfHexPass},
{HITLS_APP_OPT_KDF_SALT, HandleKdfSalt},
{HITLS_APP_OPT_KDF_HEXSALT, HandleKdfHexSalt},
{HITLS_APP_OPT_KDF_ITER, HandleKdfIter},
{HITLS_APP_OPT_KDF_KEYLEN, HandleKdfKeyLen},
{HITLS_APP_OPT_KDF_MAC_ALG, HandleKdfMacAlg},
{HITLS_APP_OPT_KDF_BINARY, HandleKdfBinary},
};
static int32_t ParseKdfOpt(KdfOpt *kdfOpt)
{
int ret = HITLS_APP_SUCCESS;
int optType = HITLS_APP_OPT_KDF_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_KDF_EOF)) {
for (size_t i = 0; i < (sizeof(g_kdfOptHandleFuncMap) / sizeof(g_kdfOptHandleFuncMap[0])); ++i) {
if (optType == g_kdfOptHandleFuncMap[i].optType) {
ret = g_kdfOptHandleFuncMap[i].func(kdfOpt);
break;
}
}
HITLS_APP_PROV_CASES(optType, kdfOpt->provider)
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t GetKdfAlg(KdfOpt *kdfOpt)
{
int32_t argc = HITLS_APP_GetRestOptNum();
char **argv = HITLS_APP_GetRestOpt();
if (argc == 0) {
AppPrintError("Please input KDF algorithm.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
kdfOpt->kdfName = argv[0];
kdfOpt->kdfId = HITLS_APP_GetCidByName(kdfOpt->kdfName, HITLS_APP_LIST_OPT_KDF_ALG);
if (kdfOpt->macId == BSL_CID_UNKNOWN) {
AppPrintError("Not support KDF algorithm.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (argc - 1 != 0) {
AppPrintError("Extra arguments given.\n");
AppPrintError("mac: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckParam(KdfOpt *kdfOpt)
{
if (kdfOpt->kdfId == CRYPT_KDF_PBKDF2) {
if (kdfOpt->pass == NULL && kdfOpt->hexPass == NULL) {
AppPrintError("kdf: No pass entered.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (kdfOpt->pass != NULL && kdfOpt->hexPass != NULL) {
AppPrintError("kdf: Cannot specify both pass and hexpass.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (kdfOpt->salt == NULL && kdfOpt->hexSalt == NULL) {
AppPrintError("kdf: No salt entered.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (kdfOpt->salt != NULL && kdfOpt->hexSalt != NULL) {
AppPrintError("kdf: Cannot specify both salt and hexsalt.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
}
if (kdfOpt->keyLen == 0) {
AppPrintError("kdf: Input keylen is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (kdfOpt->iter == 0) {
AppPrintError("kdf: Input iter is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (kdfOpt->outFile != NULL && strlen((const char*)kdfOpt->outFile) > PATH_MAX) {
AppPrintError("kdf: The output file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static CRYPT_EAL_KdfCTX *InitAlgKdf(KdfOpt *kdfOpt)
{
if (HITLS_APP_LoadProvider(kdfOpt->provider->providerPath, kdfOpt->provider->providerName) != HITLS_APP_SUCCESS) {
return NULL;
}
CRYPT_EAL_KdfCTX *ctx = CRYPT_EAL_ProviderKdfNewCtx(APP_GetCurrent_LibCtx(), kdfOpt->kdfId,
kdfOpt->provider->providerAttr);
if (ctx == NULL) {
(void)AppPrintError("Failed to create the algorithm(%s) context\n", kdfOpt->kdfName);
}
return ctx;
}
static int32_t KdfParsePass(KdfOpt *kdfOpt, uint8_t **pass, uint32_t *passLen)
{
if (kdfOpt->pass != NULL) {
*passLen = strlen((const char*)kdfOpt->pass);
*pass = (uint8_t*)kdfOpt->pass;
} else {
int32_t ret = HITLS_APP_HexToByte(kdfOpt->hexPass, pass, passLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("kdf:Invalid pass: %s.\n", kdfOpt->hexPass);
return ret;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t KdfParseSalt(KdfOpt *kdfOpt, uint8_t **salt, uint32_t *saltLen)
{
if (kdfOpt->salt != NULL) {
*saltLen = strlen((const char*)kdfOpt->salt);
*salt = (uint8_t*)kdfOpt->salt;
} else {
int32_t ret = HITLS_APP_HexToByte(kdfOpt->hexSalt, salt, saltLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("kdf:Invalid salt: %s.\n", kdfOpt->hexSalt);
return ret;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t Pbkdf2Params(CRYPT_EAL_KdfCTX *ctx, BSL_Param *params, KdfOpt *kdfOpt)
{
uint32_t index = 0;
uint8_t *pass = NULL;
uint32_t passLen = 0;
uint8_t *salt = NULL;
uint32_t saltLen = 0;
int32_t ret = HITLS_APP_SUCCESS;
do {
ret = KdfParsePass(kdfOpt, &pass, &passLen);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = KdfParseSalt(kdfOpt, &salt, &saltLen);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32,
&(kdfOpt->macId), sizeof(kdfOpt->macId));
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("kdf:Init macId failed. ERROR:%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, pass, passLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("kdf:Init pass failed. ERROR:%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt, saltLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("kdf:Init salt failed. ERROR:%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = BSL_PARAM_InitValue(¶ms[index++], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32,
&kdfOpt->iter, sizeof(kdfOpt->iter));
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("kdf:Init iter failed. ERROR:%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = CRYPT_EAL_KdfSetParam(ctx, params);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("kdf:KdfSetParam failed. ERROR:%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
}
} while (0);
if (kdfOpt->salt == NULL) {
BSL_SAL_FREE(salt);
}
if (kdfOpt->pass == NULL) {
BSL_SAL_FREE(pass);
}
return ret;
}
static int32_t PbkdfParamSet(CRYPT_EAL_KdfCTX *ctx, KdfOpt *kdfOpt)
{
if (kdfOpt->kdfId == CRYPT_KDF_PBKDF2) {
BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END};
return Pbkdf2Params(ctx, params, kdfOpt);
}
(void)AppPrintError("kdf: Unsupported KDF algorithm: %s\n", kdfOpt->kdfName);
return HITLS_APP_OPT_VALUE_INVALID;
}
static int32_t KdfResult(CRYPT_EAL_KdfCTX *ctx, KdfOpt *kdfOpt)
{
uint8_t *out = NULL;
uint32_t outLen = kdfOpt->keyLen;
int32_t ret = PbkdfParamSet(ctx, kdfOpt);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("PbkdfParamSet failed. \n");
return ret;
}
out = BSL_SAL_Malloc(outLen);
if (out == NULL) {
(void)AppPrintError("kdf: Allocate memory failed. \n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
ret = CRYPT_EAL_KdfDerive(ctx, out, outLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("KdfDeriv failed. ERROR:%d\n", ret);
BSL_SAL_FREE(out);
return HITLS_APP_CRYPTO_FAIL;
}
BSL_UIO *fileOutUio = HITLS_APP_UioOpen(kdfOpt->outFile, 'w', 0);
if (fileOutUio == NULL) {
BSL_SAL_FREE(out);
(void)AppPrintError("kdf:UioOpen failed\n");
return HITLS_APP_UIO_FAIL;
}
if (kdfOpt->outFile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(fileOutUio, true);
}
ret = HITLS_APP_OptWriteUio(fileOutUio, out, outLen,
kdfOpt->isBinary == 1 ? HITLS_APP_FORMAT_TEXT: HITLS_APP_FORMAT_HEX);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("kdf:Failed to output the content to the screen\n");
}
BSL_UIO_Free(fileOutUio);
BSL_SAL_FREE(out);
return ret;
}
int32_t HITLS_KdfMain(int argc, char *argv[])
{
int32_t mainRet = HITLS_APP_SUCCESS;
AppProvider appProvider = {"default", NULL, "provider=default"};
KdfOpt kdfOpt = {CRYPT_MAC_HMAC_SHA256, NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, 1000, &appProvider, 0};
CRYPT_EAL_KdfCTX *ctx = NULL;
do {
mainRet = HITLS_APP_OptBegin(argc, argv, g_kdfOpts);
if (mainRet != HITLS_APP_SUCCESS) {
HITLS_APP_OptEnd();
(void)AppPrintError("error in opt begin.\n");
break;
}
mainRet = ParseKdfOpt(&kdfOpt);
if (mainRet != HITLS_APP_SUCCESS) {
HITLS_APP_OptEnd();
break;
}
mainRet = GetKdfAlg(&kdfOpt);
if (mainRet != HITLS_APP_SUCCESS) {
HITLS_APP_OptEnd();
break;
}
HITLS_APP_OptEnd();
mainRet = CheckParam(&kdfOpt);
if (mainRet != HITLS_APP_SUCCESS) {
break;
}
ctx = InitAlgKdf(&kdfOpt);
if (ctx == NULL) {
mainRet = HITLS_APP_CRYPTO_FAIL;
break;
}
mainRet = KdfResult(ctx, &kdfOpt);
} while (0);
CRYPT_EAL_KdfFreeCtx(ctx);
HITLS_APP_OptEnd();
return mainRet;
} | 2302_82127028/openHiTLS-examples_5062 | apps/src/app_kdf.c | C | unknown | 15,253 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <securec.h>
#include "hitls_error.h"
#include "bsl_errno.h"
#include "bsl_uio.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_opt.h"
#include "crypt_algid.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_mac.h"
#include "crypt_eal_pkey.h"
#include "crypt_eal_md.h"
#include "crypt_eal_rand.h"
#include "crypt_eal_kdf.h"
#include "app_list.h"
const HITLS_CmdOption g_listOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"all-algorithms", HITLS_APP_LIST_OPT_ALL_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported all algorthms"},
{"digest-algorithms", HITLS_APP_LIST_OPT_DGST_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE,
"List supported digest algorthms"},
{"cipher-algorithms", HITLS_APP_LIST_OPT_CIPHER_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE,
"List supported cipher algorthms"},
{"asym-algorithms", HITLS_APP_LIST_OPT_ASYM_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported asym algorthms"},
{"mac-algorithms", HITLS_APP_LIST_OPT_MAC_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported mac algorthms"},
{"rand-algorithms", HITLS_APP_LIST_OPT_RAND_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported rand algorthms"},
{"kdf-algorithms", HITLS_APP_LIST_OPT_KDF_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported kdf algorthms"},
{"all-curves", HITLS_APP_LIST_OPT_CURVES, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "List supported curves"},
{NULL}};
typedef struct {
int32_t cid;
const char *name;
} CidInfo;
static const CidInfo g_allCipherAlgInfo [] = {
{CRYPT_CIPHER_AES128_CBC, "aes128-cbc"},
{CRYPT_CIPHER_AES128_CCM, "aes128-ccm"},
{CRYPT_CIPHER_AES128_CFB, "aes128-cfb"},
{CRYPT_CIPHER_AES128_CTR, "aes128-ctr"},
{CRYPT_CIPHER_AES128_ECB, "aes128-ecb"},
{CRYPT_CIPHER_AES128_GCM, "aes128-gcm"},
{CRYPT_CIPHER_AES128_OFB, "aes128-ofb"},
{CRYPT_CIPHER_AES128_XTS, "aes128-xts"},
{CRYPT_CIPHER_AES192_CBC, "aes192-cbc"},
{CRYPT_CIPHER_AES192_CCM, "aes192-ccm"},
{CRYPT_CIPHER_AES192_CFB, "aes192-cfb"},
{CRYPT_CIPHER_AES192_CTR, "aes192-ctr"},
{CRYPT_CIPHER_AES192_ECB, "aes192-ecb"},
{CRYPT_CIPHER_AES192_GCM, "aes192-gcm"},
{CRYPT_CIPHER_AES192_OFB, "aes192-ofb"},
{CRYPT_CIPHER_AES256_CBC, "aes256-cbc"},
{CRYPT_CIPHER_AES256_CCM, "aes256-ccm"},
{CRYPT_CIPHER_AES256_CFB, "aes256-cfb"},
{CRYPT_CIPHER_AES256_CTR, "aes256-ctr"},
{CRYPT_CIPHER_AES256_ECB, "aes256-ecb"},
{CRYPT_CIPHER_AES256_GCM, "aes256-gcm"},
{CRYPT_CIPHER_AES256_OFB, "aes256-ofb"},
{CRYPT_CIPHER_AES256_XTS, "aes256-xts"},
{CRYPT_CIPHER_CHACHA20_POLY1305, "chacha20-poly1305"},
{CRYPT_CIPHER_SM4_CBC, "sm4-cbc"},
{CRYPT_CIPHER_SM4_CFB, "sm4-cfb"},
{CRYPT_CIPHER_SM4_CTR, "sm4-ctr"},
{CRYPT_CIPHER_SM4_ECB, "sm4-ecb"},
{CRYPT_CIPHER_SM4_GCM, "sm4-gcm"},
{CRYPT_CIPHER_SM4_OFB, "sm4-ofb"},
{CRYPT_CIPHER_SM4_XTS, "sm4-xts"},
};
#define CIPHER_ALG_CNT (sizeof(g_allCipherAlgInfo) / sizeof(CidInfo))
static const CidInfo g_allMdAlgInfo[] = {
{CRYPT_MD_MD5, "md5"},
{CRYPT_MD_SHA1, "sha1"},
{CRYPT_MD_SHA224, "sha224"},
{CRYPT_MD_SHA256, "sha256"},
{CRYPT_MD_SHA384, "sha384"},
{CRYPT_MD_SHA512, "sha512"},
{CRYPT_MD_SHA3_224, "sha3-224"},
{CRYPT_MD_SHA3_256, "sha3-256"},
{CRYPT_MD_SHA3_384, "sha3-384"},
{CRYPT_MD_SHA3_512, "sha3-512"},
{CRYPT_MD_SHAKE128, "shake128"},
{CRYPT_MD_SHAKE256, "shake256"},
{CRYPT_MD_SM3, "sm3"},
};
#define MD_ALG_CNT (sizeof(g_allMdAlgInfo) / sizeof(CidInfo))
static const CidInfo g_allPkeyAlgInfo[] = {
{CRYPT_PKEY_ECDH, "ecdh"},
{CRYPT_PKEY_ECDSA, "ecdsa"},
{CRYPT_PKEY_ED25519, "ed25519"},
{CRYPT_PKEY_DH, "dh"},
{CRYPT_PKEY_DSA, "dsa"},
{CRYPT_PKEY_RSA, "rsa"},
{CRYPT_PKEY_SM2, "sm2"},
{CRYPT_PKEY_X25519, "x25519"},
};
#define PKEY_ALG_CNT (sizeof(g_allPkeyAlgInfo) / sizeof(CidInfo))
static const CidInfo g_allMacAlgInfo[] = {
{CRYPT_MAC_HMAC_MD5, "hmac-md5"},
{CRYPT_MAC_HMAC_SHA1, "hmac-sha1"},
{CRYPT_MAC_HMAC_SHA224, "hmac-sha224"},
{CRYPT_MAC_HMAC_SHA256, "hmac-sha256"},
{CRYPT_MAC_HMAC_SHA384, "hmac-sha384"},
{CRYPT_MAC_HMAC_SHA512, "hmac-sha512"},
{CRYPT_MAC_HMAC_SHA3_224, "hmac-sha3-224"},
{CRYPT_MAC_HMAC_SHA3_256, "hmac-sha3-256"},
{CRYPT_MAC_HMAC_SHA3_384, "hmac-sha3-384"},
{CRYPT_MAC_HMAC_SHA3_512, "hmac-sha3-512"},
{CRYPT_MAC_HMAC_SM3, "hmac-sm3"},
{CRYPT_MAC_CMAC_AES128, "cmac-aes128"},
{CRYPT_MAC_CMAC_AES192, "cmac-aes192"},
{CRYPT_MAC_CMAC_AES256, "cmac-aes256"},
{CRYPT_MAC_GMAC_AES128, "gmac-aes128"},
{CRYPT_MAC_GMAC_AES192, "gmac-aes192"},
{CRYPT_MAC_GMAC_AES256, "gmac-aes256"},
{CRYPT_MAC_SIPHASH64, "siphash64"},
{CRYPT_MAC_SIPHASH128, "siphash128"},
{CRYPT_MAC_CBC_MAC_SM4, "cbc-mac-sm4"},
};
#define MAC_ALG_CNT (sizeof(g_allMacAlgInfo) / sizeof(CidInfo))
static const CidInfo g_allRandAlgInfo[] = {
{CRYPT_RAND_SHA1, "sha1"},
{CRYPT_RAND_SHA224, "sha224"},
{CRYPT_RAND_SHA256, "sha256"},
{CRYPT_RAND_SHA384, "sha384"},
{CRYPT_RAND_SHA512, "sha512"},
{CRYPT_RAND_HMAC_SHA1, "hmac-sha1"},
{CRYPT_RAND_HMAC_SHA224, "hmac-sha224"},
{CRYPT_RAND_HMAC_SHA256, "hmac-sha256"},
{CRYPT_RAND_HMAC_SHA384, "hmac-sha384"},
{CRYPT_RAND_HMAC_SHA512, "hmac-sha512"},
{CRYPT_RAND_AES128_CTR, "aes128-ctr"},
{CRYPT_RAND_AES192_CTR, "aes192-ctr"},
{CRYPT_RAND_AES256_CTR, "aes256-ctr"},
{CRYPT_RAND_AES128_CTR_DF, "aes128-ctr-df"},
{CRYPT_RAND_AES192_CTR_DF, "aes192-ctr-df"},
{CRYPT_RAND_AES256_CTR_DF, "aes256-ctr-df"},
};
#define RAND_ALG_CNT (sizeof(g_allRandAlgInfo) / sizeof(CidInfo))
static const CidInfo g_allKdfAlgInfo[] = {
{CRYPT_MAC_HMAC_MD5, "hmac-md5"},
{CRYPT_MAC_HMAC_SHA1, "hmac-sha1"},
{CRYPT_MAC_HMAC_SHA224, "hmac-sha224"},
{CRYPT_MAC_HMAC_SHA256, "hmac-sha256"},
{CRYPT_MAC_HMAC_SHA384, "hmac-sha384"},
{CRYPT_MAC_HMAC_SHA512, "hmac-sha512"},
{CRYPT_MAC_HMAC_SHA3_224, "hmac-sha3-224"},
{CRYPT_MAC_HMAC_SHA3_256, "hmac-sha3-256"},
{CRYPT_MAC_HMAC_SHA3_384, "hmac-sha3-384"},
{CRYPT_MAC_HMAC_SHA3_512, "hmac-sha3-512"},
{CRYPT_MAC_HMAC_SM3, "hmac-sm3"},
{CRYPT_KDF_PBKDF2, "pbkdf2"},
};
#define KDF_ALG_CNT (sizeof(g_allKdfAlgInfo) / sizeof(CidInfo))
static CidInfo g_allCurves[] = {
{CRYPT_ECC_NISTP224, "P-224"},
{CRYPT_ECC_NISTP256, "P-256"},
{CRYPT_ECC_NISTP384, "P-384"},
{CRYPT_ECC_NISTP521, "P-521"},
{CRYPT_ECC_NISTP224, "prime224v1"},
{CRYPT_ECC_NISTP256, "prime256v1"},
{CRYPT_ECC_NISTP384, "secp384r1"},
{CRYPT_ECC_NISTP521, "secp521r1"},
{CRYPT_ECC_BRAINPOOLP256R1, "brainpoolp256r1"},
{CRYPT_ECC_BRAINPOOLP384R1, "brainpoolp384r1"},
{CRYPT_ECC_BRAINPOOLP512R1, "brainpoolp512r1"},
{CRYPT_ECC_SM2, "sm2"},
};
#define CURVES_SPLIT_LINE 6
#define CURVES_CNT (sizeof(g_allCurves) / sizeof(CidInfo))
typedef void (*PrintAlgFunc)(void);
PrintAlgFunc g_printAlgFuncList[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
#define PRINT_ALG_FUNC_LIST_CNT (sizeof(g_printAlgFuncList) / sizeof(PrintAlgFunc))
static void AppPushPrintFunc(PrintAlgFunc func)
{
for (size_t i = 0; i < PRINT_ALG_FUNC_LIST_CNT; ++i) {
if ((g_printAlgFuncList[i] == NULL) || (g_printAlgFuncList[i] == func)) {
g_printAlgFuncList[i] = func;
return;
}
}
}
static void AppPrintList(void)
{
for (size_t i = 0; i < PRINT_ALG_FUNC_LIST_CNT; ++i) {
if ((g_printAlgFuncList[i] != NULL)) {
g_printAlgFuncList[i]();
}
}
}
static void ResetPrintAlgFuncList(void)
{
for (size_t i = 0; i < PRINT_ALG_FUNC_LIST_CNT; ++i) {
g_printAlgFuncList[i] = NULL;
}
}
static BSL_UIO *g_stdout = NULL;
static int32_t AppPrintStdoutUioInit(void)
{
g_stdout = BSL_UIO_New(BSL_UIO_FileMethod());
if (BSL_UIO_Ctrl(g_stdout, BSL_UIO_FILE_PTR, 0, (void *)stdout) != BSL_SUCCESS) {
AppPrintError("Failed to set stdout mode.\n");
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static void AppPrintStdoutUioUnInit(void)
{
BSL_UIO_Free(g_stdout);
}
static void PrintCipherAlg(void)
{
AppPrint(g_stdout, "List Cipher Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < CIPHER_ALG_CNT; ++i) {
if (!CRYPT_EAL_CipherIsValidAlgId(g_allCipherAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allCipherAlgInfo[i].name, g_allCipherAlgInfo[i].cid);
}
}
static void PrintMdAlg(void)
{
AppPrint(g_stdout, "List Digest Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < MD_ALG_CNT; ++i) {
if (!CRYPT_EAL_MdIsValidAlgId(g_allMdAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allMdAlgInfo[i].name, g_allMdAlgInfo[i].cid);
}
}
static void PrintPkeyAlg(void)
{
AppPrint(g_stdout, "List Asym Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < PKEY_ALG_CNT; ++i) {
if (!CRYPT_EAL_PkeyIsValidAlgId(g_allPkeyAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allPkeyAlgInfo[i].name, g_allPkeyAlgInfo[i].cid);
}
}
static void PrintMacAlg(void)
{
AppPrint(g_stdout, "List Mac Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < MAC_ALG_CNT; ++i) {
if (!CRYPT_EAL_MacIsValidAlgId(g_allMacAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allMacAlgInfo[i].name, g_allMacAlgInfo[i].cid);
}
}
static void PrintRandAlg(void)
{
AppPrint(g_stdout, "List Rand Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < RAND_ALG_CNT; ++i) {
if (!CRYPT_EAL_RandIsValidAlgId(g_allRandAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allRandAlgInfo[i].name, g_allRandAlgInfo[i].cid);
}
}
static void PrintHkdfAlg(void)
{
AppPrint(g_stdout, "List Hkdf Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < KDF_ALG_CNT; ++i) {
if (!CRYPT_EAL_KdfIsValidAlgId(g_allKdfAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allKdfAlgInfo[i].name, g_allKdfAlgInfo[i].cid);
}
}
static void PrintPbkdf2Alg(void)
{
AppPrint(g_stdout, "List Pbkdf2 Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < KDF_ALG_CNT; ++i) {
if (!CRYPT_EAL_KdfIsValidAlgId(g_allKdfAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allKdfAlgInfo[i].name, g_allKdfAlgInfo[i].cid);
}
}
static void PrintKdftls12Alg(void)
{
AppPrint(g_stdout, "List Kdftls12 Algorithms:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < KDF_ALG_CNT; ++i) {
if (!CRYPT_EAL_KdfIsValidAlgId(g_allKdfAlgInfo[i].cid)) {
continue;
}
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allKdfAlgInfo[i].name, g_allKdfAlgInfo[i].cid);
}
}
static void PrintKdfAlg(void)
{
PrintHkdfAlg();
AppPrint(g_stdout, "\n");
PrintPbkdf2Alg();
AppPrint(g_stdout, "\n");
PrintKdftls12Alg();
}
static void PrintAllAlg(void)
{
PrintCipherAlg();
AppPrint(g_stdout, "\n");
PrintMdAlg();
AppPrint(g_stdout, "\n");
PrintPkeyAlg();
AppPrint(g_stdout, "\n");
PrintMacAlg();
AppPrint(g_stdout, "\n");
PrintRandAlg();
AppPrint(g_stdout, "\n");
PrintKdfAlg();
}
static void PrintCurves(void)
{
AppPrint(g_stdout, "List Curves:\n");
AppPrint(g_stdout, "%-20s\t%s\n", "NAME", "CID");
for (size_t i = 0; i < CURVES_CNT; ++i) {
AppPrint(g_stdout, "%-20s\t%3zu\n", g_allCurves[i].name, g_allCurves[i].cid);
}
}
static int32_t ParseListOpt(void)
{
bool isEmptyOpt = true;
int optType = HITLS_APP_OPT_ERR;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
isEmptyOpt = false;
switch (optType) {
case HITLS_APP_OPT_HELP:
HITLS_APP_OptHelpPrint(g_listOpts);
return HITLS_APP_HELP;
case HITLS_APP_OPT_ERR:
AppPrintError("list: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_LIST_OPT_ALL_ALG:
AppPushPrintFunc(PrintAllAlg);
break;
case HITLS_APP_LIST_OPT_DGST_ALG:
AppPushPrintFunc(PrintMdAlg);
break;
case HITLS_APP_LIST_OPT_CIPHER_ALG:
AppPushPrintFunc(PrintCipherAlg);
break;
case HITLS_APP_LIST_OPT_ASYM_ALG:
AppPushPrintFunc(PrintPkeyAlg);
break;
case HITLS_APP_LIST_OPT_MAC_ALG:
AppPushPrintFunc(PrintMacAlg);
break;
case HITLS_APP_LIST_OPT_RAND_ALG:
AppPushPrintFunc(PrintRandAlg);
break;
case HITLS_APP_LIST_OPT_KDF_ALG:
AppPushPrintFunc(PrintKdfAlg);
break;
case HITLS_APP_LIST_OPT_CURVES:
AppPushPrintFunc(PrintCurves);
break;
default:
break;
}
}
// Get the number of parameters that cannot be parsed in the current version
// and print the error information and help list.
if ((HITLS_APP_GetRestOptNum() != 0) || isEmptyOpt) {
AppPrintError("Extra arguments given.\n");
AppPrintError("list: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
// List main function
int32_t HITLS_ListMain(int argc, char *argv[])
{
ResetPrintAlgFuncList();
int32_t ret = HITLS_APP_SUCCESS;
do {
ret = AppPrintStdoutUioInit();
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = HITLS_APP_OptBegin(argc, argv, g_listOpts);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
break;
}
ret = ParseListOpt();
if (ret != HITLS_APP_SUCCESS) {
break;
}
AppPrintList();
} while (false);
HITLS_APP_OptEnd();
AppPrintStdoutUioUnInit();
return ret;
}
static int32_t GetInfoByType(int32_t type, const CidInfo **cidInfos, uint32_t *cnt, char **typeName)
{
switch (type) {
case HITLS_APP_LIST_OPT_DGST_ALG:
*cidInfos = g_allMdAlgInfo;
*cnt = MD_ALG_CNT;
*typeName = "dgst";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_CIPHER_ALG:
*cidInfos = g_allCipherAlgInfo;
*cnt = CIPHER_ALG_CNT;
*typeName = "cipher";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_ASYM_ALG:
*cidInfos = g_allPkeyAlgInfo;
*cnt = PKEY_ALG_CNT;
*typeName = "asym";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_MAC_ALG:
*cidInfos = g_allMacAlgInfo;
*cnt = MAC_ALG_CNT;
*typeName = "mac";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_RAND_ALG:
*cidInfos = g_allRandAlgInfo;
*cnt = RAND_ALG_CNT;
*typeName = "rand";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_KDF_ALG:
*cidInfos = g_allKdfAlgInfo;
*cnt = KDF_ALG_CNT;
*typeName = "kdf";
return HITLS_APP_SUCCESS;
case HITLS_APP_LIST_OPT_CURVES:
*cidInfos = g_allCurves;
*cnt = CURVES_CNT;
*typeName = "curves";
return HITLS_APP_SUCCESS;
default:
return HITLS_APP_INVALID_ARG;
}
}
int32_t HITLS_APP_GetCidByName(const char *name, int32_t type)
{
if (name == NULL) {
return BSL_CID_UNKNOWN;
}
const CidInfo *cidInfos = NULL;
uint32_t cnt = 0;
char *typeName;
int32_t ret = GetInfoByType(type, &cidInfos, &cnt, &typeName);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Get cid info by name failed, name: %s\n", name);
return BSL_CID_UNKNOWN;
}
for (size_t i = 0; i < cnt; ++i) {
if (strcmp(name, cidInfos[i].name) == 0) {
return (BslCid)cidInfos[i].cid;
}
}
AppPrintError("Unsupport %s: %s\n", typeName, name);
return BSL_CID_UNKNOWN;
}
const char *HITLS_APP_GetNameByCid(int32_t cid, int32_t type)
{
const CidInfo *cidInfos = NULL;
uint32_t cnt = 0;
char *typeName;
int32_t ret = GetInfoByType(type, &cidInfos, &cnt, &typeName);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Get cid info by cid failed, cid: %d\n", cid);
return NULL;
}
for (size_t i = 0; i < cnt; ++i) {
if (cid == cidInfos[i].cid) {
return cidInfos[i].name;
}
}
AppPrintError("Unsupport %s: %d\n", typeName, cid);
return NULL;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_list.c | C | unknown | 17,895 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_mac.h"
#include <linux/limits.h>
#include "string.h"
#include "securec.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_eal_mac.h"
#include "bsl_errno.h"
#include "app_opt.h"
#include "app_function.h"
#include "app_list.h"
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_provider.h"
#include "app_utils.h"
#define MAX_BUFSIZE (1024 * 8) // Indicates the length of a single mac during mac calculation.
#define IS_SUPPORT_GET_EOF 1
#define MAC_MAX_KEY_LEN 64
#define MAC_MAX_IV_LENGTH 16
typedef enum OptionChoice {
HITLS_APP_OPT_MAC_ERR = -1,
HITLS_APP_OPT_MAC_EOF = 0,
HITLS_APP_OPT_MAC_HELP = 1, // The value of the help type of each opt option is 1. The following can be customized.
HITLS_APP_OPT_MAC_ALG,
HITLS_APP_OPT_MAC_IN,
HITLS_APP_OPT_MAC_OUT,
HITLS_APP_OPT_MAC_BINARY,
HITLS_APP_OPT_MAC_KEY,
HITLS_APP_OPT_MAC_HEXKEY,
HITLS_APP_OPT_MAC_IV,
HITLS_APP_OPT_MAC_HEXIV,
HITLS_APP_OPT_MAC_TAGLEN,
HITLS_APP_PROV_ENUM
} HITLSOptType;
const HITLS_CmdOption g_macOpts[] = {
{"help", HITLS_APP_OPT_MAC_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Show usage information for MAC command."},
{"name", HITLS_APP_OPT_MAC_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Specify MAC algorithm (e.g., hmac-sha256)."},
{"in", HITLS_APP_OPT_MAC_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE,
"Set input file for MAC computation (default: stdin)."},
{"out", HITLS_APP_OPT_MAC_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE,
"Set output file for MAC result (default: stdout)."},
{"binary", HITLS_APP_OPT_MAC_BINARY, HITLS_APP_OPT_VALUETYPE_NO_VALUE,
"Output MAC result in binary format."},
{"key", HITLS_APP_OPT_MAC_KEY, HITLS_APP_OPT_VALUETYPE_STRING,
"Input encryption key as a string."},
{"hexkey", HITLS_APP_OPT_MAC_HEXKEY, HITLS_APP_OPT_VALUETYPE_STRING,
"Input encryption key in hexadecimal format (e.g., 0x1234ABCD)."},
{"iv", HITLS_APP_OPT_MAC_IV, HITLS_APP_OPT_VALUETYPE_STRING,
"Input initialization vector as a string."},
{"hexiv", HITLS_APP_OPT_MAC_HEXIV, HITLS_APP_OPT_VALUETYPE_STRING,
"Input initialization vector in hexadecimal format (e.g., 0xAABBCCDD)."},
{"taglen", HITLS_APP_OPT_MAC_TAGLEN, HITLS_APP_OPT_VALUETYPE_INT,
"Set authentication tag length."},
HITLS_APP_PROV_OPTIONS,
{NULL}};
typedef struct {
int32_t algId;
uint32_t macSize;
uint32_t isBinary;
char *inFile;
uint8_t readBuf[MAX_BUFSIZE];
uint32_t readLen;
char *outFile;
char *key;
char *hexKey;
uint32_t keyLen;
char *iv;
char *hexIv;
uint32_t tagLen;
AppProvider *provider;
} MacOpt;
typedef int32_t (*MacOptHandleFunc)(MacOpt *);
typedef struct {
int32_t optType;
MacOptHandleFunc func;
} MacOptHandleFuncMap;
static int32_t MacOptErr(MacOpt *macOpt)
{
(void)macOpt;
AppPrintError("mac: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t MacOptHelp(MacOpt *macOpt)
{
(void)macOpt;
HITLS_APP_OptHelpPrint(g_macOpts);
return HITLS_APP_HELP;
}
static int32_t MacOptIn(MacOpt *macOpt)
{
macOpt->inFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t MacOptOut(MacOpt *macOpt)
{
macOpt->outFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t MacOptKey(MacOpt *macOpt)
{
macOpt->key = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t MacOptHexKey(MacOpt *macOpt)
{
macOpt->hexKey = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t MacOptIv(MacOpt *macOpt)
{
macOpt->iv = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t MacOptHexIv(MacOpt *macOpt)
{
macOpt->hexIv = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t MacOptBinary(MacOpt *macOpt)
{
macOpt->isBinary = 1;
return HITLS_APP_SUCCESS;
}
static int32_t MacOptTagLen(MacOpt *macOpt)
{
int32_t ret = HITLS_APP_OptGetUint32(HITLS_APP_OptGetValueStr(), &(macOpt->tagLen));
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("mac: Invalid tagLen value.\n");
}
return ret;
}
static int32_t MacOptAlg(MacOpt *macOpt)
{
char *algName = HITLS_APP_OptGetValueStr();
if (algName == NULL) {
return HITLS_APP_OPT_VALUE_INVALID;
}
macOpt->algId = HITLS_APP_GetCidByName(algName, HITLS_APP_LIST_OPT_MAC_ALG);
if (macOpt->algId == BSL_CID_UNKNOWN) {
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static const MacOptHandleFuncMap g_macOptHandleFuncMap[] = {
{HITLS_APP_OPT_MAC_ERR, MacOptErr},
{HITLS_APP_OPT_MAC_HELP, MacOptHelp},
{HITLS_APP_OPT_MAC_IN, MacOptIn},
{HITLS_APP_OPT_MAC_OUT, MacOptOut},
{HITLS_APP_OPT_MAC_KEY, MacOptKey},
{HITLS_APP_OPT_MAC_HEXKEY, MacOptHexKey},
{HITLS_APP_OPT_MAC_IV, MacOptIv},
{HITLS_APP_OPT_MAC_HEXIV, MacOptHexIv},
{HITLS_APP_OPT_MAC_BINARY, MacOptBinary},
{HITLS_APP_OPT_MAC_TAGLEN, MacOptTagLen},
{HITLS_APP_OPT_MAC_ALG, MacOptAlg},
};
static int32_t ParseMacOpt(MacOpt *macOpt)
{
int ret = HITLS_APP_SUCCESS;
int optType = HITLS_APP_OPT_MAC_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_MAC_EOF)) {
for (size_t i = 0; i < sizeof(g_macOptHandleFuncMap) / sizeof(g_macOptHandleFuncMap[0]); ++i) {
if (optType == g_macOptHandleFuncMap[i].optType) {
ret = g_macOptHandleFuncMap[i].func(macOpt);
break;
}
}
HITLS_APP_PROV_CASES(optType, macOpt->provider);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
}
if (HITLS_APP_GetRestOptNum() != 0) {
AppPrintError("Extra arguments given.\n");
AppPrintError("mac: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckParam(MacOpt *macOpt)
{
if (macOpt->algId < 0) {
macOpt->algId = CRYPT_MAC_HMAC_SHA256;
}
if (macOpt->key == NULL && macOpt->hexKey == NULL) {
AppPrintError("mac: No key entered.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (macOpt->key != NULL && macOpt->hexKey != NULL) {
AppPrintError("mac: Cannot specify both key and hexkey.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (macOpt->algId >= CRYPT_MAC_GMAC_AES128 && macOpt->algId <= CRYPT_MAC_GMAC_AES256) {
if (macOpt->iv == NULL && macOpt->hexIv == NULL) {
AppPrintError("mac: No iv entered.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (macOpt->iv != NULL && macOpt->hexIv != NULL) {
AppPrintError("mac: Cannot specify both iv and hexiv.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
} else {
if (macOpt->iv != NULL || macOpt->hexIv != NULL) {
AppPrintError("mac: iv is not supported for this algorithm.\n");
BSL_SAL_FREE(macOpt->iv);
BSL_SAL_FREE(macOpt->hexIv);
}
}
if (macOpt->inFile != NULL && strlen((const char*)macOpt->inFile) > PATH_MAX) {
AppPrintError("mac: The input file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (macOpt->outFile != NULL && strlen((const char*)macOpt->outFile) > PATH_MAX) {
AppPrintError("mac: The output file length is invalid.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static CRYPT_EAL_MacCtx *InitAlgMac(MacOpt *macOpt)
{
uint8_t *key = NULL;
uint32_t keyLen = MAC_MAX_KEY_LEN;
int32_t ret;
if (macOpt->key != NULL) {
keyLen = strlen((const char*)macOpt->key);
key = (uint8_t*)macOpt->key;
} else if (macOpt->hexKey != NULL) {
ret = HITLS_APP_HexToByte(macOpt->hexKey, &key, &keyLen);
if (ret == HITLS_APP_OPT_VALUE_INVALID) {
AppPrintError("mac:Invalid key: %s.\n", macOpt->hexKey);
return NULL;
}
}
CRYPT_EAL_MacCtx *ctx = NULL;
do {
ret = HITLS_APP_LoadProvider(macOpt->provider->providerPath, macOpt->provider->providerName);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ctx = CRYPT_EAL_ProviderMacNewCtx(APP_GetCurrent_LibCtx(), macOpt->algId,
macOpt->provider->providerAttr); // creating an MAC Context
if (ctx == NULL) {
(void)AppPrintError("mac:Failed to create the algorithm(%d) context\n", macOpt->algId);
break;
}
ret = CRYPT_EAL_MacInit(ctx, key, keyLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("mac:Summary context creation failed, ret=%d\n", ret);
CRYPT_EAL_MacFreeCtx(ctx);
ctx = NULL;
break;
}
} while (0);
if (macOpt->hexKey != NULL) {
BSL_SAL_FREE(key);
}
return ctx;
}
static int32_t MacParamSet(CRYPT_EAL_MacCtx *ctx, MacOpt *macOpt)
{
int32_t ret = HITLS_APP_SUCCESS;
uint8_t *iv = NULL;
uint32_t padding = CRYPT_PADDING_ZEROS;
uint32_t ivLen = MAC_MAX_IV_LENGTH;
if (macOpt->algId == CRYPT_MAC_CBC_MAC_SM4) {
ret = CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_CBC_MAC_PADDING, &padding, sizeof(CRYPT_PaddingType));
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("mac:Failed to set CBC MAC padding, ret=%d\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
}
if (macOpt->algId >= CRYPT_MAC_GMAC_AES128 && macOpt->algId <= CRYPT_MAC_GMAC_AES256) {
if (macOpt->iv != NULL) {
ivLen = strlen((const char*)macOpt->iv);
iv = (uint8_t *)macOpt->iv;
} else {
ret = HITLS_APP_HexToByte(macOpt->hexIv, &iv, &ivLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("mac: Invalid iv: %s.\n", macOpt->hexIv);
return ret;
}
}
do {
ret = CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_IV, macOpt->iv, ivLen);
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("mac:Failed to set GMAC IV, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = CRYPT_EAL_MacCtrl(ctx, CRYPT_CTRL_SET_TAGLEN, &(macOpt->tagLen), sizeof(int32_t));
if (ret != CRYPT_SUCCESS) {
(void)AppPrintError("mac:Failed to set GMAC TAGLEN, ret=%d\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
} while (0);
if (macOpt->hexIv != NULL) {
BSL_SAL_FREE(iv);
}
}
return ret;
}
static int32_t GetReadBuf(CRYPT_EAL_MacCtx *ctx, MacOpt *macOpt)
{
int32_t ret;
bool isEof = false;
uint32_t readLen = 0;
uint64_t readFileLen = 0;
uint8_t *tmpBuf = (uint8_t *)BSL_SAL_Calloc(MAX_BUFSIZE, sizeof(uint8_t));
if (tmpBuf == NULL) {
AppPrintError("mac: Failed to allocate read buffer.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
BSL_UIO *readUio = HITLS_APP_UioOpen(macOpt->inFile, 'r', 0);
BSL_UIO_SetIsUnderlyingClosedByUio(readUio, true);
if (readUio == NULL) {
if (macOpt->inFile == NULL) {
AppPrintError("mac: Failed to open stdin\n");
} else {
AppPrintError("mac: Failed to open the file <%s>, No such file or directory\n", macOpt->inFile);
}
BSL_SAL_FREE(tmpBuf);
return HITLS_APP_UIO_FAIL;
}
if (macOpt->inFile == NULL) {
while (BSL_UIO_Ctrl(readUio, BSL_UIO_FILE_GET_EOF, IS_SUPPORT_GET_EOF, &isEof) == BSL_SUCCESS && !isEof) {
if (BSL_UIO_Read(readUio, tmpBuf, MAX_BUFSIZE, &readLen) != BSL_SUCCESS) {
BSL_SAL_FREE(tmpBuf);
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to obtain the content from the STDIN\n");
return HITLS_APP_STDIN_FAIL;
}
if (readLen == 0) {
break;
}
ret = CRYPT_EAL_MacUpdate(ctx, tmpBuf, readLen);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(tmpBuf);
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to continuously summarize the STDIN content\n");
return HITLS_APP_CRYPTO_FAIL;
}
}
} else {
ret = BSL_UIO_Ctrl(readUio, BSL_UIO_PENDING, sizeof(readFileLen), &readFileLen);
if (ret != BSL_SUCCESS) {
BSL_SAL_FREE(tmpBuf);
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to obtain the content length\n");
return HITLS_APP_UIO_FAIL;
}
while (readFileLen > 0) {
uint32_t bufLen = (readFileLen > MAX_BUFSIZE) ? MAX_BUFSIZE : (uint32_t)readFileLen;
ret = BSL_UIO_Read(readUio, tmpBuf, bufLen, &readLen); // read content to memory
if (ret != BSL_SUCCESS || bufLen != readLen) {
BSL_SAL_FREE(tmpBuf);
BSL_UIO_Free(readUio);
(void)AppPrintError("Failed to read the input content\n");
return HITLS_APP_UIO_FAIL;
}
ret = CRYPT_EAL_MacUpdate(ctx, tmpBuf, bufLen); // continuously enter summary content
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(tmpBuf);
BSL_UIO_Free(readUio);
(void)AppPrintError("mac: Failed to update MAC with file content, error code: %d\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
readFileLen -= bufLen;
}
}
BSL_UIO_Free(readUio);
BSL_SAL_FREE(tmpBuf);
return HITLS_APP_SUCCESS;
}
static int32_t MacResult(CRYPT_EAL_MacCtx *ctx, MacOpt *macOpt)
{
uint8_t *outBuf = NULL;
BSL_UIO *fileWriteUio = HITLS_APP_UioOpen(macOpt->outFile, 'w', 0); // overwrite the original content
BSL_UIO_SetIsUnderlyingClosedByUio(fileWriteUio, true);
if (fileWriteUio == NULL) {
(void)AppPrintError("Failed to open the outfile\n");
return HITLS_APP_UIO_FAIL;
}
uint32_t macSize = CRYPT_EAL_GetMacLen(ctx);
if (macSize <= 0) {
AppPrintError("mac: Invalid MAC size: %u\n", macSize);
BSL_UIO_Free(fileWriteUio);
return HITLS_APP_CRYPTO_FAIL;
}
outBuf = (uint8_t *)BSL_SAL_Calloc(macSize, sizeof(uint8_t));
if (outBuf == NULL) {
AppPrintError("mac: Failed to allocate MAC buffer.\n");
BSL_UIO_Free(fileWriteUio);
return HITLS_APP_MEM_ALLOC_FAIL;
}
uint32_t macBufLen = macSize;
int32_t ret = CRYPT_EAL_MacFinal(ctx, outBuf, &macBufLen);
if (ret != CRYPT_SUCCESS || macBufLen < macSize) {
BSL_SAL_FREE(outBuf);
(void)AppPrintError("mac: Failed to complete the final summary. ERR:%d\n", ret);
BSL_UIO_Free(fileWriteUio);
return HITLS_APP_CRYPTO_FAIL;
}
ret = HITLS_APP_OptWriteUio(fileWriteUio, outBuf, macBufLen,
macOpt->isBinary == 1 ? HITLS_APP_FORMAT_TEXT: HITLS_APP_FORMAT_HEX);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("mac:Failed to export data to the outfile path\n");
}
BSL_UIO_Free(fileWriteUio);
BSL_SAL_FREE(outBuf);
return ret;
}
int32_t HITLS_MacMain(int argc, char *argv[])
{
int32_t mainRet = HITLS_APP_SUCCESS;
AppProvider appProvider = {"default", NULL, "provider=default"};
MacOpt macOpt = {CRYPT_MAC_HMAC_SHA256, 0, 0, NULL, {0}, 0, NULL, NULL, NULL, 0, NULL, NULL, 0, &appProvider};
CRYPT_EAL_MacCtx *ctx = NULL;
do {
mainRet = HITLS_APP_OptBegin(argc, argv, g_macOpts);
if (mainRet != HITLS_APP_SUCCESS) {
HITLS_APP_OptEnd();
(void)AppPrintError("error in opt begin.\n");
break;
}
mainRet = ParseMacOpt(&macOpt);
if (mainRet != HITLS_APP_SUCCESS) {
HITLS_APP_OptEnd();
break;
}
HITLS_APP_OptEnd();
mainRet = CheckParam(&macOpt);
if (mainRet != HITLS_APP_SUCCESS) {
break;
}
ctx = InitAlgMac(&macOpt);
if (ctx == NULL) {
mainRet = HITLS_APP_CRYPTO_FAIL;
break;
}
mainRet = MacParamSet(ctx, &macOpt);
if (mainRet != CRYPT_SUCCESS) {
(void)AppPrintError("mac:Failed to set mac params\n");
break;
}
mainRet = GetReadBuf(ctx, &macOpt);
if (mainRet != HITLS_APP_SUCCESS) {
break;
}
mainRet = MacResult(ctx, &macOpt);
} while (0);
CRYPT_EAL_MacDeinit(ctx); // algorithm release
CRYPT_EAL_MacFreeCtx(ctx);
HITLS_APP_OptEnd();
return mainRet;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_mac.c | C | unknown | 17,333 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_opt.h"
#include <stdint.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <errno.h>
#include <libgen.h>
#include <sys/stat.h>
#include <stdbool.h>
#include "securec.h"
#include "app_errno.h"
#include "bsl_sal.h"
#include "app_print.h"
#include "bsl_uio.h"
#include "bsl_errno.h"
#include "bsl_base64.h"
#define MAX_HITLS_APP_OPT_NAME_WIDTH 40
#define MAX_HITLS_APP_OPT_LINE_WIDTH 80
typedef struct {
int32_t optIndex;
int32_t argc;
char *valueStr;
char progName[128];
char **argv;
const HITLS_CmdOption *opts;
} HITLS_CmdOptState;
static HITLS_CmdOptState g_cmdOptState = {0};
static const HITLS_CmdOption *g_unKnownOpt = NULL;
static char *g_unKownName = NULL;
const char *HITLS_APP_OptGetUnKownOptName(void)
{
return g_unKownName;
}
static void GetProgName(const char *filePath)
{
const char *p = NULL;
for (p = filePath + strlen(filePath); --p > filePath;) {
if (*p == '/') {
p++;
break;
}
}
// Avoid consistency between source and destination addresses.
if (p != g_cmdOptState.progName) {
(void)strncpy_s(
g_cmdOptState.progName, sizeof(g_cmdOptState.progName) - 1, p, sizeof(g_cmdOptState.progName) - 1);
}
g_cmdOptState.progName[sizeof(g_cmdOptState.progName) - 1] = '\0';
}
static void CmdOptStateInit(int32_t index, int32_t argc, char **argv, const HITLS_CmdOption *opts)
{
g_cmdOptState.optIndex = index;
g_cmdOptState.argc = argc;
g_cmdOptState.argv = argv;
g_cmdOptState.opts = opts;
(void)memset_s(g_cmdOptState.progName, sizeof(g_cmdOptState.progName), 0, sizeof(g_cmdOptState.progName));
}
static void CmdOptStateClear(void)
{
g_cmdOptState.optIndex = 0;
g_cmdOptState.argc = 0;
g_cmdOptState.argv = NULL;
g_cmdOptState.opts = NULL;
(void)memset_s(g_cmdOptState.progName, sizeof(g_cmdOptState.progName), 0, sizeof(g_cmdOptState.progName));
}
char *HITLS_APP_GetProgName(void)
{
return g_cmdOptState.progName;
}
int32_t HITLS_APP_OptBegin(int32_t argc, char **argv, const HITLS_CmdOption *opts)
{
if (argc == 0 || argv == NULL || opts == NULL) {
(void)AppPrintError("incorrect command \n");
return HITLS_APP_OPT_UNKOWN;
}
// init cmd option state
CmdOptStateInit(1, argc, argv, opts);
GetProgName(argv[0]);
g_unKnownOpt = NULL;
const HITLS_CmdOption *opt = opts;
// Check all opts before using them
for (; opt->name != NULL; ++opt) {
if ((strlen(opt->name) == 0) && (opt->valueType == HITLS_APP_OPT_VALUETYPE_NO_VALUE)) {
g_unKnownOpt = opt;
} else if ((strlen(opt->name) == 0) || (opt->name[0] == '-')) {
(void)AppPrintError("Invalid optname %s \n", opt->name);
return HITLS_APP_OPT_NAME_INVALID;
}
if (opt->valueType <= HITLS_APP_OPT_VALUETYPE_NONE || opt->valueType >= HITLS_APP_OPT_VALUETYPE_MAX) {
return HITLS_APP_OPT_VALUETYPE_INVALID;
}
if (opt->valueType == HITLS_APP_OPT_VALUETYPE_PARAMTERS && opt->optType != HITLS_APP_OPT_PARAM) {
return HITLS_APP_OPT_TYPE_INVALID;
}
for (const HITLS_CmdOption *nextOpt = opt + 1; nextOpt->name != NULL; ++nextOpt) {
if (strcmp(opt->name, nextOpt->name) == 0) {
(void)AppPrintError("Invalid duplicate name : %s\n", opt->name);
return HITLS_APP_OPT_NAME_INVALID;
}
}
}
return HITLS_APP_SUCCESS;
}
char *HITLS_APP_OptGetValueStr(void)
{
return g_cmdOptState.valueStr;
}
static int32_t IsDir(const char *path)
{
struct stat st = {0};
if (path == NULL) {
return HITLS_APP_OPT_VALUE_INVALID;
}
if (stat(path, &st) != 0) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
if (S_ISDIR(st.st_mode)) {
return HITLS_APP_SUCCESS;
}
return HITLS_APP_OPT_VALUE_INVALID;
}
int32_t HITLS_APP_OptGetLong(const char *valueS, long *valueL)
{
char *endPtr = NULL;
errno = 0;
long l = strtol(valueS, &endPtr, 0);
if (strlen(endPtr) > 0 || endPtr == valueS || (l == LONG_MAX || l == LONG_MIN) || errno == ERANGE ||
(l == 0 && errno != 0)) {
(void)AppPrintError("The parameter: %s is not a number or out of range\n", valueS);
return HITLS_APP_OPT_VALUE_INVALID;
}
*valueL = l;
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptGetInt(const char *valueS, int32_t *valueI)
{
long valueL = 0;
if (HITLS_APP_OptGetLong(valueS, &valueL) != HITLS_APP_SUCCESS) {
return HITLS_APP_OPT_VALUE_INVALID;
}
*valueI = (int32_t)valueL;
// value outside integer range
if ((long)(*valueI) != valueL) {
(void)AppPrintError("The number %ld out the int bound \n", valueL);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptGetUint32(const char *valueS, uint32_t *valueU)
{
long valueL = 0;
if (HITLS_APP_OptGetLong(valueS, &valueL) != HITLS_APP_SUCCESS) {
return HITLS_APP_OPT_VALUE_INVALID;
}
*valueU = (uint32_t)valueL;
// value outside integer range
if ((long)(*valueU) != valueL) {
(void)AppPrintError("The number %ld out the int bound \n", valueL);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptGetFormatType(const char *valueS, HITLS_ValueType type, BSL_ParseFormat *formatType)
{
if (type != HITLS_APP_OPT_VALUETYPE_FMT_PEMDER && type != HITLS_APP_OPT_VALUETYPE_FMT_ANY) {
(void)AppPrintError("Invalid Format Type\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (strcasecmp(valueS, "DER") == 0) {
*formatType = BSL_FORMAT_ASN1;
return HITLS_APP_SUCCESS;
} else if (strcasecmp(valueS, "PEM") == 0) {
*formatType = BSL_FORMAT_PEM;
return HITLS_APP_SUCCESS;
}
(void)AppPrintError("Invalid format \"%s\".\n", valueS);
return HITLS_APP_OPT_VALUE_INVALID;
}
int32_t HITLS_APP_GetRestOptNum(void)
{
return g_cmdOptState.argc - g_cmdOptState.optIndex;
}
char **HITLS_APP_GetRestOpt(void)
{
return &g_cmdOptState.argv[g_cmdOptState.optIndex];
}
static int32_t ClassifyByValue(HITLS_ValueType value)
{
switch (value) {
case HITLS_APP_OPT_VALUETYPE_IN_FILE:
case HITLS_APP_OPT_VALUETYPE_OUT_FILE:
case HITLS_APP_OPT_VALUETYPE_STRING:
case HITLS_APP_OPT_VALUETYPE_PARAMTERS:
return HITLS_APP_OPT_VALUECLASS_STR;
case HITLS_APP_OPT_VALUETYPE_DIR:
return HITLS_APP_OPT_VALUECLASS_DIR;
case HITLS_APP_OPT_VALUETYPE_INT:
case HITLS_APP_OPT_VALUETYPE_UINT:
case HITLS_APP_OPT_VALUETYPE_POSITIVE_INT:
return HITLS_APP_OPT_VALUECLASS_INT;
case HITLS_APP_OPT_VALUETYPE_LONG:
case HITLS_APP_OPT_VALUETYPE_ULONG:
return HITLS_APP_OPT_VALUECLASS_LONG;
case HITLS_APP_OPT_VALUETYPE_FMT_PEMDER:
case HITLS_APP_OPT_VALUETYPE_FMT_ANY:
return HITLS_APP_OPT_VALUECLASS_FMT;
default:
return HITLS_APP_OPT_VALUECLASS_NO_VALUE;
}
return HITLS_APP_OPT_VALUECLASS_NONE;
}
static int32_t CheckOptValueType(const HITLS_CmdOption *opt, const char *valStr)
{
int32_t valueClass = ClassifyByValue(opt->valueType);
switch (valueClass) {
case HITLS_APP_OPT_VALUECLASS_STR:
break;
case HITLS_APP_OPT_VALUECLASS_DIR: {
if (IsDir(valStr) != HITLS_APP_SUCCESS) {
AppPrintError("%s: Invalid dir \"%s\" for -%s\n", g_cmdOptState.progName, valStr, opt->name);
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
}
case HITLS_APP_OPT_VALUECLASS_INT: {
int32_t valueI = 0;
if (HITLS_APP_OptGetInt(valStr, &valueI) != HITLS_APP_SUCCESS ||
(opt->valueType == HITLS_APP_OPT_VALUETYPE_UINT && valueI < 0) ||
(opt->valueType == HITLS_APP_OPT_VALUETYPE_POSITIVE_INT && valueI < 0)) {
AppPrintError("%s: Invalid number \"%s\" for -%s\n", g_cmdOptState.progName, valStr, opt->name);
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
}
case HITLS_APP_OPT_VALUECLASS_LONG: {
long valueL = 0;
if (HITLS_APP_OptGetLong(valStr, &valueL) != HITLS_APP_SUCCESS ||
(opt->valueType == HITLS_APP_OPT_VALUETYPE_LONG && valueL < 0)) {
AppPrintError("%s: Invalid number \"%s\" for -%s\n", g_cmdOptState.progName, valStr, opt->name);
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
}
case HITLS_APP_OPT_VALUECLASS_FMT: {
BSL_ParseFormat formatType = 0;
if (HITLS_APP_OptGetFormatType(valStr, opt->valueType, &formatType) != HITLS_APP_SUCCESS) {
AppPrintError("%s: Invalid format \"%s\" for -%s\n", g_cmdOptState.progName, valStr, opt->name);
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
}
default:
AppPrintError("%s: Invalid arg \"%s\" for -%s\n", g_cmdOptState.progName, valStr, opt->name);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptNext(void)
{
char *optName = g_cmdOptState.argv[g_cmdOptState.optIndex];
if (optName == NULL || *optName != '-') {
return HITLS_APP_OPT_EOF;
}
g_cmdOptState.optIndex++;
// optName only contain '-' or '--'
if (strcmp(optName, "-") == 0 || strcmp(optName, "--") == 0) {
return HITLS_APP_OPT_ERR;
}
if (*(++optName) == '-') {
optName++;
}
// case: key=value do not support
g_cmdOptState.valueStr = strchr(optName, '=');
if (g_cmdOptState.valueStr != NULL) {
return HITLS_APP_OPT_ERR;
}
for (const HITLS_CmdOption *opt = g_cmdOptState.opts; opt->name; ++opt) {
if (strcmp(optName, opt->name) != 0) {
continue;
}
// case: opt doesn't have value
if (opt->valueType == HITLS_APP_OPT_VALUETYPE_NO_VALUE) {
if (g_cmdOptState.valueStr != NULL) {
AppPrintError("%s does not take a value\n", opt->name);
return HITLS_APP_OPT_ERR;
}
return opt->optType;
}
// case: opt should has value
if (g_cmdOptState.valueStr == NULL) {
if (g_cmdOptState.argv[g_cmdOptState.optIndex] == NULL) {
AppPrintError("%s needs a value\n", opt->name);
return HITLS_APP_OPT_ERR;
}
g_cmdOptState.valueStr = g_cmdOptState.argv[g_cmdOptState.optIndex];
g_cmdOptState.optIndex++;
}
if (CheckOptValueType(opt, g_cmdOptState.valueStr) != HITLS_APP_SUCCESS) {
return HITLS_APP_OPT_ERR;
}
return opt->optType;
}
if (g_unKnownOpt != NULL) {
g_unKownName = optName;
return g_unKnownOpt->optType;
}
AppPrintError("%s: Unknown option: -%s\n", g_cmdOptState.progName, optName);
return HITLS_APP_OPT_ERR;
}
struct {
HITLS_ValueType type;
char *param;
} g_valTypeParam[] = {
{HITLS_APP_OPT_VALUETYPE_IN_FILE, "infile"},
{HITLS_APP_OPT_VALUETYPE_OUT_FILE, "outfile"},
{HITLS_APP_OPT_VALUETYPE_STRING, "val"},
{HITLS_APP_OPT_VALUETYPE_PARAMTERS, ""},
{HITLS_APP_OPT_VALUETYPE_DIR, "dir"},
{HITLS_APP_OPT_VALUETYPE_INT, "int"},
{HITLS_APP_OPT_VALUETYPE_UINT, "uint"},
{HITLS_APP_OPT_VALUETYPE_POSITIVE_INT, "uint(>0)"},
{HITLS_APP_OPT_VALUETYPE_LONG, "long"},
{HITLS_APP_OPT_VALUETYPE_ULONG, "ulong"},
{HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "PEM|DER"},
{HITLS_APP_OPT_VALUETYPE_FMT_ANY, "format"}
};
/* Return a string describing the parameter type. */
static const char *ValueType2Param(HITLS_ValueType type)
{
for (int i = 0; i <= (int)sizeof(g_valTypeParam); i++) {
if (type == g_valTypeParam[i].type)
return g_valTypeParam[i].param;
}
return "";
}
static void OptPrint(const HITLS_CmdOption *opt, int width)
{
const char *help = opt->help ? opt->help : "";
char start[MAX_HITLS_APP_OPT_LINE_WIDTH + 1] = {0};
(void)memset_s(start, sizeof(start) - 1, ' ', sizeof(start) - 1);
start[sizeof(start) - 1] = '\0';
int pos = 0;
start[pos++] = ' ';
if (opt->valueType != HITLS_APP_OPT_VALUETYPE_PARAMTERS) {
start[pos++] = '-';
} else {
start[pos++] = '[';
}
if (strlen(opt->name) > 0) {
if (EOK == strncpy_s(&start[pos], sizeof(start) - pos - 1, opt->name, strlen(opt->name))) {
pos += strlen(opt->name);
}
(void)memset_s(&start[pos + 1], sizeof(start) - 1 - pos - 1, ' ', sizeof(start) - 1 - pos - 1);
} else {
start[pos++] = '*';
}
if (opt->valueType == HITLS_APP_OPT_VALUETYPE_PARAMTERS) {
start[pos++] = ']';
}
if (opt->valueType != HITLS_APP_OPT_VALUETYPE_NO_VALUE) {
start[pos++] = ' ';
const char *param = ValueType2Param(opt->valueType);
if (strncpy_s(&start[pos], sizeof(start) - pos - 1, param, strlen(param)) == EOK) {
pos += strlen(param);
}
(void)memset_s(&start[pos + 1], sizeof(start) - 1 - pos - 1, ' ', sizeof(start) - 1 - pos - 1);
}
start[pos++] = ' ';
if (pos >= MAX_HITLS_APP_OPT_NAME_WIDTH) {
start[pos] = '\0';
(void)AppPrintError("%s\n", start);
(void)memset_s(start, sizeof(start) - 1, ' ', sizeof(start) - 1);
}
start[width] = '\0';
(void)AppPrintError("%s %s\n", start, help);
}
void HITLS_APP_OptHelpPrint(const HITLS_CmdOption *opts)
{
int width = 5;
int len = 0;
const HITLS_CmdOption *opt;
for (opt = opts; opt->name != NULL; opt++) {
len = 1 + (int)strlen(opt->name) + 1; // '-' + name + space
if (opt->valueType != HITLS_APP_OPT_VALUETYPE_NO_VALUE) {
len += 1 + strlen(ValueType2Param(opt->valueType));
}
if (len < MAX_HITLS_APP_OPT_NAME_WIDTH && len > width) {
width = len;
}
}
(void)AppPrintError("Usage: %s \n", g_cmdOptState.progName);
for (opt = opts; opt->name != NULL; opt++) {
(void)OptPrint(opt, width);
}
}
void HITLS_APP_OptEnd(void)
{
CmdOptStateClear();
}
BSL_UIO *HITLS_APP_UioOpen(const char *filename, char mode, int32_t flag)
{
if (mode != 'w' && mode != 'r' && mode != 'a') {
(void)AppPrintError("Invalid mode, only support a/w/r\n");
return NULL;
}
BSL_UIO *uio = BSL_UIO_New(BSL_UIO_FileMethod());
if (uio == NULL) {
return uio;
}
int32_t cmd = 0;
int32_t larg = 0;
void *parg = NULL;
if (filename == NULL) {
cmd = BSL_UIO_FILE_PTR;
larg = flag;
switch (mode) {
case 'w': parg = (void *)stdout;
break;
case 'r': parg = (void *)stdin;
break;
default:
BSL_UIO_Free(uio);
(void)AppPrintError("Only standard I/O is supported\n");
return NULL;
}
} else {
parg = (void *)(uintptr_t)filename;
cmd = BSL_UIO_FILE_OPEN;
switch (mode) {
case 'w': larg = BSL_UIO_FILE_WRITE;
break;
case 'r': larg = BSL_UIO_FILE_READ;
break;
case 'a': larg = BSL_UIO_FILE_APPEND;
break;
default:
BSL_UIO_Free(uio);
(void)AppPrintError("Only standard I/O is supported\n");
return NULL;
}
}
int32_t ctrlRet = BSL_UIO_Ctrl(uio, cmd, larg, parg);
if (ctrlRet != BSL_SUCCESS) {
(void)AppPrintError("Failed to bind the filepath\n");
BSL_UIO_Free(uio);
uio = NULL;
}
return uio;
}
int32_t HITLS_APP_OptToBase64(uint8_t *inBuf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen)
{
if (inBuf == NULL || outBuf == NULL || inBufLen == 0 || outBufLen == 0) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
// encode conversion
int32_t encodeRet = BSL_BASE64_Encode(inBuf, inBufLen, outBuf, &outBufLen);
if (encodeRet != BSL_SUCCESS) {
(void)AppPrintError("Failed to convert to Base64 format\n");
return HITLS_APP_ENCODE_FAIL;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptToHex(uint8_t *inBuf, uint32_t inBufLen, char *outBuf, uint32_t outBufLen)
{
if (inBuf == NULL || outBuf == NULL || inBufLen == 0 || outBufLen == 0) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
// One byte is encoded into hex and becomes 2 bytes.
int32_t hexCharSize = 2;
char midBuf[outBufLen + 1]; // snprint_s will definitely increase '\ 0'
for (uint32_t i = 0; i < inBufLen; ++i) {
int ret = snprintf_s(midBuf + i * hexCharSize, outBufLen + 1, outBufLen, "%02x", inBuf[i]);
if (ret == -1) {
(void)AppPrintError("Failed to convert to hex format\n");
return HITLS_APP_ENCODE_FAIL;
}
}
if (memcpy_s(outBuf, outBufLen, midBuf, strlen(midBuf)) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptWriteUio(BSL_UIO *uio, uint8_t *buf, uint32_t bufLen, int32_t format)
{
if (buf == NULL || uio == NULL || bufLen == 0) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
uint32_t outBufLen = 0;
uint32_t writeLen = 0;
switch (format) {
case HITLS_APP_FORMAT_BASE64:
/* In the Base64 format, three 8-bit bytes are converted into four 6-bit bytes. Therefore, the length
of the data in the Base64 format must be at least (Length of the original data + 2)/3 x 4 + 1.
The original data length plus 2 is used to ensure that
the remainder of buflen divided by 3 after rounding down is not lost. */
outBufLen = (bufLen + 2) / 3 * 4 + 1;
break;
// One byte is encoded into hex and becomes 2 bytes.
case HITLS_APP_FORMAT_HEX:
outBufLen = bufLen * 2; // The length of the encoded data is 2 times the length of the original data.
break;
default: // The original length of bufLen is used by the default type.
outBufLen = bufLen;
}
char *outBuf = (char *)BSL_SAL_Calloc(outBufLen, sizeof(char));
if (outBuf == NULL) {
(void)AppPrintError("Failed to read the UIO content to calloc space\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
int32_t outRet = HITLS_APP_SUCCESS;
switch (format) {
case HITLS_APP_FORMAT_BASE64:
outRet = HITLS_APP_OptToBase64(buf, bufLen, outBuf, outBufLen);
break;
case HITLS_APP_FORMAT_HEX:
outRet = HITLS_APP_OptToHex(buf, bufLen, outBuf, outBufLen);
break;
default:
outRet = memcpy_s(outBuf, outBufLen, buf, bufLen);
}
if (outRet != HITLS_APP_SUCCESS) {
BSL_SAL_FREE(outBuf);
return outRet;
}
int32_t writeRet = BSL_UIO_Write(uio, outBuf, outBufLen, &writeLen);
BSL_SAL_FREE(outBuf);
if (writeRet != BSL_SUCCESS || outBufLen != writeLen) {
(void)AppPrintError("Failed to output the content.\n");
return HITLS_APP_UIO_FAIL;
}
(void)BSL_UIO_Ctrl(uio, BSL_UIO_FLUSH, 0, NULL);
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_OptReadUio(BSL_UIO *uio, uint8_t **readBuf, uint64_t *readBufLen, uint64_t maxBufLen)
{
if (uio == NULL) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
int32_t readRet = BSL_UIO_Ctrl(uio, BSL_UIO_PENDING, sizeof(*readBufLen), readBufLen);
if (readRet != BSL_SUCCESS) {
(void)AppPrintError("Failed to obtain the content length\n");
return HITLS_APP_UIO_FAIL;
}
if (*readBufLen == 0 || *readBufLen > maxBufLen) {
(void)AppPrintError("Invalid content length\n");
return HITLS_APP_UIO_FAIL;
}
// obtain the length of the UIO content, the pointer of the input parameter points to the allocated memory
uint8_t *buf = (uint8_t *)BSL_SAL_Calloc(*readBufLen + 1, sizeof(uint8_t));
if (buf == NULL) {
(void)AppPrintError("Failed to create the space.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
uint32_t readLen = 0;
readRet = BSL_UIO_Read(uio, buf, *readBufLen, &readLen); // read content to memory
if (readRet != BSL_SUCCESS || *readBufLen != readLen) {
BSL_SAL_FREE(buf);
(void)AppPrintError("Failed to read UIO content.\n");
return HITLS_APP_UIO_FAIL;
}
buf[*readBufLen] = '\0';
*readBuf = buf;
return HITLS_APP_SUCCESS;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_opt.c | C | unknown | 21,317 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_passwd.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <termios.h>
#include <unistd.h>
#include <securec.h>
#include <linux/limits.h>
#include "bsl_ui.h"
#include "bsl_uio.h"
#include "bsl_sal.h"
#include "bsl_errno.h"
#include "app_opt.h"
#include "app_errno.h"
#include "app_print.h"
#include "app_utils.h"
#include "crypt_eal_rand.h"
#include "crypt_errno.h"
#include "crypt_eal_md.h"
typedef enum {
HITLS_APP_OPT_PASSWD_ERR = -1,
HITLS_APP_OPT_PASSWD_EOF = 0,
HITLS_APP_OPT_PASSWD_HELP = 1,
HITLS_APP_OPT_PASSWD_OUTFILE = 2,
HITLS_APP_OPT_PASSWD_SHA512,
} HITLSOptType;
const HITLS_CmdOption g_passwdOpts[] = {
{"help", HITLS_APP_OPT_PASSWD_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"out", HITLS_APP_OPT_PASSWD_OUTFILE, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Outfile"},
{"sha512", HITLS_APP_OPT_PASSWD_SHA512, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "SHA512-based password algorithm"},
{NULL}
};
typedef struct {
char *outFile;
int32_t algTag; // 6 indicates sha512, 5 indicates sha256, and 1 indicates md5.
uint8_t *salt;
int32_t saltLen;
char *pass;
uint32_t passwdLen;
long iter;
} PasswdOpt;
typedef struct {
uint8_t *buf;
size_t bufLen;
} BufLen;
// List of visible characters also B64 coding table
static const char g_b64Table[] = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static int32_t HandleOpt(PasswdOpt *opt);
static int32_t CheckPara(PasswdOpt *opt, BSL_UIO *outUio);
static int32_t GetSalt(PasswdOpt *opt);
static int32_t GetPasswd(PasswdOpt *opt);
static int32_t Sha512Crypt(PasswdOpt *opt, char *resBuf, uint32_t bufMaxLen);
static int32_t OutputResult(BSL_UIO *outUio, char *resBuf, uint32_t bufLen);
static bool IsSaltValid(char *salt);
static bool IsSaltArgValid(PasswdOpt *opt);
static bool IsDigit(char *str);
static long StrToDigit(char *str);
static bool ParseSalt(PasswdOpt *opt);
static char *SubStr(const char* srcStr, int32_t startPos, int32_t cutLen);
static CRYPT_EAL_MdCTX *InitSha512Ctx(void);
static int32_t B64EncToBuf(char *resBuf, uint32_t bufLen, uint32_t offset, uint8_t *hashBuf, uint32_t hashBufLen);
static int32_t ResToBuf(PasswdOpt *opt, char *resBuf, uint32_t bufMaxLen, uint8_t *hashBuf, uint32_t hashBufLen);
static int32_t Sha512Md2Hash(CRYPT_EAL_MdCTX *md2, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen);
static int32_t Sha512Md1HashWithMd2(CRYPT_EAL_MdCTX *md1, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen);
static int32_t Sha512MdPHash(CRYPT_EAL_MdCTX *mdP, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen);
static int32_t Sha512MdSHash(CRYPT_EAL_MdCTX *mdS, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen, uint8_t nForMdS);
static int32_t Sha512GetMdPBuf(PasswdOpt *opt, uint8_t *mdPBuf, uint32_t mdPBufLen);
static int32_t Sha512GetMdSBuf(PasswdOpt *opt, uint8_t *mdSBuf, uint32_t mdSBufLen, uint8_t nForMdS);
static int32_t Sha512IterHash(long rounds, BufLen *md1HashRes, BufLen *mdPBuf, BufLen *mdSBuf);
static int32_t Sha512MdCrypt(PasswdOpt *opt, char *resBuf, uint32_t bufLen);
int32_t HITLS_PasswdMain(int argc, char *argv[])
{
PasswdOpt opt = {NULL, -1, NULL, -1, NULL, 0, -1};
int32_t ret = HITLS_APP_SUCCESS;
BSL_UIO *outUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (outUio == NULL) {
AppPrintError("Failed to create the output UIO.\n");
return HITLS_APP_UIO_FAIL;
}
if ((ret = HITLS_APP_OptBegin(argc, argv, g_passwdOpts)) != HITLS_APP_SUCCESS) {
AppPrintError("error in opt begin.\n");
goto passwdEnd;
}
if ((ret = HandleOpt(&opt)) != HITLS_APP_SUCCESS) {
goto passwdEnd;
}
if ((ret = CheckPara(&opt, outUio)) != HITLS_APP_SUCCESS) {
goto passwdEnd;
}
char res[REC_MAX_ARRAY_LEN] = {0};
if ((ret = Sha512Crypt(&opt, res, REC_MAX_ARRAY_LEN)) != HITLS_APP_SUCCESS) {
goto passwdEnd;
}
uint32_t resBufLen = strlen(res);
if ((ret = OutputResult(outUio, res, resBufLen)) != HITLS_APP_SUCCESS) {
goto passwdEnd;
}
passwdEnd:
BSL_SAL_FREE(opt.salt);
if (opt.pass != NULL && opt.passwdLen > 0) {
(void)memset_s(opt.pass, opt.passwdLen, 0, opt.passwdLen);
}
BSL_SAL_FREE(opt.pass);
if (opt.outFile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(outUio, true);
}
BSL_UIO_Free(outUio);
return ret;
}
static int32_t HandleOpt(PasswdOpt *opt)
{
int32_t optType;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_PASSWD_EOF) {
switch (optType) {
case HITLS_APP_OPT_PASSWD_EOF:
break;
case HITLS_APP_OPT_PASSWD_ERR:
AppPrintError("passwd: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
case HITLS_APP_OPT_PASSWD_HELP:
HITLS_APP_OptHelpPrint(g_passwdOpts);
return HITLS_APP_HELP;
case HITLS_APP_OPT_PASSWD_OUTFILE:
opt->outFile = HITLS_APP_OptGetValueStr();
break;
case HITLS_APP_OPT_PASSWD_SHA512:
opt->algTag = REC_SHA512_ALGTAG;
opt->saltLen = REC_SHA512_SALTLEN;
break;
default:
break;
}
}
// Obtains the value of the last digit numbits.
int32_t restOptNum = HITLS_APP_GetRestOptNum();
if (restOptNum != 0) {
(void)AppPrintError("Extra arguments given.\n");
AppPrintError("passwd: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return HITLS_APP_SUCCESS;
}
static int32_t GetSalt(PasswdOpt *opt)
{
if (opt->salt == NULL && opt->saltLen != -1) {
uint8_t *tmpSalt = (uint8_t *)BSL_SAL_Calloc(opt->saltLen + 1, sizeof(uint8_t));
if (tmpSalt == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
opt->salt = tmpSalt;
// Generate a salt value
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_SHA256, "provider=default",
NULL, 0, NULL) != CRYPT_SUCCESS ||
CRYPT_EAL_RandbytesEx(NULL, opt->salt, opt->saltLen) != CRYPT_SUCCESS) {
AppPrintError("Failed to generate the salt value.\n");
BSL_SAL_FREE(opt->salt);
CRYPT_EAL_RandDeinitEx(NULL);
return HITLS_APP_CRYPTO_FAIL;
}
// Convert salt value to visible code
int32_t count = 0;
for (; count < opt->saltLen; count++) {
if ((opt->salt[count] & 0x3f) < strlen(g_b64Table)) {
opt->salt[count] = g_b64Table[opt->salt[count] & 0x3f];
}
}
opt->salt[count] = '\0';
CRYPT_EAL_RandDeinitEx(NULL);
}
return HITLS_APP_SUCCESS;
}
static int32_t GetPasswd(PasswdOpt *opt)
{
uint32_t bufLen = APP_MAX_PASS_LENGTH + 1;
BSL_UI_ReadPwdParam param = {"password", NULL, true};
if (opt->pass == NULL) {
char *tmpPasswd = (char *)BSL_SAL_Calloc(APP_MAX_PASS_LENGTH + 1, sizeof(char));
if (tmpPasswd == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
int32_t readPassRet = BSL_UI_ReadPwdUtil(¶m, tmpPasswd, &bufLen, HITLS_APP_DefaultPassCB, NULL);
if (readPassRet == BSL_UI_READ_BUFF_TOO_LONG || readPassRet == BSL_UI_READ_LEN_TOO_SHORT) {
HITLS_APP_PrintPassErrlog();
BSL_SAL_FREE(tmpPasswd);
return HITLS_APP_PASSWD_FAIL;
}
if (readPassRet != BSL_SUCCESS) {
BSL_SAL_FREE(tmpPasswd);
return HITLS_APP_PASSWD_FAIL;
}
bufLen -= 1; // The interface also reads the Enter, so the last digit needs to be replaced with the '\0'.
tmpPasswd[bufLen] = '\0';
opt->pass = tmpPasswd;
} else {
bufLen = strlen(opt->pass);
}
opt->passwdLen = bufLen;
if (HITLS_APP_CheckPasswd((uint8_t *)opt->pass, opt->passwdLen) != HITLS_APP_SUCCESS) {
opt->passwdLen = 0;
return HITLS_APP_PASSWD_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckPara(PasswdOpt *passwdOpt, BSL_UIO *outUio)
{
if (passwdOpt->algTag == -1 || passwdOpt->saltLen == -1) {
AppPrintError("The hash algorithm is not specified.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (passwdOpt->iter != -1) {
if (passwdOpt->iter < REC_MIN_ITER_TIMES || passwdOpt->iter > REC_MAX_ITER_TIMES) {
AppPrintError("Invalid iterations number, valid range[1000, 999999999].\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
}
int32_t checkRet = HITLS_APP_SUCCESS;
if ((checkRet = GetSalt(passwdOpt)) != HITLS_APP_SUCCESS) {
return checkRet;
}
if ((checkRet = GetPasswd(passwdOpt)) != HITLS_APP_SUCCESS) {
return checkRet;
}
// Obtains the post-value of the OUT option. If there is no post-value or this option, stdout.
if (passwdOpt->outFile == NULL) {
if (BSL_UIO_Ctrl(outUio, BSL_UIO_FILE_PTR, 0, (void *)stdout) != BSL_SUCCESS) {
AppPrintError("Failed to set stdout mode.\n");
return HITLS_APP_UIO_FAIL;
}
} else {
// User input file path, which is bound to the output file.
if (strlen(passwdOpt->outFile) >= PATH_MAX || strlen(passwdOpt->outFile) == 0) {
AppPrintError("The length of outfile error, range is (0, 4096].\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
if (BSL_UIO_Ctrl(outUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_WRITE, passwdOpt->outFile) != BSL_SUCCESS) {
AppPrintError("Failed to set outfile mode.\n");
return HITLS_APP_UIO_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
static bool IsDigit(char *str)
{
for (size_t i = 0; i < strlen(str); i++) {
if (str[i] < '0' || str[i] > '9') {
return false;
}
}
return true;
}
static long StrToDigit(char *str)
{
long res = 0;
for (size_t i = 0; i < strlen(str); i++) {
res = res * REC_TEN + (str[i] - '0');
}
return res;
}
static char *SubStr(const char* srcStr, int32_t startPos, int32_t cutLen)
{
if (srcStr == NULL || (size_t)startPos < 0 || cutLen < 0) {
return NULL;
}
if (strlen(srcStr) < (size_t)startPos || strlen(srcStr) < (size_t)cutLen) {
return NULL;
}
int32_t index = 0;
static char destStr[REC_MAX_ARRAY_LEN] = {0};
srcStr = srcStr + startPos;
while (srcStr != NULL && index < cutLen) {
destStr[index] = *srcStr++;
if (*srcStr == '\0') {
break;
}
index++;
}
return destStr;
}
// Parse the user salt value in the special format and obtain the core salt value.
// For example, "$6$rounds=100000$/q1Z/N8SXhnbS5p5$cipherText" or "$6$/q1Z/N8SXhnbS5p5$cipherText"
// This function parses a string and extracts a valid salt value as "/q1Z/N8SXhnbS5p5"
static bool ParseSalt(PasswdOpt *opt)
{
if (strncmp((char *)opt->salt, "$6$", REC_PRE_TAG_LEN) != 0) {
return false;
}
// cutting salt value head
if (strlen((char *)opt->salt) < REC_PRE_TAG_LEN + 1) {
return false;
}
uint8_t *restSalt = opt->salt + REC_PRE_TAG_LEN;
// Check whether this part is the information about the number of iterations.
if (strncmp((char *)restSalt, "rounds=", REC_PRE_ITER_LEN - 1) == 0) {
// Check whether the number of iterations is valid and assign the value.
if (strlen((char *)restSalt) < REC_PRE_ITER_LEN) {
return false;
}
restSalt = restSalt + REC_PRE_ITER_LEN - 1;
char *context = NULL;
char *iterStr = strtok_s((char *)restSalt, "$", &context);
if (iterStr == NULL || !IsDigit(iterStr)) {
return false;
}
if (opt->iter != -1) {
if (opt->iter != StrToDigit(iterStr)) {
AppPrintError("Input iterations does not match the information in the salt string.\n");
return false;
}
} else {
long tmpIter = StrToDigit(iterStr);
if (tmpIter < REC_MIN_ITER_TIMES || tmpIter > REC_MAX_ITER_TIMES) {
AppPrintError("Invalid input iterations number, valid range[1000, 999999999].\n");
return false;
}
opt->iter = tmpIter;
}
char *cipherText = NULL;
char *tmpSalt = strtok_s(context, "$", &cipherText);
if (tmpSalt == NULL || !IsSaltValid(tmpSalt)) {
return false;
}
opt->salt = (uint8_t *)tmpSalt;
} else {
char *cipherText = NULL;
char *tmpSalt = strtok_s((char *)restSalt, "$", &cipherText);
if (tmpSalt == NULL || !IsSaltValid(tmpSalt)) {
return false;
}
opt->salt = (uint8_t *)tmpSalt;
}
if (strlen((char *)opt->salt) > REC_MAX_SALTLEN) {
opt->salt = (uint8_t *)SubStr((char *)opt->salt, 0, REC_MAX_SALTLEN);
}
return true;
}
static bool IsSaltValid(char *salt)
{
if (salt == NULL || strlen(salt) == 0) {
return false;
}
for (size_t i = 1; i < strlen(salt); i++) {
if (salt[i] == '$') {
return false;
}
}
return true;
}
static bool IsSaltArgValid(PasswdOpt *opt)
{
if (opt->salt[0] != '$') {
// Salt value in non-encrypted format
return IsSaltValid((char *)opt->salt);
} else {
// Salt value of the encryption format.
return ParseSalt(opt);
}
return true;
}
static CRYPT_EAL_MdCTX *InitSha512Ctx(void)
{
// Creating an MD Context
CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_ProviderMdNewCtx(NULL, CRYPT_MD_SHA512, "provider=default");
if (ctx == NULL) {
return NULL;
}
if (CRYPT_EAL_MdInit(ctx) != CRYPT_SUCCESS) {
CRYPT_EAL_MdFreeCtx(ctx);
return NULL;
}
return ctx;
}
static int32_t B64EncToBuf(char *resBuf, uint32_t bufLen, uint32_t offset, uint8_t *hashBuf, uint32_t hashBufLen)
{
if (resBuf == NULL || bufLen == 0 || hashBuf == NULL || hashBufLen < REC_HASH_BUF_LEN || offset > bufLen) {
return HITLS_APP_INVALID_ARG;
}
#define B64_FROM_24BIT(B3, B2, B1, N) \
do { \
uint32_t w = ((B3) << 16) | ((B2) << 8) | (B1); \
int32_t n = (N); \
while (n-- > 0 && bufLen > 0) { \
*(resBuf + offset++) = g_b64Table[w & 0x3f]; \
--bufLen; \
w >>= 6; \
} \
} while (0)
B64_FROM_24BIT (hashBuf[0], hashBuf[21], hashBuf[42], 4);
B64_FROM_24BIT (hashBuf[22], hashBuf[43], hashBuf[1], 4);
B64_FROM_24BIT (hashBuf[44], hashBuf[2], hashBuf[23], 4);
B64_FROM_24BIT (hashBuf[3], hashBuf[24], hashBuf[45], 4);
B64_FROM_24BIT (hashBuf[25], hashBuf[46], hashBuf[4], 4);
B64_FROM_24BIT (hashBuf[47], hashBuf[5], hashBuf[26], 4);
B64_FROM_24BIT (hashBuf[6], hashBuf[27], hashBuf[48], 4);
B64_FROM_24BIT (hashBuf[28], hashBuf[49], hashBuf[7], 4);
B64_FROM_24BIT (hashBuf[50], hashBuf[8], hashBuf[29], 4);
B64_FROM_24BIT (hashBuf[9], hashBuf[30], hashBuf[51], 4);
B64_FROM_24BIT (hashBuf[31], hashBuf[52], hashBuf[10], 4);
B64_FROM_24BIT (hashBuf[53], hashBuf[11], hashBuf[32], 4);
B64_FROM_24BIT (hashBuf[12], hashBuf[33], hashBuf[54], 4);
B64_FROM_24BIT (hashBuf[34], hashBuf[55], hashBuf[13], 4);
B64_FROM_24BIT (hashBuf[56], hashBuf[14], hashBuf[35], 4);
B64_FROM_24BIT (hashBuf[15], hashBuf[36], hashBuf[57], 4);
B64_FROM_24BIT (hashBuf[37], hashBuf[58], hashBuf[16], 4);
B64_FROM_24BIT (hashBuf[59], hashBuf[17], hashBuf[38], 4);
B64_FROM_24BIT (hashBuf[18], hashBuf[39], hashBuf[60], 4);
B64_FROM_24BIT (hashBuf[40], hashBuf[61], hashBuf[19], 4);
B64_FROM_24BIT (hashBuf[62], hashBuf[20], hashBuf[41], 4);
B64_FROM_24BIT (0, 0, hashBuf[63], 2);
if (bufLen <= 0) {
return HITLS_APP_ENCODE_FAIL;
} else {
*(resBuf + offset) = '\0';
}
return CRYPT_SUCCESS;
}
static int32_t ResToBuf(PasswdOpt *opt, char *resBuf, uint32_t bufMaxLen, uint8_t *hashBuf, uint32_t hashBufLen)
{
// construct the result string
if (resBuf == NULL || bufMaxLen < REC_MIN_PREFIX_LEN) {
return HITLS_APP_INVALID_ARG;
}
uint32_t bufLen = bufMaxLen; // Remaining buffer size
uint32_t offset = 0; // Number of characters in the prefix
// algorithm identifier
if (snprintf_s((char *)resBuf, bufLen, REC_PRE_TAG_LEN, "$%d$", opt->algTag) == -1) {
return HITLS_APP_SECUREC_FAIL;
}
bufLen -= REC_PRE_TAG_LEN;
offset += REC_PRE_TAG_LEN;
// Determine whether to add the iteration times flag.
if (opt->iter != -1) {
uint32_t iterBit = 0;
long tmpIter = opt->iter;
while (tmpIter != 0) {
tmpIter /= REC_TEN;
iterBit++;
}
uint32_t totalLen = iterBit + REC_PRE_ITER_LEN;
if (snprintf_s(resBuf + offset, bufLen, totalLen, "rounds=%ld$", opt->algTag) == -1) {
return HITLS_APP_SECUREC_FAIL;
}
bufLen -= totalLen;
offset += totalLen;
}
// Add Salt Value
if (snprintf_s(resBuf + offset, bufLen, opt->saltLen + 1, "%s$", opt->salt) == -1) {
return HITLS_APP_SECUREC_FAIL;
}
bufLen -= (opt->saltLen + 1);
offset += (opt->saltLen + 1);
if (B64EncToBuf(resBuf, bufLen, offset, hashBuf, hashBufLen) != CRYPT_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t Sha512Md2Hash(CRYPT_EAL_MdCTX *md2, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen)
{
if (CRYPT_EAL_MdUpdate(md2, (uint8_t *)opt->pass, opt->passwdLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (CRYPT_EAL_MdUpdate(md2, opt->salt, opt->saltLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (CRYPT_EAL_MdUpdate(md2, (uint8_t *)opt->pass, opt->passwdLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (CRYPT_EAL_MdFinal(md2, resBuf, bufLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512Md1HashWithMd2(CRYPT_EAL_MdCTX *md1, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen)
{
if (CRYPT_EAL_MdUpdate(md1, (uint8_t *)opt->pass, opt->passwdLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (CRYPT_EAL_MdUpdate(md1, opt->salt, opt->saltLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_MdCTX *md2 = InitSha512Ctx();
if (md2 == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
uint8_t md2_hash_res[REC_MAX_ARRAY_LEN] = {0};
uint32_t md2_hash_len = REC_MAX_ARRAY_LEN;
if (Sha512Md2Hash(md2, opt, md2_hash_res, &md2_hash_len) != CRYPT_SUCCESS) {
CRYPT_EAL_MdFreeCtx(md2);
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_MdFreeCtx(md2);
uint32_t times = opt->passwdLen / REC_SHA512_BLOCKSIZE;
uint32_t restDataLen = opt->passwdLen % REC_SHA512_BLOCKSIZE;
for (uint32_t i = 0; i < times; i++) {
if (CRYPT_EAL_MdUpdate(md1, md2_hash_res, md2_hash_len) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
if (restDataLen != 0) {
if (CRYPT_EAL_MdUpdate(md1, md2_hash_res, restDataLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
for (uint32_t count = opt->passwdLen; count > 0; count >>= 1) {
if ((count & 1) != 0) {
if (CRYPT_EAL_MdUpdate(md1, md2_hash_res, md2_hash_len) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
} else {
if (CRYPT_EAL_MdUpdate(md1, (uint8_t *)opt->pass, opt->passwdLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
}
if (CRYPT_EAL_MdFinal(md1, resBuf, bufLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512MdPHash(CRYPT_EAL_MdCTX *mdP, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen)
{
for (uint32_t i = opt->passwdLen; i > 0; i--) {
if (CRYPT_EAL_MdUpdate(mdP, (uint8_t *)opt->pass, opt->passwdLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
if (CRYPT_EAL_MdFinal(mdP, resBuf, bufLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512MdSHash(CRYPT_EAL_MdCTX *mdS, PasswdOpt *opt, uint8_t *resBuf, uint32_t *bufLen, uint8_t nForMdS)
{
for (int32_t count = 16 + nForMdS; count > 0; count--) {
if (CRYPT_EAL_MdUpdate(mdS, opt->salt, opt->saltLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
}
if (CRYPT_EAL_MdFinal(mdS, resBuf, bufLen) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512GetMdPBuf(PasswdOpt *opt, uint8_t *mdPBuf, uint32_t mdPBufLen)
{
CRYPT_EAL_MdCTX *mdP = InitSha512Ctx();
if (mdP == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t mdPBufMaxLen = REC_MAX_ARRAY_LEN;
uint8_t mdP_hash_res[REC_MAX_ARRAY_LEN] = {0};
uint32_t mdP_hash_len = REC_MAX_ARRAY_LEN; // The generated length is 64 characters.
if (Sha512MdPHash(mdP, opt, mdP_hash_res, &mdP_hash_len) != CRYPT_SUCCESS) {
CRYPT_EAL_MdFreeCtx(mdP);
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_MdFreeCtx(mdP);
uint32_t cpyLen = 0;
for (; mdPBufLen > REC_SHA512_BLOCKSIZE; mdPBufLen -= REC_SHA512_BLOCKSIZE) {
if (strncpy_s((char *)(mdPBuf + cpyLen), mdPBufMaxLen, (char *)mdP_hash_res, mdP_hash_len) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
cpyLen += mdP_hash_len;
mdPBufMaxLen -= mdP_hash_len;
}
if (strncpy_s((char *)(mdPBuf + cpyLen), mdPBufMaxLen, (char *)mdP_hash_res, mdPBufLen) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512GetMdSBuf(PasswdOpt *opt, uint8_t *mdSBuf, uint32_t mdSBufLen, uint8_t nForMdS)
{
CRYPT_EAL_MdCTX *mdS = InitSha512Ctx();
if (mdS == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t mdSBufMaxLen = REC_MAX_ARRAY_LEN;
uint8_t mdS_hash_res[REC_MAX_ARRAY_LEN] = {0};
uint32_t mdS_hash_len = REC_MAX_ARRAY_LEN; // The generated length is 64 characters.
if (Sha512MdSHash(mdS, opt, mdS_hash_res, &mdS_hash_len, nForMdS) != CRYPT_SUCCESS) {
CRYPT_EAL_MdFreeCtx(mdS);
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_MdFreeCtx(mdS);
uint32_t cpyLen = 0;
for (; mdSBufLen > REC_SHA512_BLOCKSIZE; mdSBufLen -= REC_SHA512_BLOCKSIZE) {
if (strncpy_s((char *)(mdSBuf + cpyLen), mdSBufMaxLen, (char *)mdS_hash_res, mdS_hash_len) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
cpyLen += mdS_hash_len;
mdSBufMaxLen -= mdS_hash_len;
}
if (strncpy_s((char *)(mdSBuf + cpyLen), mdSBufMaxLen, (char *)mdS_hash_res, mdSBufLen) != EOK) {
return HITLS_APP_SECUREC_FAIL;
}
mdSBufLen = opt->saltLen;
return CRYPT_SUCCESS;
}
static int32_t Sha512IterHash(long rounds, BufLen *md1HashRes, BufLen *mdPBuf, BufLen *mdSBuf)
{
uint32_t md1HashLen = md1HashRes->bufLen;
uint32_t mdPBufLen = mdPBuf->bufLen;
uint32_t mdSBufLen = mdSBuf->bufLen;
for (long round = 0; round < rounds; round++) {
CRYPT_EAL_MdCTX *md_r = InitSha512Ctx();
if (md_r == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
uint32_t ret = CRYPT_SUCCESS;
if (round % REC_TWO != 0) {
if ((ret = CRYPT_EAL_MdUpdate(md_r, mdPBuf->buf, mdPBufLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
} else {
if ((ret = CRYPT_EAL_MdUpdate(md_r, md1HashRes->buf, md1HashLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
}
if (round % REC_THREE != 0) {
if ((ret = CRYPT_EAL_MdUpdate(md_r, mdSBuf->buf, mdSBufLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
}
if (round % REC_SEVEN != 0) {
if ((ret = CRYPT_EAL_MdUpdate(md_r, mdPBuf->buf, mdPBufLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
}
if (round % REC_TWO != 0) {
if ((ret = CRYPT_EAL_MdUpdate(md_r, md1HashRes->buf, md1HashLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
} else {
if ((ret = CRYPT_EAL_MdUpdate(md_r, mdPBuf->buf, mdPBufLen)) != CRYPT_SUCCESS) {
goto iterEnd;
}
}
ret = CRYPT_EAL_MdFinal(md_r, md1HashRes->buf, &md1HashLen);
iterEnd:
CRYPT_EAL_MdFreeCtx(md_r);
if (ret != CRYPT_SUCCESS) {
return ret;
}
}
return CRYPT_SUCCESS;
}
static int32_t Sha512MdCrypt(PasswdOpt *opt, char *resBuf, uint32_t bufLen)
{
CRYPT_EAL_MdCTX *md1 = InitSha512Ctx();
if (md1 == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
uint8_t md1_hash_res[REC_MAX_ARRAY_LEN] = {0};
uint32_t md1_hash_len = REC_MAX_ARRAY_LEN; // The generated length is 64 characters.
if (Sha512Md1HashWithMd2(md1, opt, md1_hash_res, &md1_hash_len) != CRYPT_SUCCESS) {
CRYPT_EAL_MdFreeCtx(md1);
return HITLS_APP_CRYPTO_FAIL;
}
CRYPT_EAL_MdFreeCtx(md1);
uint8_t mdP_buf[REC_MAX_ARRAY_LEN] = {0};
uint32_t mdP_buf_len = opt->passwdLen;
if (Sha512GetMdPBuf(opt, mdP_buf, mdP_buf_len) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
uint8_t mdS_buf[REC_MAX_ARRAY_LEN] = {0};
uint32_t mdS_buf_len = opt->saltLen;
if (Sha512GetMdSBuf(opt, mdS_buf, mdS_buf_len, md1_hash_res[0]) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
long rounds = (opt->iter == -1) ? 5000 : opt->iter;
BufLen md1HasnResBuf = {.buf = md1_hash_res, .bufLen = md1_hash_len};
BufLen mdPBuf = {.buf = mdP_buf, .bufLen = mdP_buf_len};
BufLen mdSBuf = {.buf = mdS_buf, .bufLen = mdS_buf_len};
if (Sha512IterHash(rounds, &md1HasnResBuf, &mdPBuf, &mdSBuf) != CRYPT_SUCCESS) {
return HITLS_APP_CRYPTO_FAIL;
}
if (ResToBuf(opt, resBuf, bufLen, md1_hash_res, md1_hash_len) != HITLS_APP_SUCCESS) {
return HITLS_APP_ENCODE_FAIL;
}
return CRYPT_SUCCESS;
}
static int32_t Sha512Crypt(PasswdOpt *opt, char *resBuf, uint32_t bufMaxLen)
{
if (opt->pass == NULL || opt->salt == NULL) {
return HITLS_APP_INVALID_ARG;
}
if (opt->algTag != REC_SHA512_ALGTAG && opt->algTag != REC_SHA256_ALGTAG && opt->algTag != REC_MD5_ALGTAG) {
return HITLS_APP_INVALID_ARG;
}
if (!IsSaltArgValid(opt)) {
return HITLS_APP_INVALID_ARG;
}
int32_t shaRet = HITLS_APP_SUCCESS;
if ((shaRet = Sha512MdCrypt(opt, resBuf, bufMaxLen)) != HITLS_APP_SUCCESS) {
return shaRet;
}
return shaRet;
}
static int32_t OutputResult(BSL_UIO *outUio, char *resBuf, uint32_t bufLen)
{
uint32_t writeLen = 0;
if (BSL_UIO_Write(outUio, resBuf, bufLen, &writeLen) != BSL_SUCCESS || writeLen == 0) {
return HITLS_APP_UIO_FAIL;
}
if (BSL_UIO_Write(outUio, "\n", 1, &writeLen) != BSL_SUCCESS || writeLen == 0) {
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_passwd.c | C | unknown | 28,128 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_pkcs12.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <securec.h>
#include <linux/limits.h>
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_utils.h"
#include "app_list.h"
#include "crypt_algid.h"
#include "crypt_errno.h"
#include "bsl_err.h"
#include "bsl_uio.h"
#include "bsl_ui.h"
#include "bsl_obj.h"
#include "bsl_errno.h"
#include "crypt_eal_rand.h"
#include "hitls_cert_local.h"
#include "hitls_pkcs12_local.h"
#include "hitls_pki_errno.h"
#define CA_NAME_NUM (APP_FILE_MAX_SIZE_KB / 1) // Calculated based on the average value of 1K for each certificate.
typedef enum {
HITLS_APP_OPT_IN_FILE = 2,
HITLS_APP_OPT_OUT_FILE,
HITLS_APP_OPT_PASS_IN,
HITLS_APP_OPT_PASS_OUT,
HITLS_APP_OPT_IN_KEY,
HITLS_APP_OPT_EXPORT,
HITLS_APP_OPT_CLCERTS,
HITLS_APP_OPT_KEY_PBE,
HITLS_APP_OPT_CERT_PBE,
HITLS_APP_OPT_MAC_ALG,
HITLS_APP_OPT_CHAIN,
HITLS_APP_OPT_CANAME,
HITLS_APP_OPT_NAME,
HITLS_APP_OPT_CA_FILE,
HITLS_APP_OPT_CIPHER_ALG,
} HITLSOptType;
typedef struct {
char *inFile;
char *outFile;
char *passInArg;
char *passOutArg;
} GeneralOptions;
typedef struct {
bool clcerts;
const char *cipherAlgName;
} ImportOptions;
typedef struct {
char *inKey;
char *name;
char *caName[CA_NAME_NUM];
uint32_t caNameSize;
char *caFile;
char *macAlgArg;
char *certPbeArg;
char *keyPbeArg;
bool chain;
bool export;
} OutputOptions;
typedef struct {
GeneralOptions genOpt;
ImportOptions importOpt;
OutputOptions outPutOpt;
CRYPT_EAL_PkeyCtx *pkey;
char *passin;
char *passout;
int32_t cipherAlgCid;
int32_t macAlg;
int32_t certPbe;
int32_t keyPbe;
HITLS_PKCS12 *p12;
HITLS_X509_StoreCtx *store;
HITLS_X509_StoreCtx *dupStore;
HITLS_X509_List *certList;
HITLS_X509_List *caCertList;
HITLS_X509_List *outCertChainList;
HITLS_X509_Cert *userCert;
BSL_UIO *wUio;
} Pkcs12OptCtx;
typedef struct {
const uint32_t id;
const char *name;
} AlgList;
typedef int32_t (*OptHandleFunc)(Pkcs12OptCtx *);
typedef struct {
int optType;
OptHandleFunc func;
} OptHandleTable;
#define MIN_NAME_LEN 1U
#define MAX_NAME_LEN 1024U
static const HITLS_CmdOption OPTS[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"in", HITLS_APP_OPT_IN_FILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file"},
{"out", HITLS_APP_OPT_OUT_FILE, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"passin", HITLS_APP_OPT_PASS_IN, HITLS_APP_OPT_VALUETYPE_STRING, "Input file pass phrase source"},
{"passout", HITLS_APP_OPT_PASS_OUT, HITLS_APP_OPT_VALUETYPE_STRING, "Output file pass phrase source"},
{"inkey", HITLS_APP_OPT_IN_KEY, HITLS_APP_OPT_VALUETYPE_STRING, "Private key if not infile"},
{"export", HITLS_APP_OPT_EXPORT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Output PKCS12 file"},
{"clcerts", HITLS_APP_OPT_CLCERTS, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "output client certs"},
{"keypbe", HITLS_APP_OPT_KEY_PBE, HITLS_APP_OPT_VALUETYPE_STRING, "Private key PBE algorithm (default PBES2)"},
{"certpbe", HITLS_APP_OPT_CERT_PBE, HITLS_APP_OPT_VALUETYPE_STRING, "Certificate PBE algorithm (default PBES2)"},
{"macalg", HITLS_APP_OPT_MAC_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Digest algorithm used in MAC (default SHA256)"},
{"chain", HITLS_APP_OPT_CHAIN, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Add certificate chain"},
{"caname", HITLS_APP_OPT_CANAME, HITLS_APP_OPT_VALUETYPE_STRING, "Input friendly ca name"},
{"name", HITLS_APP_OPT_NAME, HITLS_APP_OPT_VALUETYPE_STRING, "Use name as friendly name"},
{"CAfile", HITLS_APP_OPT_CA_FILE, HITLS_APP_OPT_VALUETYPE_STRING, "PEM-format file of CA's"},
{"", HITLS_APP_OPT_CIPHER_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Any supported cipher"},
{NULL}
};
static const AlgList MAC_ALG_LIST[] = {
{CRYPT_MD_SHA224, "sha224"},
{CRYPT_MD_SHA256, "sha256"},
{CRYPT_MD_SHA384, "sha384"},
{CRYPT_MD_SHA512, "sha512"}
};
static const AlgList CERT_PBE_LIST[] = {
{BSL_CID_PBES2, "PBES2"}
};
static const AlgList KEY_PBE_LIST[] = {
{BSL_CID_PBES2, "PBES2"}
};
static int32_t DisplayHelp(Pkcs12OptCtx *opt)
{
(void)opt;
HITLS_APP_OptHelpPrint(OPTS);
return HITLS_APP_HELP;
}
static int32_t HandleOptErr(Pkcs12OptCtx *opt)
{
(void)opt;
AppPrintError("pkcs12: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t ParseInFile(Pkcs12OptCtx *opt)
{
opt->genOpt.inFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParseOutFile(Pkcs12OptCtx *opt)
{
opt->genOpt.outFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParsePassIn(Pkcs12OptCtx *opt)
{
opt->genOpt.passInArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParsePassOut(Pkcs12OptCtx *opt)
{
opt->genOpt.passOutArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParseInKey(Pkcs12OptCtx *opt)
{
opt->outPutOpt.inKey = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParseExport(Pkcs12OptCtx *opt)
{
opt->outPutOpt.export = true;
return HITLS_APP_SUCCESS;
}
static int32_t ParseClcerts(Pkcs12OptCtx *opt)
{
opt->importOpt.clcerts = true;
return HITLS_APP_SUCCESS;
}
static int32_t ParseKeyPbe(Pkcs12OptCtx *opt)
{
opt->outPutOpt.keyPbeArg = HITLS_APP_OptGetValueStr();
bool find = false;
for (size_t i = 0; i < sizeof(KEY_PBE_LIST) / sizeof(KEY_PBE_LIST[0]); i++) {
if (strcmp(KEY_PBE_LIST[i].name, opt->outPutOpt.keyPbeArg) == 0) {
find = true;
opt->keyPbe = KEY_PBE_LIST[i].id;
break;
}
}
// If the supported algorithm list is not found, print the supported algorithm list and return an error.
if (!find) {
AppPrintError("pkcs12: The current private key PBE algorithm supports only the following algorithms:\n");
for (size_t i = 0; i < sizeof(KEY_PBE_LIST) / sizeof(KEY_PBE_LIST[0]); i++) {
AppPrintError("%-19s", KEY_PBE_LIST[i].name);
// 4 algorithm names are displayed in each row.
if ((i + 1) % 4 == 0 && i != ((sizeof(KEY_PBE_LIST) / sizeof(KEY_PBE_LIST[0])) - 1)) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t ParseCertPbe(Pkcs12OptCtx *opt)
{
opt->outPutOpt.certPbeArg = HITLS_APP_OptGetValueStr();
bool find = false;
for (size_t i = 0; i < sizeof(CERT_PBE_LIST) / sizeof(CERT_PBE_LIST[0]); i++) {
if (strcmp(CERT_PBE_LIST[i].name, opt->outPutOpt.certPbeArg) == 0) {
find = true;
opt->certPbe = CERT_PBE_LIST[i].id;
break;
}
}
// If the supported algorithm list is not found, print the supported algorithm list and return an error.
if (!find) {
AppPrintError("pkcs12: The current certificate PBE algorithm supports only the following algorithms:\n");
for (size_t i = 0; i < sizeof(CERT_PBE_LIST) / sizeof(CERT_PBE_LIST[0]); i++) {
AppPrintError("%-19s", CERT_PBE_LIST[i].name);
// 4 algorithm names are displayed in each row.
if ((i + 1) % 4 == 0 && i != ((sizeof(CERT_PBE_LIST) / sizeof(CERT_PBE_LIST[0])) - 1)) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t ParseMacAlg(Pkcs12OptCtx *opt)
{
opt->outPutOpt.macAlgArg = HITLS_APP_OptGetValueStr();
bool find = false;
for (size_t i = 0; i < sizeof(MAC_ALG_LIST) / sizeof(MAC_ALG_LIST[0]); i++) {
if (strcmp(MAC_ALG_LIST[i].name, opt->outPutOpt.macAlgArg) == 0) {
find = true;
opt->macAlg = MAC_ALG_LIST[i].id;
break;
}
}
// If the supported algorithm list is not found, print the supported algorithm list and return an error.
if (!find) {
AppPrintError("pkcs12: The current digest algorithm supports only the following algorithms:\n");
for (size_t i = 0; i < sizeof(MAC_ALG_LIST) / sizeof(MAC_ALG_LIST[0]); i++) {
AppPrintError("%-19s", MAC_ALG_LIST[i].name);
// 4 algorithm names are displayed in each row.
if ((i + 1) % 4 == 0 && i != ((sizeof(MAC_ALG_LIST) / sizeof(MAC_ALG_LIST[0])) - 1)) {
AppPrintError("\n");
}
}
AppPrintError("\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t ParseChain(Pkcs12OptCtx *opt)
{
opt->outPutOpt.chain = true;
return HITLS_APP_SUCCESS;
}
static int32_t ParseName(Pkcs12OptCtx *opt)
{
opt->outPutOpt.name = HITLS_APP_OptGetValueStr();
if (strlen(opt->outPutOpt.name) > MAX_NAME_LEN) {
AppPrintError("pkcs12: The name length is incorrect. It should be in the range of %u to %u.\n", MIN_NAME_LEN,
MAX_NAME_LEN);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t ParseCaName(Pkcs12OptCtx *opt)
{
char *caName = HITLS_APP_OptGetValueStr();
if (strlen(caName) > MAX_NAME_LEN) {
AppPrintError("pkcs12: The name length is incorrect. It should be in the range of %u to %u.\n", MIN_NAME_LEN,
MAX_NAME_LEN);
return HITLS_APP_OPT_VALUE_INVALID;
}
uint32_t index = opt->outPutOpt.caNameSize;
if (index >= CA_NAME_NUM) {
AppPrintError("pkcs12: The maximum number of canames is %u.\n", CA_NAME_NUM);
return HITLS_APP_OPT_VALUE_INVALID;
}
opt->outPutOpt.caName[index] = caName;
++(opt->outPutOpt.caNameSize);
return HITLS_APP_SUCCESS;
}
static int32_t ParseCaFile(Pkcs12OptCtx *opt)
{
opt->outPutOpt.caFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ParseCipher(Pkcs12OptCtx *opt)
{
opt->importOpt.cipherAlgName = HITLS_APP_OptGetUnKownOptName();
return HITLS_APP_GetAndCheckCipherOpt(opt->importOpt.cipherAlgName, &opt->cipherAlgCid);
}
static const OptHandleTable OPT_HANDLE_TABLE[] = {
{HITLS_APP_OPT_ERR, HandleOptErr},
{HITLS_APP_OPT_HELP, DisplayHelp},
{HITLS_APP_OPT_IN_FILE, ParseInFile},
{HITLS_APP_OPT_OUT_FILE, ParseOutFile},
{HITLS_APP_OPT_PASS_IN, ParsePassIn},
{HITLS_APP_OPT_PASS_OUT, ParsePassOut},
{HITLS_APP_OPT_IN_KEY, ParseInKey},
{HITLS_APP_OPT_EXPORT, ParseExport},
{HITLS_APP_OPT_CLCERTS, ParseClcerts},
{HITLS_APP_OPT_KEY_PBE, ParseKeyPbe},
{HITLS_APP_OPT_CERT_PBE, ParseCertPbe},
{HITLS_APP_OPT_MAC_ALG, ParseMacAlg},
{HITLS_APP_OPT_CHAIN, ParseChain},
{HITLS_APP_OPT_CANAME, ParseCaName},
{HITLS_APP_OPT_NAME, ParseName},
{HITLS_APP_OPT_CA_FILE, ParseCaFile},
{HITLS_APP_OPT_CIPHER_ALG, ParseCipher}
};
static int32_t ParseOpt(int argc, char *argv[], Pkcs12OptCtx *opt)
{
int32_t ret = HITLS_APP_OptBegin(argc, argv, OPTS);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkcs12: error in opt begin.\n");
return ret;
}
int optType = HITLS_APP_OPT_ERR;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF) {
for (size_t i = 0; i < (sizeof(OPT_HANDLE_TABLE) / sizeof(OPT_HANDLE_TABLE[0])); i++) {
if (optType != OPT_HANDLE_TABLE[i].optType) {
continue;
}
ret = OPT_HANDLE_TABLE[i].func(opt);
if (ret != HITLS_APP_SUCCESS) { // If any option fails to be parsed, an error is returned.
return ret;
}
break; // If the parsing is successful, exit the current loop and parse the next option.
}
}
// Obtain the number of parameters that cannot be parsed in the current version,
// and print the error information and help list.
if (HITLS_APP_GetRestOptNum() != 0) {
AppPrintError("pkcs12: Extra arguments given.\n");
AppPrintError("pkcs12: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
return ret;
}
static int32_t CheckInFile(const char *inFile, const char *fileType)
{
if (inFile == NULL) {
AppPrintError("pkcs12: The %s is not specified.\n", fileType);
return HITLS_APP_OPT_UNKOWN;
}
if ((strnlen(inFile, PATH_MAX + 1) >= PATH_MAX) || (strlen(inFile) == 0)) {
AppPrintError("pkcs12: The length of %s error, range is (0, %d).\n", fileType, PATH_MAX);
return HITLS_APP_OPT_VALUE_INVALID;
}
size_t fileLen = 0;
int32_t ret = BSL_SAL_FileLength(inFile, &fileLen);
if (ret != BSL_SUCCESS) {
AppPrintError("pkcs12: Failed to get file size: %s, errCode = 0x%x.\n", fileType, ret);
return HITLS_APP_BSL_FAIL;
}
if (fileLen > APP_FILE_MAX_SIZE) {
AppPrintError("pkcs12: File size exceed limit %zukb: %s.\n", APP_FILE_MAX_SIZE_KB, fileType);
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t CheckOutFile(const char *outFile)
{
// If outfile is transferred, the length cannot exceed PATH_MAX.
if ((outFile != NULL) && ((strnlen(outFile, PATH_MAX + 1) >= PATH_MAX) || (strlen(outFile) == 0))) {
AppPrintError("pkcs12: The length of out file error, range is (0, %d).\n", PATH_MAX);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t LoadCertList(const char *certFile, HITLS_X509_List **outCertList)
{
HITLS_X509_List *certlist = NULL;
int32_t ret = HITLS_X509_CertParseBundleFile(BSL_FORMAT_PEM, certFile, &certlist);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to read cert from %s. errCode = 0x%x.\n", certFile, ret);
return HITLS_APP_X509_FAIL;
}
*outCertList = certlist;
return HITLS_APP_SUCCESS;
}
static int32_t CheckCertListWithPriKey(HITLS_X509_List *certList, CRYPT_EAL_PkeyCtx *prvKey, HITLS_X509_Cert **userCert)
{
HITLS_X509_Cert *pstCert = BSL_LIST_GET_FIRST(certList);
while (pstCert != NULL) {
CRYPT_EAL_PkeyCtx *pubKey = NULL;
int32_t ret = HITLS_X509_CertCtrl(pstCert, HITLS_X509_GET_PUBKEY, &pubKey, 0);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Get pubKey from certificate failed, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = CRYPT_EAL_PkeyCmp(pubKey, prvKey);
CRYPT_EAL_PkeyFreeCtx(pubKey);
if (ret == CRYPT_SUCCESS) {
// If an error occurs, the memory applied here will be uniformly freed through the release of caList
*userCert = HITLS_X509_CertDup(pstCert);
if (*userCert == NULL) {
AppPrintError("pkcs12: Failed to duplicate the certificate.\n");
return HITLS_APP_X509_FAIL;
}
BSL_LIST_DeleteCurrent(certList, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
return HITLS_APP_SUCCESS;
}
pstCert = BSL_LIST_GET_NEXT(certList);
}
AppPrintError("pkcs12: No certificate matches private key.\n");
return HITLS_APP_X509_FAIL;
}
static int32_t AddCertToList(HITLS_X509_Cert *cert, HITLS_X509_List *certList)
{
HITLS_X509_Cert *tmpCert = HITLS_X509_CertDup(cert);
if (tmpCert == NULL) {
AppPrintError("pkcs12: Failed to duplicate the certificate.\n");
return HITLS_APP_X509_FAIL;
}
int32_t ret = BSL_LIST_AddElement(certList, tmpCert, BSL_LIST_POS_AFTER);
if (ret != BSL_SUCCESS) {
AppPrintError("pkcs12: Failed to add cert list, errCode = 0x%x.\n", ret);
HITLS_X509_CertFree(tmpCert);
return HITLS_APP_BSL_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t AddCertChain(Pkcs12OptCtx *opt)
{
// if the issuer certificate for input certificate is not found in the trust store, then only input
// certificate will be considered in the output chain.
if (BSL_LIST_COUNT(opt->outCertChainList) <= 1) {
AppPrintError("pkcs12: Failed to get local issuer certificate.\n");
return HITLS_APP_X509_FAIL;
}
// Mark duplicate CA certificate
opt->dupStore = HITLS_X509_StoreCtxNew();
if (opt->dupStore == NULL) {
AppPrintError("pkcs12: Failed to create the dup store context.\n");
return HITLS_APP_X509_FAIL;
}
HITLS_X509_Cert *cert = BSL_LIST_GET_FIRST(opt->certList);
while (cert != NULL) {
(void)HITLS_X509_StoreCtxCtrl(opt->dupStore, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, cert,
sizeof(HITLS_X509_Cert));
cert = BSL_LIST_GET_NEXT(opt->certList);
}
// The first element in the output certificate chain is the input certificate, skip it.
HITLS_X509_Cert *pstCert = BSL_LIST_GET_FIRST(opt->outCertChainList);
pstCert = BSL_LIST_GET_NEXT(opt->outCertChainList);
while (pstCert != NULL) {
if (HITLS_X509_StoreCtxCtrl(opt->dupStore, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, pstCert,
sizeof(HITLS_X509_Cert)) == HITLS_X509_ERR_CERT_EXIST) {
pstCert = BSL_LIST_GET_NEXT(opt->outCertChainList);
continue;
}
int32_t ret = AddCertToList(pstCert, opt->certList);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
pstCert = BSL_LIST_GET_NEXT(opt->outCertChainList);
}
return HITLS_APP_SUCCESS;
}
static int32_t ParseAndAddCertChain(Pkcs12OptCtx *opt)
{
// If the user certificate is a root certificate, no action is required.
bool selfSigned = false;
int32_t ret = HITLS_X509_CheckIssued(opt->userCert, opt->userCert, &selfSigned);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to check cert issued, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
opt->store = HITLS_X509_StoreCtxNew();
if (opt->store == NULL) {
AppPrintError("pkcs12: Failed to create the store context.\n");
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CertParseBundleFile(BSL_FORMAT_PEM, opt->outPutOpt.caFile, &opt->caCertList);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to parse certificate %s, errCode = 0x%x.\n", opt->outPutOpt.caFile, ret);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_Cert *cert = BSL_LIST_GET_FIRST(opt->caCertList);
while (cert != NULL) {
ret = HITLS_X509_StoreCtxCtrl(opt->store, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, cert, sizeof(HITLS_X509_Cert));
if (ret == HITLS_X509_ERR_CERT_EXIST) {
cert = BSL_LIST_GET_NEXT(opt->caCertList);
continue;
}
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to add the certificate %s to the trust store, errCode = 0x%0x.\n",
opt->outPutOpt.caFile, ret);
return HITLS_APP_X509_FAIL;
}
cert = BSL_LIST_GET_NEXT(opt->caCertList);
}
ret = HITLS_X509_CertChainBuild(opt->store, true, opt->userCert, &opt->outCertChainList);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed get cert chain by cert, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return AddCertChain(opt);
}
static int32_t AddKeyBagToP12(char *name, CRYPT_EAL_PkeyCtx *pkey, HITLS_PKCS12 *p12)
{
// new a key Bag
HITLS_PKCS12_Bag *pkeyBag = HITLS_PKCS12_BagNew(BSL_CID_PKCS8SHROUDEDKEYBAG, 0, pkey);
if (pkeyBag == NULL) {
AppPrintError("pkcs12: Failed to create the private key bag.\n");
return HITLS_APP_X509_FAIL;
}
if (name != NULL) {
BSL_Buffer attribute = { (uint8_t *)name, strlen(name) };
int32_t ret = HITLS_PKCS12_BagAddAttr(pkeyBag, BSL_CID_FRIENDLYNAME, &attribute);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to add the private key friendlyname, errCode = 0x%x.\n", ret);
HITLS_PKCS12_BagFree(pkeyBag);
return HITLS_APP_X509_FAIL;
}
}
// Set entity-key to p12
int32_t ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_KEYBAG, pkeyBag, 0);
HITLS_PKCS12_BagFree(pkeyBag);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to set the private key bag, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t AddUserCertBagToP12(char *name, HITLS_X509_Cert *cert, HITLS_PKCS12 *p12)
{
// new a cert Bag
HITLS_PKCS12_Bag *certBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, cert);
if (certBag == NULL) {
AppPrintError("pkcs12: Failed to create the user cert bag.\n");
return HITLS_APP_X509_FAIL;
}
if (name != NULL) {
BSL_Buffer attribute = { (uint8_t *)name, strlen(name) };
int32_t ret = HITLS_PKCS12_BagAddAttr(certBag, BSL_CID_FRIENDLYNAME, &attribute);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to add the user cert friendlyname, errCode = 0x%x.\n", ret);
HITLS_PKCS12_BagFree(certBag);
return HITLS_APP_X509_FAIL;
}
}
// Set entity-cert to p12
int32_t ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_SET_ENTITY_CERTBAG, certBag, 0);
HITLS_PKCS12_BagFree(certBag);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to set the user cert bag, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t AddOtherCertListBagToP12(char **caName, uint32_t caNameSize, HITLS_X509_List *certList,
HITLS_PKCS12 *p12)
{
int32_t ret = HITLS_APP_SUCCESS;
HITLS_X509_Cert *pstCert = BSL_LIST_GET_FIRST(certList);
uint32_t index = 0;
while (pstCert != NULL) {
HITLS_PKCS12_Bag *otherCertBag = HITLS_PKCS12_BagNew(BSL_CID_CERTBAG, BSL_CID_X509CERTIFICATE, pstCert);
if (otherCertBag == NULL) {
AppPrintError("pkcs12: Failed to create the other cert bag.\n");
return HITLS_APP_X509_FAIL;
}
if ((index < caNameSize) && (caName[index] != NULL)) {
BSL_Buffer caAttribute = { (uint8_t *)caName[index], strlen(caName[index]) };
ret = HITLS_PKCS12_BagAddAttr(otherCertBag, BSL_CID_FRIENDLYNAME, &caAttribute);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to add the other cert friendlyname, errCode = 0x%x.\n", ret);
HITLS_PKCS12_BagFree(otherCertBag);
return HITLS_APP_X509_FAIL;
}
++index;
}
ret = HITLS_PKCS12_Ctrl(p12, HITLS_PKCS12_ADD_CERTBAG, otherCertBag, 0);
HITLS_PKCS12_BagFree(otherCertBag);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to add the other cert bag, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
pstCert = BSL_LIST_GET_NEXT(certList);
}
if (index < caNameSize) {
AppPrintError("pkcs12: Warning: Redundant %zu -caname options.\n", caNameSize - index);
}
return HITLS_APP_SUCCESS;
}
static int32_t PrintPkcs12(Pkcs12OptCtx *opt)
{
int32_t ret = HITLS_APP_SUCCESS;
uint8_t *passOutBuf = NULL;
uint32_t passOutBufLen = 0;
BSL_UI_ReadPwdParam passParam = { "Export passwd", opt->genOpt.outFile, true };
if (HITLS_APP_GetPasswd(&passParam, &opt->passout, &passOutBuf, &passOutBufLen) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
HITLS_PKCS12_EncodeParam encodeParam = { 0 };
CRYPT_Pbkdf2Param certPbParam = { 0 };
certPbParam.pbesId = opt->certPbe;
certPbParam.pbkdfId = BSL_CID_PBKDF2;
certPbParam.hmacId = CRYPT_MAC_HMAC_SHA256;
certPbParam.symId = CRYPT_CIPHER_AES256_CBC;
certPbParam.saltLen = DEFAULT_SALTLEN;
certPbParam.pwd = passOutBuf;
certPbParam.pwdLen = passOutBufLen;
certPbParam.itCnt = DEFAULT_ITCNT;
CRYPT_EncodeParam certEncParam = { CRYPT_DERIVE_PBKDF2, &certPbParam };
HITLS_PKCS12_KdfParam hmacParam = { 0 };
hmacParam.macId = opt->macAlg;
hmacParam.saltLen = DEFAULT_SALTLEN;
hmacParam.pwd = passOutBuf;
hmacParam.pwdLen = passOutBufLen;
hmacParam.itCnt = DEFAULT_ITCNT;
HITLS_PKCS12_MacParam macParam = { .para = &hmacParam, .algId = BSL_CID_PKCS12KDF };
encodeParam.macParam = macParam;
encodeParam.encParam = certEncParam;
BSL_Buffer p12Buff = { 0 };
ret = HITLS_PKCS12_GenBuff(BSL_FORMAT_ASN1, opt->p12, &encodeParam, true, &p12Buff);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to generate pkcs12, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_APP_OptWriteUio(opt->wUio, p12Buff.data, p12Buff.dataLen, HITLS_APP_FORMAT_ASN1);
BSL_SAL_FREE(p12Buff.data);
return ret;
}
static int32_t MakePfxAndOutput(Pkcs12OptCtx *opt)
{
// Create pkcs12 info
opt->p12 = HITLS_PKCS12_New();
if (opt->p12 == NULL) {
AppPrintError("pkcs12: Failed to create pkcs12 info.\n");
return HITLS_APP_X509_FAIL;
}
// add key to p12
int32_t ret = AddKeyBagToP12(opt->outPutOpt.name, opt->pkey, opt->p12);
if (ret != HITLS_PKI_SUCCESS) {
return ret;
}
// add user cert to p12
ret = AddUserCertBagToP12(opt->outPutOpt.name, opt->userCert, opt->p12);
if (ret != HITLS_PKI_SUCCESS) {
return ret;
}
// add other cert to p12
ret = AddOtherCertListBagToP12(opt->outPutOpt.caName, opt->outPutOpt.caNameSize, opt->certList, opt->p12);
if (ret != HITLS_PKI_SUCCESS) {
return ret;
}
// Cal localKeyId to p12
int32_t mdId = CRYPT_MD_SHA1;
ret = HITLS_PKCS12_Ctrl(opt->p12, HITLS_PKCS12_GEN_LOCALKEYID, &mdId, sizeof(CRYPT_MD_AlgId));
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to set the local keyid, errCode = 0x%x.\n", ret);
return HITLS_APP_X509_FAIL;
}
return PrintPkcs12(opt);
}
static int32_t CreatePkcs12File(Pkcs12OptCtx *opt)
{
int32_t ret = LoadCertList(opt->genOpt.inFile, &opt->certList);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkcs12: Failed to load cert list.\n");
return ret;
}
opt->pkey = HITLS_APP_LoadPrvKey(opt->outPutOpt.inKey, BSL_FORMAT_PEM, &opt->passin);
if (opt->pkey == NULL) {
AppPrintError("pkcs12: Load key failed.\n");
return HITLS_APP_LOAD_KEY_FAIL;
}
ret = CheckCertListWithPriKey(opt->certList, opt->pkey, &opt->userCert);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (opt->outPutOpt.chain) {
ret = ParseAndAddCertChain(opt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
}
return MakePfxAndOutput(opt);
}
static int32_t OutPutCert(const char *certType, BSL_UIO *wUio, HITLS_X509_Cert *cert)
{
BSL_Buffer encodeCert = {};
int32_t ret = HITLS_X509_CertGenBuff(BSL_FORMAT_PEM, cert, &encodeCert);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: encode %s failed, errCode = 0x%0x.\n", certType, ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_APP_OptWriteUio(wUio, encodeCert.data, encodeCert.dataLen, HITLS_APP_FORMAT_PEM);
BSL_SAL_Free(encodeCert.data);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("pkcs12: Failed to print the cert\n");
return ret;
}
return HITLS_APP_SUCCESS;
}
static int32_t OutPutCerts(Pkcs12OptCtx *opt)
{
// Output the user cert.
int32_t ret = HITLS_PKCS12_Ctrl(opt->p12, HITLS_PKCS12_GET_ENTITY_CERT, &opt->userCert, 0);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to get user cert, errCode = 0x%0x.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = OutPutCert("user cert", opt->wUio, opt->userCert);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// only output user cert
if (opt->importOpt.clcerts) {
return HITLS_APP_SUCCESS;
}
// Output other cert and cert chain
HITLS_PKCS12_Bag *pstCertBag = BSL_LIST_GET_FIRST(opt->p12->certList);
while (pstCertBag != NULL) {
ret = OutPutCert("cert chain", opt->wUio, pstCertBag->value.cert);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
pstCertBag = BSL_LIST_GET_NEXT(opt->p12->certList);
}
return HITLS_APP_SUCCESS;
}
static int32_t OutPutKey(Pkcs12OptCtx *opt)
{
// Output private key
int32_t ret = HITLS_PKCS12_Ctrl(opt->p12, HITLS_PKCS12_GET_ENTITY_KEY, &opt->pkey, 0);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to get private key, errCode = 0x%0x.\n", ret);
return HITLS_APP_X509_FAIL;
}
AppKeyPrintParam param = { opt->genOpt.outFile, BSL_FORMAT_PEM, opt->cipherAlgCid, false, false};
return HITLS_APP_PrintPrvKeyByUio(opt->wUio, opt->pkey, ¶m, &opt->passout);
}
static int32_t OutPutCertsAndKey(Pkcs12OptCtx *opt)
{
int32_t ret = OutPutCerts(opt);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return OutPutKey(opt);
}
static int32_t ParsePkcs12File(Pkcs12OptCtx *opt)
{
BSL_UI_ReadPwdParam passParam = { "Import passwd", NULL, false };
BSL_Buffer encPwd = { (uint8_t *)"", 0 };
if (HITLS_APP_GetPasswd(&passParam, &opt->passin, &encPwd.data, &encPwd.dataLen) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
HITLS_PKCS12_PwdParam param = {
.encPwd = &encPwd,
.macPwd = &encPwd,
};
int32_t ret = HITLS_PKCS12_ParseFile(BSL_FORMAT_ASN1, opt->genOpt.inFile, ¶m, &opt->p12, true);
(void)memset_s(encPwd.data, encPwd.dataLen, 0, encPwd.dataLen);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("pkcs12: Failed to parse the %s pkcs12 file, errCode = 0x%x.\n", opt->genOpt.inFile, ret);
return HITLS_APP_X509_FAIL;
}
return OutPutCertsAndKey(opt);
}
static int32_t CheckParam(Pkcs12OptCtx *opt)
{
// In all cases, the infile must exist.
int32_t ret = CheckInFile(opt->genOpt.inFile, "in file");
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (opt->outPutOpt.export) {
// In the export cases, the private key must be available.
ret = CheckInFile(opt->outPutOpt.inKey, "private key");
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (opt->importOpt.clcerts) {
AppPrintError("pkcs12: Warning: -clcerts option ignored with -export\n");
}
if (opt->importOpt.cipherAlgName != NULL) {
AppPrintError("pkcs12: Warning: output encryption option -%s ignored with -export\n",
opt->importOpt.cipherAlgName);
}
// When adding a certificate chain, caFile must be exist.
if (opt->outPutOpt.chain) {
ret = CheckInFile(opt->outPutOpt.caFile, "ca file");
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
} else if (opt->outPutOpt.caFile != NULL) {
AppPrintError("pkcs12: Warning: ignoring -CAfile since -chain is not given\n");
}
} else {
if (opt->outPutOpt.chain) {
AppPrintError("pkcs12: Warning: ignoring -chain since -export is not given\n");
}
if (opt->outPutOpt.caFile != NULL) {
AppPrintError("pkcs12: Warning: ignoring -CAfile since -export is not given\n");
}
if (opt->outPutOpt.keyPbeArg != NULL) {
AppPrintError("pkcs12: Warning: ignoring -keypbe since -export is not given\n");
}
if (opt->outPutOpt.certPbeArg != NULL) {
AppPrintError("pkcs12: Warning: ignoring -certpbe since -export is not given\n");
}
if (opt->outPutOpt.macAlgArg != NULL) {
AppPrintError("pkcs12: Warning: ignoring -macalg since -export is not given\n");
}
if (opt->outPutOpt.name != NULL) {
AppPrintError("pkcs12: Warning: ignoring -name since -export is not given\n");
}
if (opt->outPutOpt.caNameSize != 0) {
AppPrintError("pkcs12: Warning: ignoring -caname since -export is not given\n");
}
}
return CheckOutFile(opt->genOpt.outFile);
}
static void InitPkcs12OptCtx(Pkcs12OptCtx *optCtx)
{
optCtx->pkey = NULL;
optCtx->passin = NULL;
optCtx->passout = NULL;
optCtx->cipherAlgCid = CRYPT_CIPHER_AES256_CBC;
optCtx->macAlg = BSL_CID_SHA256;
optCtx->certPbe = BSL_CID_PBES2;
optCtx->keyPbe = BSL_CID_PBES2;
optCtx->p12 = NULL;
optCtx->store = NULL;
optCtx->certList = NULL;
optCtx->caCertList = NULL;
optCtx->outCertChainList = NULL;
optCtx->userCert = NULL;
optCtx->wUio = NULL;
optCtx->genOpt.inFile = NULL;
optCtx->genOpt.outFile = NULL;
optCtx->genOpt.passInArg = NULL;
optCtx->genOpt.passOutArg = NULL;
optCtx->importOpt.clcerts = false;
optCtx->importOpt.cipherAlgName = NULL;
optCtx->outPutOpt.inKey = NULL;
optCtx->outPutOpt.name = NULL;
optCtx->outPutOpt.caNameSize = 0;
optCtx->outPutOpt.caFile = NULL;
optCtx->outPutOpt.macAlgArg = NULL;
optCtx->outPutOpt.certPbeArg = NULL;
optCtx->outPutOpt.keyPbeArg = NULL;
optCtx->outPutOpt.chain = false;
optCtx->outPutOpt.export = false;
}
static void UnInitPkcs12OptCtx(Pkcs12OptCtx *optCtx)
{
CRYPT_EAL_PkeyFreeCtx(optCtx->pkey);
optCtx->pkey = NULL;
if (optCtx->passin != NULL) {
BSL_SAL_ClearFree(optCtx->passin, strlen(optCtx->passin));
}
if (optCtx->passout != NULL) {
BSL_SAL_ClearFree(optCtx->passout, strlen(optCtx->passout));
}
HITLS_PKCS12_Free(optCtx->p12);
optCtx->p12 = NULL;
HITLS_X509_StoreCtxFree(optCtx->store);
optCtx->store = NULL;
HITLS_X509_StoreCtxFree(optCtx->dupStore);
optCtx->dupStore = NULL;
BSL_LIST_FREE(optCtx->caCertList, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
BSL_LIST_FREE(optCtx->outCertChainList, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
BSL_LIST_FREE(optCtx->certList, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
HITLS_X509_CertFree(optCtx->userCert);
optCtx->userCert = NULL;
BSL_UIO_Free(optCtx->wUio);
optCtx->wUio = NULL;
BSL_SAL_FREE(optCtx);
}
static int32_t HandlePKCS12Opt(Pkcs12OptCtx *opt)
{
// 1.Read and Parse pass arg
if ((HITLS_APP_ParsePasswd(opt->genOpt.passInArg, &opt->passin) != HITLS_APP_SUCCESS) ||
(HITLS_APP_ParsePasswd(opt->genOpt.passOutArg, &opt->passout) != HITLS_APP_SUCCESS)) {
return HITLS_APP_PASSWD_FAIL;
}
// 2.Create output uio
opt->wUio = HITLS_APP_UioOpen(opt->genOpt.outFile, 'w', 0);
if (opt->wUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(opt->wUio, true);
return opt->outPutOpt.export ? CreatePkcs12File(opt) : ParsePkcs12File(opt);
}
// pkcs12 main function
int32_t HITLS_PKCS12Main(int argc, char *argv[])
{
Pkcs12OptCtx *opt = BSL_SAL_Calloc(1, sizeof(Pkcs12OptCtx));
if (opt == NULL) {
AppPrintError("pkcs12: Failed to create pkcs12 ctx.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
InitPkcs12OptCtx(opt);
int32_t ret = HITLS_APP_SUCCESS;
do {
ret = ParseOpt(argc, argv, opt);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = CheckParam(opt);
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR, "provider=default", NULL, 0, NULL);
if (ret != CRYPT_SUCCESS) {
AppPrintError("pkcs12: Failed to initialize the random number, errCode = 0x%x.\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = HandlePKCS12Opt(opt);
} while (false);
UnInitPkcs12OptCtx(opt);
CRYPT_EAL_RandDeinitEx(NULL);
return ret;
} | 2302_82127028/openHiTLS-examples_5062 | apps/src/app_pkcs12.c | C | unknown | 36,641 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_pkey.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <securec.h>
#include <linux/limits.h>
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_list.h"
#include "app_utils.h"
#include "bsl_sal.h"
#include "crypt_errno.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_rand.h"
typedef enum {
HITLS_APP_OPT_IN = 2,
HITLS_APP_OPT_PASSIN,
HITLS_APP_OPT_OUT,
HITLS_APP_OPT_PUBOUT,
HITLS_APP_OPT_CIPHER_ALG,
HITLS_APP_OPT_PASSOUT,
HITLS_APP_OPT_TEXT,
HITLS_APP_OPT_NOOUT,
} HITLSOptType;
const HITLS_CmdOption g_pKeyOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"in", HITLS_APP_OPT_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input key"},
{"passin", HITLS_APP_OPT_PASSIN, HITLS_APP_OPT_VALUETYPE_STRING, "Input file pass phrase source"},
{"out", HITLS_APP_OPT_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"pubout", HITLS_APP_OPT_PUBOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Output public key, not private"},
{"", HITLS_APP_OPT_CIPHER_ALG, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Any supported cipher"},
{"passout", HITLS_APP_OPT_PASSOUT, HITLS_APP_OPT_VALUETYPE_STRING, "Output file pass phrase source"},
{"text", HITLS_APP_OPT_TEXT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print key in text(only RSA is supported)"},
{"noout", HITLS_APP_OPT_NOOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Do not output the key in encoded form"},
{NULL},
};
typedef struct {
char *inFilePath;
BSL_ParseFormat inFormat;
char *passInArg;
bool pubin;
} InputKeyPara;
typedef struct {
char *outFilePath;
BSL_ParseFormat outFormat;
char *passOutArg;
bool pubout;
bool text;
bool noout;
} OutPutKeyPara;
typedef struct {
CRYPT_EAL_PkeyCtx *pkey;
char *passin;
char *passout;
BSL_UIO *wUio;
int32_t cipherAlgCid;
InputKeyPara inPara;
OutPutKeyPara outPara;
} PkeyOptCtx;
typedef int32_t (*PkeyOptHandleFunc)(PkeyOptCtx *);
typedef struct {
int optType;
PkeyOptHandleFunc func;
} PkeyOptHandleTable;
static int32_t PkeyOptErr(PkeyOptCtx *optCtx)
{
(void)optCtx;
AppPrintError("pkey: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t PkeyOptHelp(PkeyOptCtx *optCtx)
{
(void)optCtx;
HITLS_APP_OptHelpPrint(g_pKeyOpts);
return HITLS_APP_HELP;
}
static int32_t PkeyOptIn(PkeyOptCtx *optCtx)
{
optCtx->inPara.inFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptPassin(PkeyOptCtx *optCtx)
{
optCtx->inPara.passInArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptOut(PkeyOptCtx *optCtx)
{
optCtx->outPara.outFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptPubout(PkeyOptCtx *optCtx)
{
optCtx->outPara.pubout = true;
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptCipher(PkeyOptCtx *optCtx)
{
const char *name = HITLS_APP_OptGetUnKownOptName();
return HITLS_APP_GetAndCheckCipherOpt(name, &optCtx->cipherAlgCid);
}
static int32_t PkeyOptPassout(PkeyOptCtx *optCtx)
{
optCtx->outPara.passOutArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptText(PkeyOptCtx *optCtx)
{
optCtx->outPara.text = true;
return HITLS_APP_SUCCESS;
}
static int32_t PkeyOptNoout(PkeyOptCtx *optCtx)
{
optCtx->outPara.noout = true;
return HITLS_APP_SUCCESS;
}
static const PkeyOptHandleTable g_pkeyOptHandleTable[] = {
{HITLS_APP_OPT_ERR, PkeyOptErr},
{HITLS_APP_OPT_HELP, PkeyOptHelp},
{HITLS_APP_OPT_IN, PkeyOptIn},
{HITLS_APP_OPT_PASSIN, PkeyOptPassin},
{HITLS_APP_OPT_OUT, PkeyOptOut},
{HITLS_APP_OPT_PUBOUT, PkeyOptPubout},
{HITLS_APP_OPT_CIPHER_ALG, PkeyOptCipher},
{HITLS_APP_OPT_PASSOUT, PkeyOptPassout},
{HITLS_APP_OPT_TEXT, PkeyOptText},
{HITLS_APP_OPT_NOOUT, PkeyOptNoout},
};
static int32_t ParsePkeyOpt(int argc, char *argv[], PkeyOptCtx *optCtx)
{
int32_t ret = HITLS_APP_OptBegin(argc, argv, g_pKeyOpts);
if (ret != HITLS_APP_SUCCESS) {
HITLS_APP_OptEnd();
AppPrintError("error in opt begin.\n");
return ret;
}
int optType = HITLS_APP_OPT_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF)) {
for (size_t i = 0; i < (sizeof(g_pkeyOptHandleTable) / sizeof(g_pkeyOptHandleTable[0])); ++i) {
if (optType == g_pkeyOptHandleTable[i].optType) {
ret = g_pkeyOptHandleTable[i].func(optCtx);
break;
}
}
}
// Obtain the number of parameters that cannot be parsed in the current version,
// and print the error inFormation and help list.
if ((ret == HITLS_APP_SUCCESS) && (HITLS_APP_GetRestOptNum() != 0)) {
AppPrintError("Extra arguments given.\n");
AppPrintError("pkey: Use -help for summary.\n");
ret = HITLS_APP_OPT_UNKOWN;
}
HITLS_APP_OptEnd();
return ret;
}
static int32_t HandlePkeyOpt(int argc, char *argv[], PkeyOptCtx *optCtx)
{
int32_t ret = ParsePkeyOpt(argc, argv, optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// 1. Read Password
if ((optCtx->cipherAlgCid == CRYPT_CIPHER_MAX) && (optCtx->outPara.passOutArg != NULL)) {
AppPrintError("Warning: The -passout option is ignored without a cipher option.\n");
}
if ((HITLS_APP_ParsePasswd(optCtx->inPara.passInArg, &optCtx->passin) != HITLS_APP_SUCCESS) ||
(HITLS_APP_ParsePasswd(optCtx->outPara.passOutArg, &optCtx->passout) != HITLS_APP_SUCCESS)) {
return HITLS_APP_PASSWD_FAIL;
}
// 2. Load the public or private key
if (optCtx->inPara.pubin) {
optCtx->pkey = HITLS_APP_LoadPubKey(optCtx->inPara.inFilePath, optCtx->inPara.inFormat);
} else {
optCtx->pkey = HITLS_APP_LoadPrvKey(optCtx->inPara.inFilePath, optCtx->inPara.inFormat, &optCtx->passin);
}
if (optCtx->pkey == NULL) {
return HITLS_APP_LOAD_KEY_FAIL;
}
// 3. Output the public or private key.
if (optCtx->outPara.pubout) {
return HITLS_APP_PrintPubKey(optCtx->pkey, optCtx->outPara.outFilePath, optCtx->outPara.outFormat);
}
optCtx->wUio = HITLS_APP_UioOpen(optCtx->outPara.outFilePath, 'w', 0);
if (optCtx->wUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(optCtx->wUio, true);
AppKeyPrintParam param = { optCtx->outPara.outFilePath, BSL_FORMAT_PEM, optCtx->cipherAlgCid,
optCtx->outPara.text, optCtx->outPara.noout};
return HITLS_APP_PrintPrvKeyByUio(optCtx->wUio, optCtx->pkey, ¶m, &optCtx->passout);
}
static void InitPkeyOptCtx(PkeyOptCtx *optCtx)
{
optCtx->pkey = NULL;
optCtx->passin = NULL;
optCtx->passout = NULL;
optCtx->cipherAlgCid = CRYPT_CIPHER_MAX;
optCtx->inPara.inFilePath = NULL;
optCtx->inPara.inFormat = BSL_FORMAT_PEM;
optCtx->inPara.passInArg = NULL;
optCtx->inPara.pubin = false;
optCtx->outPara.outFilePath = NULL;
optCtx->outPara.outFormat = BSL_FORMAT_PEM;
optCtx->outPara.passOutArg = NULL;
optCtx->outPara.pubout = false;
optCtx->outPara.text = false;
optCtx->outPara.noout = false;
}
static void UnInitPkeyOptCtx(PkeyOptCtx *optCtx)
{
CRYPT_EAL_PkeyFreeCtx(optCtx->pkey);
optCtx->pkey = NULL;
if (optCtx->passin != NULL) {
BSL_SAL_ClearFree(optCtx->passin, strlen(optCtx->passin));
}
if (optCtx->passout != NULL) {
BSL_SAL_ClearFree(optCtx->passout, strlen(optCtx->passout));
}
BSL_UIO_Free(optCtx->wUio);
optCtx->wUio = NULL;
}
// pkey main function
int32_t HITLS_PkeyMain(int argc, char *argv[])
{
PkeyOptCtx optCtx = {};
InitPkeyOptCtx(&optCtx);
int32_t ret = HITLS_APP_SUCCESS;
do {
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR,
"provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) {
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = HandlePkeyOpt(argc, argv, &optCtx);
} while (false);
CRYPT_EAL_RandDeinitEx(NULL);
UnInitPkeyOptCtx(&optCtx);
return ret;
} | 2302_82127028/openHiTLS-examples_5062 | apps/src/app_pkey.c | C | unknown | 8,914 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include "securec.h"
#include "bsl_uio.h"
#include "bsl_errno.h"
#include "bsl_sal.h"
#include "app_errno.h"
#define X509_PRINT_MAX_LAYER 10
#define X509_PRINT_LAYER_INDENT 4
#define X509_PRINT_MAX_INDENT (X509_PRINT_MAX_LAYER * X509_PRINT_LAYER_INDENT)
#define LOG_BUFFER_LEN 2048
static BSL_UIO *g_errorUIO = NULL;
int32_t AppUioVPrint(BSL_UIO *uio, const char *format, va_list args)
{
int32_t ret = 0;
if (uio == NULL) {
return HITLS_APP_INVALID_ARG;
}
uint32_t writeLen = 0;
char *buf = (char *)BSL_SAL_Calloc(LOG_BUFFER_LEN + 1, sizeof(char));
if (buf == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
ret = vsnprintf_s(buf, LOG_BUFFER_LEN + 1, LOG_BUFFER_LEN, format, args);
if (ret < EOK) {
BSL_SAL_FREE(buf);
return HITLS_APP_SECUREC_FAIL;
}
ret = BSL_UIO_Write(uio, buf, ret, &writeLen);
BSL_SAL_FREE(buf);
return ret;
}
int32_t AppPrint(BSL_UIO *uio, const char *format, ...)
{
if (uio == NULL) {
return HITLS_APP_INVALID_ARG;
}
va_list args;
va_start(args, format);
int32_t ret = AppUioVPrint(uio, format, args);
va_end(args);
return ret;
}
void AppPrintError(const char *format, ...)
{
if (g_errorUIO == NULL) {
return;
}
va_list args;
va_start(args, format);
(void)AppUioVPrint(g_errorUIO, format, args);
va_end(args);
return;
}
int32_t AppPrintErrorUioInit(FILE *fp)
{
if (fp == NULL) {
return HITLS_APP_INVALID_ARG;
}
if (g_errorUIO != NULL) {
return HITLS_APP_SUCCESS;
}
g_errorUIO = BSL_UIO_New(BSL_UIO_FileMethod());
if (g_errorUIO == NULL) {
return BSL_UIO_MEM_ALLOC_FAIL;
}
return BSL_UIO_Ctrl(g_errorUIO, BSL_UIO_FILE_PTR, 0, (void *)fp);
}
void AppPrintErrorUioUnInit(void)
{
if (g_errorUIO != NULL) {
BSL_UIO_Free(g_errorUIO);
g_errorUIO = NULL;
}
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_print.c | C | unknown | 2,515 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifdef HITLS_CRYPTO_PROVIDER
#include "app_provider.h"
#include <linux/limits.h>
#include "string.h"
#include "securec.h"
#include "app_errno.h"
#include "app_print.h"
#include "bsl_sal.h"
#include "bsl_errno.h"
#include "crypt_errno.h"
#include "crypt_eal_provider.h"
static CRYPT_EAL_LibCtx *g_libCtx = NULL;
CRYPT_EAL_LibCtx *APP_GetCurrent_LibCtx(void)
{
return g_libCtx;
}
CRYPT_EAL_LibCtx *APP_Create_LibCtx(void)
{
if (g_libCtx == NULL) {
g_libCtx = CRYPT_EAL_LibCtxNew();
}
return g_libCtx;
}
int32_t HITLS_APP_LoadProvider(const char *searchPath, const char *providerName)
{
CRYPT_EAL_LibCtx *ctx = g_libCtx;
int32_t ret = HITLS_APP_SUCCESS;
if (ctx == NULL) {
(void)AppPrintError("Lib not initialized\n");
return HITLS_APP_INVALID_ARG;
}
if (searchPath != NULL) {
ret = CRYPT_EAL_ProviderSetLoadPath(ctx, searchPath);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("Load SetSearchPath failed. ERR:%d\n", ret);
return ret;
}
}
if (providerName != NULL) {
ret = CRYPT_EAL_ProviderLoad(ctx, BSL_SAL_LIB_FMT_OFF, providerName, NULL, NULL);
if (ret != HITLS_APP_SUCCESS) {
(void)AppPrintError("Load provider failed. ERR:%d\n", ret);
}
}
return ret;
}
#endif // HITLS_CRYPTO_PROVIDER
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_provider.c | C | unknown | 1,903 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_rand.h"
#include <stddef.h>
#include <linux/limits.h>
#include "securec.h"
#include "bsl_uio.h"
#include "crypt_eal_rand.h"
#include "bsl_base64.h"
#include "crypt_errno.h"
#include "bsl_errno.h"
#include "bsl_sal.h"
#include "app_opt.h"
#include "app_print.h"
#include "app_errno.h"
#include "app_function.h"
#define MAX_RANDOM_LEN 4096
typedef enum OptionChoice {
HITLS_APP_OPT_RAND_ERR = -1,
HITLS_APP_OPT_RAND_EOF = 0,
HITLS_APP_OPT_RAND_NUMBITS = HITLS_APP_OPT_RAND_EOF,
HITLS_APP_OPT_RAND_HELP = 1, // The value of help type of each opt is 1. The following options can be customized.
HITLS_APP_OPT_RAND_HEX = 2,
HITLS_APP_OPT_RAND_BASE64,
HITLS_APP_OPT_RAND_OUT,
} HITLSOptType;
HITLS_CmdOption g_randOpts[] = {
{"help", HITLS_APP_OPT_RAND_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"hex", HITLS_APP_OPT_RAND_HEX, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Hex-encoded output"},
{"base64", HITLS_APP_OPT_RAND_BASE64, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Base64-encoded output"},
{"out", HITLS_APP_OPT_RAND_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"numbytes", HITLS_APP_OPT_RAND_NUMBITS, HITLS_APP_OPT_VALUETYPE_PARAMTERS, "Random byte length"},
{NULL}};
static int32_t OptParse(char **outfile, int32_t *format);
static int32_t RandNumOut(int32_t randNumLen, char *outfile, int format);
int32_t HITLS_RandMain(int argc, char **argv)
{
char *outfile = NULL; // output file name
int32_t format = HITLS_APP_FORMAT_BINARY; // default binary output
int32_t randNumLen = 0; // length of the random number entered by the user
int32_t mainRet = HITLS_APP_SUCCESS; // return value of the main function
mainRet = HITLS_APP_OptBegin(argc, argv, g_randOpts);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
mainRet = OptParse(&outfile, &format);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
// 获取用户输入即要生成的随机数长度
int unParseParamNum = HITLS_APP_GetRestOptNum();
char** unParseParam = HITLS_APP_GetRestOpt();
if (unParseParamNum != 1) {
(void)AppPrintError("Extra arguments given.\n");
(void)AppPrintError("rand: Use -help for summary.\n");
mainRet = HITLS_APP_OPT_UNKOWN;
goto end;
} else {
mainRet = HITLS_APP_OptGetInt(unParseParam[0], &randNumLen);
if (mainRet != HITLS_APP_SUCCESS || randNumLen <= 0) {
mainRet = HITLS_APP_OPT_VALUE_INVALID;
(void)AppPrintError("Valid Range[1, 2147483647]\n");
goto end;
}
}
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR,
"provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) {
mainRet = HITLS_APP_CRYPTO_FAIL;
goto end;
}
mainRet = RandNumOut(randNumLen, outfile, format);
end:
CRYPT_EAL_RandDeinitEx(NULL);
HITLS_APP_OptEnd();
return mainRet;
}
static int32_t OptParse(char **outfile, int32_t *format)
{
HITLSOptType optType;
int ret = HITLS_APP_SUCCESS;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_RAND_EOF) {
switch (optType) {
case HITLS_APP_OPT_RAND_EOF:
case HITLS_APP_OPT_RAND_ERR:
ret = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("rand: Use -help for summary.\n");
return ret;
case HITLS_APP_OPT_RAND_HELP:
ret = HITLS_APP_HELP;
(void)HITLS_APP_OptHelpPrint(g_randOpts);
return ret;
case HITLS_APP_OPT_RAND_OUT:
*outfile = HITLS_APP_OptGetValueStr();
if (*outfile == NULL || strlen(*outfile) >= PATH_MAX) {
AppPrintError("The length of outfile error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_RAND_BASE64:
*format = HITLS_APP_FORMAT_BASE64;
break;
case HITLS_APP_OPT_RAND_HEX:
*format = HITLS_APP_FORMAT_HEX;
break;
default:
break;
}
}
return HITLS_APP_SUCCESS;
}
static int32_t RandNumOut(int32_t randNumLen, char *outfile, int format)
{
int ret = HITLS_APP_SUCCESS;
BSL_UIO *uio;
uio = HITLS_APP_UioOpen(outfile, 'w', 0);
if (uio == NULL) {
return HITLS_APP_UIO_FAIL;
}
if (outfile != NULL) {
BSL_UIO_SetIsUnderlyingClosedByUio(uio, true);
}
while (randNumLen > 0) {
uint8_t outBuf[MAX_RANDOM_LEN] = {0};
uint32_t outLen = randNumLen;
if (outLen > MAX_RANDOM_LEN) {
outLen = MAX_RANDOM_LEN;
}
int32_t randRet = CRYPT_EAL_RandbytesEx(NULL, outBuf, outLen);
if (randRet != CRYPT_SUCCESS) {
BSL_UIO_Free(uio);
(void)AppPrintError("Failed to generate a random number.\n");
return HITLS_APP_CRYPTO_FAIL;
}
ret = HITLS_APP_OptWriteUio(uio, outBuf, outLen, format);
if (ret != HITLS_APP_SUCCESS) {
BSL_UIO_Free(uio);
return ret;
}
randNumLen -= outLen;
if (format != HITLS_APP_FORMAT_BINARY && randNumLen == 0) {
char buf[1] = {'\n'}; // Enter a newline character at the end.
uint32_t bufLen = 1;
uint32_t writeLen = 0;
ret = BSL_UIO_Write(uio, buf, bufLen, &writeLen);
if (ret != BSL_SUCCESS) {
BSL_UIO_Free(uio);
(void)AppPrintError("Failed to enter the newline character\n");
return ret;
}
}
}
BSL_UIO_Free(uio);
return HITLS_APP_SUCCESS;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_rand.c | C | unknown | 6,364 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_req.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <securec.h>
#include <linux/limits.h>
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_opt.h"
#include "app_list.h"
#include "bsl_ui.h"
#include "app_utils.h"
#include "bsl_sal.h"
#include "bsl_errno.h"
#include "crypt_errno.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_rand.h"
#include "hitls_csr_local.h"
#include "hitls_pki_errno.h"
#define HITLS_APP_REQ_SECTION "req"
#define HITLS_APP_REQ_EXTENSION_SECTION "req_extensions"
typedef enum {
HITLS_REQ_APP_OPT_NEW = 2,
HITLS_REQ_APP_OPT_VERIFY,
HITLS_REQ_APP_OPT_MDALG,
HITLS_REQ_APP_OPT_SUBJ,
HITLS_REQ_APP_OPT_KEY,
HITLS_REQ_APP_OPT_KEYFORM,
HITLS_REQ_APP_OPT_PASSIN,
HITLS_REQ_APP_OPT_PASSOUT,
HITLS_REQ_APP_OPT_NOOUT,
HITLS_REQ_APP_OPT_TEXT,
HITLS_REQ_APP_OPT_CONFIG,
HITLS_REQ_APP_OPT_IN,
HITLS_REQ_APP_OPT_INFORM,
HITLS_REQ_APP_OPT_OUT,
HITLS_REQ_APP_OPT_OUTFORM,
} HITLSOptType;
const HITLS_CmdOption g_reqOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"new", HITLS_REQ_APP_OPT_NEW, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "New request"},
{"verify", HITLS_REQ_APP_OPT_VERIFY, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Verify self-signature on the request"},
{"mdalg", HITLS_REQ_APP_OPT_MDALG, HITLS_APP_OPT_VALUETYPE_STRING, "Any supported digest"},
{"subj", HITLS_REQ_APP_OPT_SUBJ, HITLS_APP_OPT_VALUETYPE_STRING, "Set or modify subject of request or cert"},
{"key", HITLS_REQ_APP_OPT_KEY, HITLS_APP_OPT_VALUETYPE_STRING, "Key for signing, and to include unless -in given"},
{"keyform", HITLS_REQ_APP_OPT_KEYFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Input format - DER or PEM"},
{"passin", HITLS_REQ_APP_OPT_PASSIN, HITLS_APP_OPT_VALUETYPE_STRING, "Private key and certificate password source"},
{"passout", HITLS_REQ_APP_OPT_PASSOUT, HITLS_APP_OPT_VALUETYPE_STRING, "Output file pass phrase source"},
{"noout", HITLS_REQ_APP_OPT_NOOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Do not output REQ"},
{"text", HITLS_REQ_APP_OPT_TEXT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Text form of request"},
{"config", HITLS_REQ_APP_OPT_CONFIG, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Request template file"},
{"in", HITLS_REQ_APP_OPT_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "X.509 request input file (default stdin)"},
{"inform", HITLS_REQ_APP_OPT_INFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Input format - DER or PEM"},
{"out", HITLS_REQ_APP_OPT_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"outform", HITLS_REQ_APP_OPT_OUTFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Output format - DER or PEM"},
{NULL},
};
typedef struct {
char *inFilePath;
BSL_ParseFormat inFormat;
bool verify;
} ReqGeneralOptions;
typedef struct {
bool new;
char *configFilePath;
bool text;
char *subj;
} ReqCertOptions;
typedef struct {
char *keyFilePath;
BSL_ParseFormat keyFormat;
char *passInArg;
char *passOutArg;
int32_t mdalgId;
} ReqKeysAndSignOptions;
typedef struct {
char *outFilePath;
BSL_ParseFormat outFormat;
bool noout;
} ReqOutputOptions;
typedef struct {
ReqGeneralOptions genOpt;
ReqCertOptions certOpt;
ReqKeysAndSignOptions keyAndSignOpt;
ReqOutputOptions outPutOpt;
char *passin;
char *passout;
HITLS_X509_Csr *csr;
CRYPT_EAL_PkeyCtx *pkey;
BSL_UIO *wUio;
BSL_Buffer encode;
HITLS_X509_Ext *ext;
BSL_CONF *conf;
} ReqOptCtx;
typedef int32_t (*ReqOptHandleFunc)(ReqOptCtx *);
typedef struct {
int optType;
ReqOptHandleFunc func;
} ReqOptHandleTable;
static int32_t ReqOptErr(ReqOptCtx *optCtx)
{
(void)optCtx;
AppPrintError("req: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t ReqOptHelp(ReqOptCtx *optCtx)
{
(void)optCtx;
HITLS_APP_OptHelpPrint(g_reqOpts);
return HITLS_APP_HELP;
}
static int32_t ReqOptNew(ReqOptCtx *optCtx)
{
optCtx->certOpt.new = true;
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptVerify(ReqOptCtx *optCtx)
{
optCtx->genOpt.verify = true;
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptMdAlg(ReqOptCtx *optCtx)
{
return HITLS_APP_GetAndCheckHashOpt(HITLS_APP_OptGetValueStr(), &optCtx->keyAndSignOpt.mdalgId);
}
static int32_t ReqOptSubj(ReqOptCtx *optCtx)
{
optCtx->certOpt.subj = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptKey(ReqOptCtx *optCtx)
{
optCtx->keyAndSignOpt.keyFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptKeyFormat(ReqOptCtx *optCtx)
{
return HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_ANY,
&optCtx->keyAndSignOpt.keyFormat);
}
static int32_t ReqOptPassin(ReqOptCtx *optCtx)
{
optCtx->keyAndSignOpt.passInArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptPassout(ReqOptCtx *optCtx)
{
optCtx->keyAndSignOpt.passOutArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptNoout(ReqOptCtx *optCtx)
{
optCtx->outPutOpt.noout = true;
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptText(ReqOptCtx *optCtx)
{
optCtx->certOpt.text = true;
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptConfig(ReqOptCtx *optCtx)
{
optCtx->certOpt.configFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptIn(ReqOptCtx *optCtx)
{
optCtx->genOpt.inFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptInFormat(ReqOptCtx *optCtx)
{
return HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_PEMDER,
&optCtx->genOpt.inFormat);
}
static int32_t ReqOptOut(ReqOptCtx *optCtx)
{
optCtx->outPutOpt.outFilePath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t ReqOptOutFormat(ReqOptCtx *optCtx)
{
return HITLS_APP_OptGetFormatType(HITLS_APP_OptGetValueStr(), HITLS_APP_OPT_VALUETYPE_FMT_PEMDER,
&optCtx->outPutOpt.outFormat);
}
static const ReqOptHandleTable g_reqOptHandleTable[] = {
{HITLS_APP_OPT_ERR, ReqOptErr},
{HITLS_APP_OPT_HELP, ReqOptHelp},
{HITLS_REQ_APP_OPT_NEW, ReqOptNew},
{HITLS_REQ_APP_OPT_VERIFY, ReqOptVerify},
{HITLS_REQ_APP_OPT_MDALG, ReqOptMdAlg},
{HITLS_REQ_APP_OPT_SUBJ, ReqOptSubj},
{HITLS_REQ_APP_OPT_KEY, ReqOptKey},
{HITLS_REQ_APP_OPT_KEYFORM, ReqOptKeyFormat},
{HITLS_REQ_APP_OPT_PASSIN, ReqOptPassin},
{HITLS_REQ_APP_OPT_PASSOUT, ReqOptPassout},
{HITLS_REQ_APP_OPT_NOOUT, ReqOptNoout},
{HITLS_REQ_APP_OPT_TEXT, ReqOptText},
{HITLS_REQ_APP_OPT_CONFIG, ReqOptConfig},
{HITLS_REQ_APP_OPT_IN, ReqOptIn},
{HITLS_REQ_APP_OPT_INFORM, ReqOptInFormat},
{HITLS_REQ_APP_OPT_OUT, ReqOptOut},
{HITLS_REQ_APP_OPT_OUTFORM, ReqOptOutFormat},
};
static int32_t ParseReqOpt(ReqOptCtx *optCtx)
{
int32_t ret = HITLS_APP_SUCCESS;
int optType = HITLS_APP_OPT_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF)) {
for (size_t i = 0; i < (sizeof(g_reqOptHandleTable) / sizeof(g_reqOptHandleTable[0])); ++i) {
if (optType == g_reqOptHandleTable[i].optType) {
ret = g_reqOptHandleTable[i].func(optCtx);
break;
}
}
}
// Obtain the number of parameters that cannot be parsed in the current version,
// and print the error inFormation and help list.
if ((ret == HITLS_APP_SUCCESS) && (HITLS_APP_GetRestOptNum() != 0)) {
AppPrintError("Extra arguments given.\n");
AppPrintError("req: Use -help for summary.\n");
ret = HITLS_APP_OPT_UNKOWN;
}
if ((HITLS_APP_ParsePasswd(optCtx->keyAndSignOpt.passInArg, &optCtx->passin) != HITLS_APP_SUCCESS) ||
(HITLS_APP_ParsePasswd(optCtx->keyAndSignOpt.passOutArg, &optCtx->passout) != HITLS_APP_SUCCESS)) {
return HITLS_APP_PASSWD_FAIL;
}
return ret;
}
static int32_t ReqLoadPrvKey(ReqOptCtx *optCtx)
{
if (optCtx->keyAndSignOpt.keyFilePath == NULL) {
optCtx->pkey = HITLS_APP_GenRsaPkeyCtx(2048); // default 2048
if (optCtx->pkey == NULL) {
return HITLS_APP_CRYPTO_FAIL;
}
// default write to private.pem
int32_t ret = HITLS_APP_PrintPrvKey(
optCtx->pkey, "private.pem", BSL_FORMAT_PEM, CRYPT_CIPHER_AES256_CBC, &optCtx->passout);
return ret;
}
optCtx->pkey =
HITLS_APP_LoadPrvKey(optCtx->keyAndSignOpt.keyFilePath, optCtx->keyAndSignOpt.keyFormat, &optCtx->passin);
if (optCtx->pkey == NULL) {
return HITLS_APP_LOAD_KEY_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetRequestedExt(ReqOptCtx *optCtx)
{
if (optCtx->ext == NULL) {
return HITLS_APP_SUCCESS;
}
BslList *attrList = NULL;
int32_t ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_CSR_GET_ATTRIBUTES, &attrList, sizeof(BslList *));
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to get attr the csr, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_Attrs *attrs = NULL;
ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_CSR_GET_ATTRIBUTES, &attrs, sizeof(HITLS_X509_Attrs *));
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to get attrs from the csr, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_AttrCtrl(attrs, HITLS_X509_ATTR_SET_REQUESTED_EXTENSIONS, optCtx->ext, 0);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to set attr the csr, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t GetSignMdId(ReqOptCtx *optCtx)
{
CRYPT_PKEY_AlgId id = CRYPT_EAL_PkeyGetId(optCtx->pkey);
int32_t mdalgId = optCtx->keyAndSignOpt.mdalgId;
if (mdalgId == CRYPT_MD_MAX) {
if (id == CRYPT_PKEY_ED25519) {
mdalgId = CRYPT_MD_SHA512;
} else if ((id == CRYPT_PKEY_SM2)) {
mdalgId = CRYPT_MD_SM3;
} else {
mdalgId = CRYPT_MD_SHA256;
}
}
return mdalgId;
}
static int32_t ProcSanExt(BslCid cid, void *val, void *ctx)
{
HITLS_X509_Ext *ext = ctx;
switch (cid) {
case BSL_CID_CE_SUBJECTALTNAME:
return HITLS_X509_ExtCtrl(ext, HITLS_X509_EXT_SET_SAN, val, sizeof(HITLS_X509_ExtSan));
default:
return HITLS_APP_CONF_FAIL;
}
}
static int32_t ParseConf(ReqOptCtx *optCtx)
{
if (!optCtx->certOpt.new || (optCtx->certOpt.configFilePath == NULL)) {
return HITLS_APP_SUCCESS;
}
optCtx->ext = HITLS_X509_ExtNew(HITLS_X509_EXT_TYPE_CSR);
if (optCtx->ext == NULL) {
(void)AppPrintError("req: Failed to create the ext context.\n");
return HITLS_APP_X509_FAIL;
}
optCtx->conf = BSL_CONF_New(BSL_CONF_DefaultMethod());
if (optCtx->conf == NULL) {
(void)AppPrintError("req: Failed to create profile context.\n");
return HITLS_APP_CONF_FAIL;
}
char extSectionStr[BSL_CONF_SEC_SIZE + 1] = {0};
uint32_t extSectionStrLen = sizeof(extSectionStr);
int32_t ret = BSL_CONF_Load(optCtx->conf, optCtx->certOpt.configFilePath);
if (ret != BSL_SUCCESS) {
(void)AppPrintError("req: Failed to load the config file %s.\n", optCtx->certOpt.configFilePath);
return HITLS_APP_CONF_FAIL;
}
ret = BSL_CONF_GetString(optCtx->conf, HITLS_APP_REQ_SECTION, HITLS_APP_REQ_EXTENSION_SECTION,
extSectionStr, &extSectionStrLen);
if (ret == BSL_CONF_VALUE_NOT_FOUND) {
return HITLS_APP_SUCCESS;
} else if (ret != BSL_SUCCESS) {
(void)AppPrintError("req: Failed to get req_extensions, config file %s.\n", optCtx->certOpt.configFilePath);
return HITLS_APP_CONF_FAIL;
}
ret = HITLS_APP_CONF_ProcExt(optCtx->conf, extSectionStr, ProcSanExt, optCtx->ext);
if (ret == HITLS_APP_NO_EXT) {
return HITLS_APP_SUCCESS;
} else if (ret != BSL_SUCCESS) {
(void)AppPrintError("req: Failed to parse SAN from config file %s.\n", optCtx->certOpt.configFilePath);
return HITLS_APP_CONF_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t ReqGen(ReqOptCtx *optCtx)
{
if (optCtx->certOpt.subj == NULL) {
AppPrintError("req: -subj must be included when -new is used.\n");
return HITLS_APP_INVALID_ARG;
}
if (optCtx->genOpt.inFilePath != NULL) {
AppPrintError("req: ignore -in option when generating csr.\n");
}
int32_t ret = ReqLoadPrvKey(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
optCtx->csr = HITLS_X509_CsrNew();
if (optCtx->csr == NULL) {
(void)AppPrintError("req: Failed to create the csr context.\n");
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_SET_PUBKEY, optCtx->pkey, sizeof(CRYPT_EAL_PkeyCtx *));
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to set public the csr, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
if (ParseConf(optCtx) != HITLS_APP_SUCCESS) {
return HITLS_APP_CONF_FAIL;
}
ret = HITLS_APP_CFG_ProcDnName(optCtx->certOpt.subj, HiTLS_AddSubjDnNameToCsr, optCtx->csr);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to set subject name the csr, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = SetRequestedExt(optCtx);
if (ret != HITLS_PKI_SUCCESS) {
return ret;
}
ret = HITLS_X509_CsrSign(GetSignMdId(optCtx), optCtx->pkey, NULL, optCtx->csr);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to sign the csr, errCode = %x.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CsrGenBuff(optCtx->outPutOpt.outFormat, optCtx->csr, &optCtx->encode);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("req: Failed to generate the csr, errCode = %x.\n", ret);
}
return ret;
}
static int32_t ReqLoad(ReqOptCtx *optCtx)
{
optCtx->csr = HITLS_APP_LoadCsr(optCtx->genOpt.inFilePath, optCtx->genOpt.inFormat);
if (optCtx->csr == NULL) {
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static void ReqVerify(ReqOptCtx *optCtx)
{
int32_t ret = HITLS_X509_CsrVerify(optCtx->csr);
if (ret == HITLS_PKI_SUCCESS) {
(void)AppPrintError("req: verify ok.\n");
} else {
(void)AppPrintError("req: verify failure, errCode = %d.\n", ret);
}
}
static int32_t ReqOutput(ReqOptCtx *optCtx)
{
if (optCtx->outPutOpt.noout && !optCtx->certOpt.text) {
return HITLS_APP_SUCCESS;
}
optCtx->wUio = HITLS_APP_UioOpen(optCtx->outPutOpt.outFilePath, 'w', 0);
if (optCtx->wUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(optCtx->wUio, true);
int32_t ret;
if (optCtx->certOpt.text) {
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_CSR, optCtx->csr, sizeof(HITLS_X509_Csr *), optCtx->wUio);
if (ret != HITLS_PKI_SUCCESS) {
AppPrintError("x509: print csr failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
if (optCtx->outPutOpt.noout) {
return HITLS_APP_SUCCESS;
}
if (optCtx->encode.data == NULL) {
ret = HITLS_X509_CsrGenBuff(optCtx->outPutOpt.outFormat, optCtx->csr, &optCtx->encode);
if (ret != 0) {
AppPrintError("x509: encode csr failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
uint32_t writeLen = 0;
ret = BSL_UIO_Write(optCtx->wUio, optCtx->encode.data, optCtx->encode.dataLen, &writeLen);
if (ret != 0 || writeLen != optCtx->encode.dataLen) {
AppPrintError("req: write csr failed, errCode = %d, writeLen = %u.\n", ret, writeLen);
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static void InitReqOptCtx(ReqOptCtx *optCtx)
{
optCtx->genOpt.inFormat = BSL_FORMAT_PEM;
optCtx->keyAndSignOpt.keyFormat = BSL_FORMAT_UNKNOWN;
optCtx->outPutOpt.outFormat = BSL_FORMAT_PEM;
}
static void UnInitReqOptCtx(ReqOptCtx *optCtx)
{
if (optCtx->passin != NULL) {
BSL_SAL_ClearFree(optCtx->passin, strlen(optCtx->passin));
}
if (optCtx->passout != NULL) {
BSL_SAL_ClearFree(optCtx->passout, strlen(optCtx->passout));
}
HITLS_X509_CsrFree(optCtx->csr);
CRYPT_EAL_PkeyFreeCtx(optCtx->pkey);
BSL_UIO_Free(optCtx->wUio);
BSL_SAL_FREE(optCtx->encode.data);
HITLS_X509_ExtFree(optCtx->ext);
BSL_CONF_Free(optCtx->conf);
}
// req main function
int32_t HITLS_ReqMain(int argc, char *argv[])
{
ReqOptCtx optCtx = {0};
InitReqOptCtx(&optCtx);
int32_t ret = HITLS_APP_SUCCESS;
do {
ret = HITLS_APP_OptBegin(argc, argv, g_reqOpts);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("req: error in opt begin.\n");
break;
}
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR,
"provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) {
AppPrintError("req: failed to init rand.\n");
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = ParseReqOpt(&optCtx);
if (ret != HITLS_APP_SUCCESS) {
break;
}
if (optCtx.certOpt.new) {
ret = ReqGen(&optCtx);
} else {
ret = ReqLoad(&optCtx);
}
if (ret != HITLS_APP_SUCCESS) {
break;
}
if (optCtx.genOpt.verify) {
ReqVerify(&optCtx);
}
ret = ReqOutput(&optCtx);
} while (false);
CRYPT_EAL_RandDeinitEx(NULL);
UnInitReqOptCtx(&optCtx);
HITLS_APP_OptEnd();
return ret;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_req.c | C | unknown | 18,571 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_rsa.h"
#include <stddef.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <linux/limits.h>
#include "securec.h"
#include "bsl_uio.h"
#include "bsl_ui.h"
#include "app_errno.h"
#include "app_function.h"
#include "bsl_sal.h"
#include "app_utils.h"
#include "app_opt.h"
#include "app_utils.h"
#include "app_print.h"
#include "crypt_eal_codecs.h"
#include "crypt_encode_decode_key.h"
#include "crypt_errno.h"
#define RSA_MIN_LEN 256
#define RSA_MAX_LEN 4096
#define DEFAULT_RSA_SIZE 512U
typedef enum OptionChoice {
HITLS_APP_OPT_RSA_ERR = -1,
HITLS_APP_OPT_RSA_ROF = 0,
HITLS_APP_OPT_RSA_HELP = 1, // first opt of each option is help = 1, following opt can be customized.
HITLS_APP_OPT_RSA_IN,
HITLS_APP_OPT_RSA_OUT,
HITLS_APP_OPT_RSA_NOOUT,
HITLS_APP_OPT_RSA_TEXT,
} HITLSOptType;
typedef struct {
int32_t outformat;
bool text;
bool noout;
char *outfile;
} OutputInfo;
HITLS_CmdOption g_rsaOpts[] = {
{"help", HITLS_APP_OPT_RSA_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"in", HITLS_APP_OPT_RSA_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file"},
{"out", HITLS_APP_OPT_RSA_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"noout", HITLS_APP_OPT_RSA_NOOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "No RSA output "},
{"text", HITLS_APP_OPT_RSA_TEXT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print RSA key in text"},
{NULL}};
static int32_t OutPemFormat(BSL_UIO *uio, void *encode)
{
BSL_Buffer *outBuf = encode; // Encode data into the PEM format.
(void)AppPrintError("writing RSA key\n");
int32_t writeRet = HITLS_APP_OptWriteUio(uio, outBuf->data, outBuf->dataLen, HITLS_APP_FORMAT_PEM);
if (writeRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("Failed to export data in PEM format\n");
}
return writeRet;
}
static int32_t BufWriteToUio(void *pkey, OutputInfo outInfo)
{
int32_t writeRet = HITLS_APP_SUCCESS;
BSL_UIO *uio = HITLS_APP_UioOpen(outInfo.outfile, 'w', 0); // Open the file and overwrite the file content.
if (uio == NULL) {
(void)AppPrintError("Failed to open the file <%s> \n", outInfo.outfile);
return HITLS_APP_UIO_FAIL;
}
if (outInfo.text == true) {
writeRet = CRYPT_EAL_PrintPrikey(0, pkey, uio);
if (writeRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("Failed to export data in text format to a file <%s> \n", outInfo.outfile);
goto end;
}
}
if (outInfo.noout != true) {
BSL_Buffer encodeBuffer = {0};
writeRet = CRYPT_EAL_EncodeBuffKey(pkey, NULL, BSL_FORMAT_PEM, CRYPT_PRIKEY_RSA, &encodeBuffer);
if (writeRet != CRYPT_SUCCESS) {
(void)AppPrintError("Failed to encode pem format data\n");
goto end;
}
writeRet = OutPemFormat(uio, &encodeBuffer);
BSL_SAL_FREE(encodeBuffer.data);
if (writeRet != CRYPT_SUCCESS) {
(void)AppPrintError("Failed to export data in pem format to a file <%s> \n", outInfo.outfile);
}
}
end:
BSL_UIO_SetIsUnderlyingClosedByUio(uio, true);
BSL_UIO_Free(uio);
return writeRet;
}
static int32_t GetRsaByStd(uint8_t **readBuf, uint64_t *readBufLen)
{
(void)AppPrintError("Please enter the key content\n");
size_t rsaDataCapacity = DEFAULT_RSA_SIZE;
void *rsaData = BSL_SAL_Calloc(rsaDataCapacity, sizeof(uint8_t));
if (rsaData == NULL) {
return HITLS_APP_MEM_ALLOC_FAIL;
}
size_t rsaDataSize = 0;
bool isMatchRsaData = false;
uint32_t i = 0;
char *header[] = {"-----BEGIN RSA PRIVATE KEY-----\n",
"-----BEGIN PRIVATE KEY-----\n", "-----BEGIN ENCRYPTED PRIVATE KEY-----\n"};
char *tail[] = {"-----END RSA PRIVATE KEY-----\n",
"-----END PRIVATE KEY-----\n", "-----END ENCRYPTED PRIVATE KEY-----\n"};
uint32_t num = (uint32_t)sizeof(header) / sizeof(header[0]);
while (true) {
char *buf = NULL;
size_t bufLen = 0;
ssize_t readLen = getline(&buf, &bufLen, stdin);
if (readLen <= 0) {
free(buf);
(void)AppPrintError("Failed to obtain the standard input.\n");
break;
}
if ((rsaDataSize + readLen) > rsaDataCapacity) {
// If the space is insufficient, expand the capacity by twice.
size_t newRsaDataCapacity = rsaDataCapacity << 1;
/* If the space is insufficient for two times of capacity expansion,
expand the capacity based on the actual length. */
if ((rsaDataSize + readLen) > newRsaDataCapacity) {
newRsaDataCapacity = rsaDataSize + readLen;
}
rsaData = ExpandingMem(rsaData, newRsaDataCapacity, rsaDataCapacity);
rsaDataCapacity = newRsaDataCapacity;
}
if (memcpy_s(rsaData + rsaDataSize, rsaDataCapacity - rsaDataSize, buf, readLen) != 0) {
free(buf);
BSL_SAL_FREE(rsaData);
return HITLS_APP_SECUREC_FAIL;
}
rsaDataSize += readLen;
i *= (uint32_t)isMatchRsaData; // reset 0 if false.
while (!isMatchRsaData && (i < num)) {
if (strcmp(buf, header[i]) == 0) {
isMatchRsaData = true;
break;
}
i++;
}
if (isMatchRsaData && (strcmp(buf, tail[i]) == 0)) {
free(buf);
break;
}
free(buf);
}
*readBuf = rsaData;
*readBufLen = rsaDataSize;
return (rsaDataSize > 0) ? HITLS_APP_SUCCESS : HITLS_APP_STDIN_FAIL;
}
static int32_t UioReadToBuf(uint8_t **readBuf, uint64_t *readBufLen, const char *infile, int32_t flag)
{
int32_t readRet = HITLS_APP_SUCCESS;
if (infile == NULL) {
readRet = GetRsaByStd(readBuf, readBufLen);
} else {
BSL_UIO *uio = HITLS_APP_UioOpen(infile, 'r', flag);
if (uio == NULL) {
AppPrintError("Failed to open the file <%s>, No such file or directory\n", infile);
return HITLS_APP_UIO_FAIL;
}
readRet = HITLS_APP_OptReadUio(uio, readBuf, readBufLen, RSA_MAX_LEN);
BSL_UIO_SetIsUnderlyingClosedByUio(uio, true);
BSL_UIO_Free(uio);
if (readRet != HITLS_APP_SUCCESS) {
AppPrintError("Failed to read the file: <%s>\n", infile);
}
}
return readRet;
}
static int32_t OptParse(char **infile, OutputInfo *outInfo)
{
HITLSOptType optType;
int ret = HITLS_APP_SUCCESS;
outInfo->outformat = HITLS_APP_FORMAT_PEM;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_RSA_ROF) {
switch (optType) {
case HITLS_APP_OPT_RSA_ROF:
case HITLS_APP_OPT_RSA_ERR:
ret = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("rsa: Use -help for summary.\n");
return ret;
case HITLS_APP_OPT_RSA_HELP:
ret = HITLS_APP_HELP;
(void)HITLS_APP_OptHelpPrint(g_rsaOpts);
return ret;
case HITLS_APP_OPT_RSA_IN:
*infile = HITLS_APP_OptGetValueStr();
if (*infile == NULL || strlen(*infile) >= PATH_MAX) {
AppPrintError("The length of infile error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_RSA_OUT:
outInfo->outfile = HITLS_APP_OptGetValueStr();
if (outInfo->outfile == NULL || strlen(outInfo->outfile) >= PATH_MAX) {
AppPrintError("The length of out file error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_RSA_NOOUT:
outInfo->noout = true;
break;
case HITLS_APP_OPT_RSA_TEXT:
outInfo->text = true;
break;
default:
ret = HITLS_APP_OPT_UNKOWN;
return ret;
}
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_RsaMain(int argc, char *argv[])
{
char *infile = NULL;
uint64_t readBufLen = 0;
uint8_t *readBuf = NULL;
int32_t mainRet = HITLS_APP_SUCCESS;
OutputInfo outInfo = {HITLS_APP_FORMAT_PEM, false, false, NULL};
CRYPT_EAL_PkeyCtx *ealPKey = NULL;
mainRet = HITLS_APP_OptBegin(argc, argv, g_rsaOpts);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
mainRet = OptParse(&infile, &outInfo);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
int unParseParamNum = HITLS_APP_GetRestOptNum();
if (unParseParamNum != 0) { // The input parameters are not completely parsed.
(void)AppPrintError("Extra arguments given.\n");
(void)AppPrintError("rsa: Use -help for summary.\n");
mainRet = HITLS_APP_OPT_UNKOWN;
goto end;
}
mainRet = UioReadToBuf(
&readBuf, &readBufLen, infile, 0); // Read the content of the input file from the file to the buffer.
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
BSL_Buffer read = {readBuf, readBufLen};
mainRet = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, CRYPT_PRIKEY_RSA, &read, NULL, 0, &ealPKey);
if (mainRet == BSL_PEM_SYMBOL_NOT_FOUND) {
mainRet = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, CRYPT_PRIKEY_PKCS8_UNENCRYPT, &read, NULL, 0, &ealPKey);
}
if (mainRet == BSL_PEM_SYMBOL_NOT_FOUND || mainRet == BSL_PEM_NO_PWD) {
char pwd[APP_MAX_PASS_LENGTH + 1] = {0};
int32_t pwdLen = HITLS_APP_Passwd(pwd, APP_MAX_PASS_LENGTH + 1, 0, NULL);
if (pwdLen == -1) {
mainRet = HITLS_APP_PASSWD_FAIL;
goto end;
}
if (mainRet == BSL_PEM_SYMBOL_NOT_FOUND) {
mainRet = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, CRYPT_PRIKEY_PKCS8_ENCRYPT,
&read, (uint8_t *)pwd, pwdLen, &ealPKey);
} else {
mainRet = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, CRYPT_PRIKEY_RSA,
&read, (uint8_t *)pwd, pwdLen, &ealPKey);
}
(void)memset_s(pwd, APP_MAX_PASS_LENGTH, 0, APP_MAX_PASS_LENGTH);
}
if (mainRet != CRYPT_SUCCESS) {
(void)AppPrintError("Decode failed.\n");
mainRet = HITLS_APP_DECODE_FAIL;
goto end;
}
mainRet = BufWriteToUio(ealPKey, outInfo); // Selective output based on command line parameters.
end:
CRYPT_EAL_PkeyFreeCtx(ealPKey);
BSL_SAL_FREE(readBuf);
HITLS_APP_OptEnd();
return mainRet;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_rsa.c | C | unknown | 11,175 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_utils.h"
#include <stdio.h>
#include <securec.h>
#include <string.h>
#include <linux/limits.h>
#include "bsl_sal.h"
#include "bsl_buffer.h"
#include "bsl_ui.h"
#include "bsl_errno.h"
#include "bsl_buffer.h"
#include "bsl_pem_internal.h"
#include "sal_file.h"
#include "crypt_errno.h"
#include "crypt_eal_codecs.h"
#include "crypt_eal_pkey.h"
#include "crypt_eal_cipher.h"
#include "crypt_eal_md.h"
#include "crypt_encode_decode_key.h"
#include "app_print.h"
#include "app_errno.h"
#include "app_opt.h"
#include "app_list.h"
#include "hitls_pki_errno.h"
#define DEFAULT_PEM_FILE_SIZE 1024U
#define RSA_PRV_CTX_LEN 8
#define HEX_TO_BYTE 2
#define APP_HEX_HEAD "0x"
#define APP_LINESIZE 255
#define PEM_BEGIN_STR "-----BEGIN "
#define PEM_END_STR "-----END "
#define PEM_TAIL_STR "-----\n"
#define PEM_TAIL_KEY_STR "KEY-----\n"
#define PEM_BEGIN_STR_LEN ((int)(sizeof(PEM_BEGIN_STR) - 1))
#define PEM_END_STR_LEN ((int)(sizeof(PEM_END_STR) - 1))
#define PEM_TAIL_STR_LEN ((int)(sizeof(PEM_TAIL_STR) - 1))
#define PEM_TAIL_KEY_STR_LEN ((int)(sizeof(PEM_TAIL_KEY_STR) - 1))
#define PEM_RSA_PRIVATEKEY_STR "RSA PRIVATE KEY"
#define PEM_RSA_PUBLIC_STR "RSA PUBLIC KEY"
#define PEM_EC_PRIVATEKEY_STR "EC PRIVATE KEY"
#define PEM_PKCS8_PRIVATEKEY_STR "PRIVATE KEY"
#define PEM_PKCS8_PUBLIC_STR "PUBLIC KEY"
#define PEM_ENCRYPTED_PKCS8_PRIVATEKEY_STR "ENCRYPTED PRIVATE KEY"
#define PEM_PROC_TYPE_STR "Proc-Type:"
#define PEM_PROC_TYPE_NUM_STR "4,"
#define PEM_ENCRYPTED_STR "ENCRYPTED"
#define APP_PASS_ARG_STR "pass:"
#define APP_PASS_ARG_STR_LEN ((int)(sizeof(APP_PASS_ARG_STR) - 1))
#define APP_PASS_STDIN_STR "stdin"
#define APP_PASS_STDIN_STR_LEN ((int)(sizeof(APP_PASS_STDIN_STR) - 1))
#define APP_PASS_FILE_STR "file:"
#define APP_PASS_FILE_STR_LEN ((int)(sizeof(APP_PASS_FILE_STR) - 1))
typedef struct defaultPassCBData {
uint32_t maxLen;
uint32_t minLen;
} APP_DefaultPassCBData;
void *ExpandingMem(void *oldPtr, size_t newSize, size_t oldSize)
{
if (newSize <= 0) {
return oldPtr;
}
void *newPtr = BSL_SAL_Calloc(newSize, sizeof(uint8_t));
if (newPtr == NULL) {
return oldPtr;
}
if (oldPtr != NULL) {
if (memcpy_s(newPtr, newSize, oldPtr, oldSize) != 0) {
BSL_SAL_FREE(newPtr);
return oldPtr;
}
BSL_SAL_FREE(oldPtr);
}
return newPtr;
}
int32_t HITLS_APP_CheckPasswd(const uint8_t *password, const uint32_t passwordLen)
{
for (uint32_t i = 0; i < passwordLen; ++i) {
if (password[i] < '!' || password[i] > '~') {
AppPrintError("The password can contain only the following characters:\n");
AppPrintError("a~z A~Z 0~9 ! \" # $ %% & ' ( ) * + , - . / : ; < = > ? @ [ \\ ] ^ _ ` { | } ~\n");
return HITLS_APP_PASSWD_FAIL;
}
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_DefaultPassCB(BSL_UI *ui, char *buff, uint32_t buffLen, void *callBackData)
{
if (ui == NULL || buff == NULL || buffLen == 1) {
(void)AppPrintError("You have not entered a password.\n");
return BSL_UI_INVALID_DATA_ARG;
}
uint32_t passLen = buffLen - 1;
uint32_t maxLength = 0;
if (callBackData == NULL) {
maxLength = APP_MAX_PASS_LENGTH;
} else {
APP_DefaultPassCBData *data = callBackData;
maxLength = data->maxLen;
}
if (passLen > maxLength) {
HITLS_APP_PrintPassErrlog();
return BSL_UI_INVALID_DATA_RESULT;
}
return BSL_SUCCESS;
}
static int32_t CheckFileSizeByUio(BSL_UIO *uio, uint32_t *fileSize)
{
uint64_t getFileSize = 0;
int32_t ret = BSL_UIO_Ctrl(uio, BSL_UIO_PENDING, sizeof(getFileSize), &getFileSize);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to get the file size: %d.\n", ret);
return HITLS_APP_UIO_FAIL;
}
if (getFileSize > APP_FILE_MAX_SIZE) {
AppPrintError("File size exceed limit %zukb.\n", APP_FILE_MAX_SIZE_KB);
return HITLS_APP_UIO_FAIL;
}
if (fileSize != NULL) {
*fileSize = (uint32_t)getFileSize;
}
return ret;
}
static int32_t CheckFileSizeByPath(const char *inFilePath, uint32_t *fileSize)
{
size_t getFileSize = 0;
int32_t ret = BSL_SAL_FileLength(inFilePath, &getFileSize);
if (ret != BSL_SUCCESS) {
AppPrintError("Failed to get the file size: %d.\n", ret);
return HITLS_APP_UIO_FAIL;
}
if (getFileSize > APP_FILE_MAX_SIZE) {
AppPrintError("File size exceed limit %zukb.\n", APP_FILE_MAX_SIZE_KB);
return HITLS_APP_UIO_FAIL;
}
if (fileSize != NULL) {
*fileSize = (uint32_t)getFileSize;
}
return ret;
}
static char *GetPemKeyFileName(const char *buf, size_t readLen)
{
// -----BEGIN *** KEY-----
if ((strncmp(buf, PEM_BEGIN_STR, PEM_BEGIN_STR_LEN) != 0) || (readLen < PEM_TAIL_KEY_STR_LEN) ||
(strncmp(buf + readLen - PEM_TAIL_KEY_STR_LEN, PEM_TAIL_KEY_STR, PEM_TAIL_KEY_STR_LEN) != 0)) {
return NULL;
}
int32_t len = readLen - PEM_BEGIN_STR_LEN - PEM_TAIL_STR_LEN;
char *name = BSL_SAL_Calloc(len + 1, sizeof(char));
if (name == NULL) {
return name;
}
memcpy_s(name, len, buf + PEM_BEGIN_STR_LEN, len);
name[len] = '\0';
return name;
}
static bool IsNeedEncryped(const char *name, const char *header, uint32_t headerLen)
{
// PKCS8
if (strcmp(name, PEM_ENCRYPTED_PKCS8_PRIVATEKEY_STR) == 0) {
return true;
}
// PKCS1
// Proc-Type: 4, ENCRYPTED
uint32_t offset = 0;
uint32_t len = strlen(PEM_PROC_TYPE_STR);
if (strncmp(header + offset, PEM_PROC_TYPE_STR, len) != 0) {
return false;
}
offset += len + strspn(header + offset + len, " \t");
len = strlen(PEM_PROC_TYPE_NUM_STR);
if ((offset >= headerLen) || (strncmp(header + offset, PEM_PROC_TYPE_NUM_STR, len) != 0)) {
return false;
}
offset += len + strspn(header + offset + len, " \t");
len = strlen(PEM_ENCRYPTED_STR);
if ((offset >= headerLen) || (strncmp(header + offset, PEM_ENCRYPTED_STR, len) != 0)) {
return false;
}
offset += len + strspn(header + offset + len, " \t");
if ((offset >= headerLen) || header[offset] != '\n') {
return false;
}
return true;
}
static void PrintFileOrStdinError(const char *filePath, const char *errStr)
{
if (filePath == NULL) {
AppPrintError("%s.\n", errStr);
} else {
AppPrintError("%s from \"%s\".\n", errStr, filePath);
}
}
static int32_t ReadPemKeyFile(const char *inFilePath, uint8_t **inData, uint32_t *inDataSize, char **name,
bool *isEncrypted)
{
if ((inData == NULL) || (inDataSize == NULL) || (name == NULL)) {
return HITLS_APP_INVALID_ARG;
}
BSL_UIO *rUio = HITLS_APP_UioOpen(inFilePath, 'r', 1);
if (rUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(rUio, true);
uint32_t fileSize = 0;
if (CheckFileSizeByUio(rUio, &fileSize) != HITLS_APP_SUCCESS) {
BSL_UIO_Free(rUio);
return HITLS_APP_UIO_FAIL;
}
// End after reading the following two strings in sequence:
// -----BEGIN XXX-----
// -----END XXX-----
bool isParseHeader = false;
uint8_t *data = (uint8_t *)BSL_SAL_Calloc(fileSize + 1, sizeof(uint8_t)); // +1 for the null terminator
if (data == NULL) {
BSL_UIO_Free(rUio);
return HITLS_APP_MEM_ALLOC_FAIL;
}
char *tmp = (char *)data;
uint32_t readLen = 0;
while (readLen < fileSize) {
uint32_t getsLen = APP_LINESIZE;
if ((BSL_UIO_Gets(rUio, tmp, &getsLen) != BSL_SUCCESS) || (getsLen == 0)) {
break;
}
if (*name == NULL) {
*name = GetPemKeyFileName(tmp, getsLen);
} else if (getsLen < PEM_END_STR_LEN && strncmp(tmp, PEM_END_STR, PEM_END_STR_LEN) == 0) {
break; // Read the end of the pem.
} else if (!isParseHeader) {
*isEncrypted = IsNeedEncryped(*name, tmp, getsLen);
isParseHeader = true;
}
tmp += getsLen;
readLen += getsLen;
}
BSL_UIO_Free(rUio);
if (readLen == 0 || *name == NULL) {
AppPrintError("Failed to read the pem file.\n");
BSL_SAL_FREE(data);
BSL_SAL_FREE(*name);
return HITLS_APP_STDIN_FAIL;
}
*inData = data;
*inDataSize = readLen;
return HITLS_APP_SUCCESS;
}
static int32_t GetPasswdByFile(const char *passwdArg, size_t passwdArgLen, char **pass)
{
if (passwdArgLen <= APP_PASS_FILE_STR_LEN) {
AppPrintError("Failed to read passwd from file.\n");
return HITLS_APP_INVALID_ARG;
}
// Apply for a new memory and copy the unprocessed character string.
char filePath[PATH_MAX] = {0};
if (strcpy_s(filePath, PATH_MAX - 1, passwdArg + APP_PASS_FILE_STR_LEN) != EOK) {
AppPrintError("Failed to read passwd from file.\n");
return HITLS_APP_SECUREC_FAIL;
}
// Binding the password file UIO.
BSL_UIO *passUio = BSL_UIO_New(BSL_UIO_FileMethod());
if (passUio == NULL) {
AppPrintError("Failed to read passwd from file.\n");
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(passUio, true);
if (BSL_UIO_Ctrl(passUio, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_READ, filePath) != BSL_SUCCESS) {
AppPrintError("Failed to set infile mode for passwd.\n");
BSL_UIO_Free(passUio);
return HITLS_APP_UIO_FAIL;
}
char *passBuf = (char *)BSL_SAL_Calloc(APP_MAX_PASS_LENGTH + 1 + 1, sizeof(char));
if (passBuf == NULL) {
BSL_UIO_Free(passUio);
AppPrintError("Failed to read passwd from file.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
// When the number of bytes exceeds 1024 bytes, only one more bit is read.
uint32_t passLen = APP_MAX_PASS_LENGTH + 1 + 1;
if (BSL_UIO_Gets(passUio, passBuf, &passLen) != BSL_SUCCESS) {
AppPrintError("Failed to read passwd from file.\n");
BSL_UIO_Free(passUio);
BSL_SAL_FREE(passBuf);
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_Free(passUio);
if (passLen <= 0) {
passBuf[0] = '\0';
} else if (passBuf[passLen - 1] == '\n') {
passBuf[passLen - 1] = '\0';
}
*pass = passBuf;
return HITLS_APP_SUCCESS;
}
static char *GetPasswdByStdin(BSL_UI_ReadPwdParam *param)
{
char *pass = (char *)BSL_SAL_Calloc(APP_MAX_PASS_LENGTH + 1, sizeof(char));
if (pass == NULL) {
return NULL;
}
uint32_t passLen = APP_MAX_PASS_LENGTH + 1;
int32_t ret = BSL_UI_ReadPwdUtil(param, pass, &passLen, NULL, NULL);
if (ret != BSL_SUCCESS) {
pass[0] = '\0';
return pass;
}
pass[passLen - 1] = '\0';
return pass;
}
static char *GetStrAfterPreFix(const char *inputArg, uint32_t inputArgLen, uint32_t prefixLen)
{
if (prefixLen > inputArgLen) {
return NULL;
}
uint32_t len = inputArgLen - prefixLen;
char *str = (char *)BSL_SAL_Calloc(len + 1, sizeof(char));
if (str == NULL) {
return NULL;
}
memcpy_s(str, len, inputArg + prefixLen, len);
str[len] = '\0';
return str;
}
int32_t HITLS_APP_ParsePasswd(const char *passArg, char **pass)
{
if (passArg == NULL) {
return HITLS_APP_SUCCESS;
}
if (strncmp(passArg, APP_PASS_ARG_STR, APP_PASS_ARG_STR_LEN) == 0) {
*pass = GetStrAfterPreFix(passArg, strlen(passArg), APP_PASS_ARG_STR_LEN);
} else if (strncmp(passArg, APP_PASS_STDIN_STR, APP_PASS_STDIN_STR_LEN) == 0) {
BSL_UI_ReadPwdParam passParam = { "passwd", NULL, false };
*pass = GetPasswdByStdin(&passParam);
} else if (strncmp(passArg, APP_PASS_FILE_STR, APP_PASS_FILE_STR_LEN) == 0) {
return GetPasswdByFile(passArg, strlen(passArg), pass);
} else {
AppPrintError("The %s password parameter is not supported.\n", passArg);
return HITLS_APP_PASSWD_FAIL;
}
return HITLS_APP_SUCCESS;
}
static CRYPT_EAL_PkeyCtx *ReadPemPrvKey(BSL_Buffer *encode, const char *name, uint8_t *pass, uint32_t passLen)
{
int32_t type = CRYPT_ENCDEC_UNKNOW;
if (strcmp(name, PEM_RSA_PRIVATEKEY_STR) == 0) {
type = CRYPT_PRIKEY_RSA;
} else if (strcmp(name, PEM_EC_PRIVATEKEY_STR) == 0) {
type = CRYPT_PRIKEY_ECC;
} else if (strcmp(name, PEM_PKCS8_PRIVATEKEY_STR) == 0) {
type = CRYPT_PRIKEY_PKCS8_UNENCRYPT;
} else if (strcmp(name, PEM_ENCRYPTED_PKCS8_PRIVATEKEY_STR) == 0) {
type = CRYPT_PRIKEY_PKCS8_ENCRYPT;
}
CRYPT_EAL_PkeyCtx *pkey = NULL;
if (CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, type, encode, pass, passLen, &pkey) != CRYPT_SUCCESS) {
return NULL;
}
return pkey;
}
static CRYPT_EAL_PkeyCtx *ReadPemPubKey(BSL_Buffer *encode, const char *name)
{
int32_t type = CRYPT_ENCDEC_UNKNOW;
if (strcmp(name, PEM_RSA_PUBLIC_STR) == 0) {
type = CRYPT_PUBKEY_RSA;
} else if (strcmp(name, PEM_PKCS8_PUBLIC_STR) == 0) {
type = CRYPT_PUBKEY_SUBKEY;
}
CRYPT_EAL_PkeyCtx *pkey = NULL;
if (CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, type, encode, NULL, 0, &pkey) != CRYPT_SUCCESS) {
return NULL;
}
return pkey;
}
int32_t HITLS_APP_GetPasswd(BSL_UI_ReadPwdParam *param, char **passin, uint8_t **pass, uint32_t *passLen)
{
if (*passin == NULL) {
*passin = GetPasswdByStdin(param);
}
if ((*passin == NULL) || (strlen(*passin) > APP_MAX_PASS_LENGTH) || (strlen(*passin) < APP_MIN_PASS_LENGTH)) {
HITLS_APP_PrintPassErrlog();
return HITLS_APP_PASSWD_FAIL;
}
*pass = (uint8_t *)*passin;
*passLen = strlen(*passin);
return HITLS_APP_SUCCESS;
}
static bool CheckFilePath(const char *filePath)
{
if (filePath == NULL) {
return true;
}
if (strlen(filePath) > PATH_MAX) {
AppPrintError("The maximum length of the file path is %d.\n", PATH_MAX);
return false;
}
return true;
}
static CRYPT_EAL_PkeyCtx *LoadPrvDerKey(const char *inFilePath)
{
static CRYPT_ENCDEC_TYPE encodeType[] = {CRYPT_PRIKEY_ECC, CRYPT_PRIKEY_RSA, CRYPT_PRIKEY_PKCS8_UNENCRYPT};
CRYPT_EAL_PkeyCtx *pkey = NULL;
for (uint32_t i = 0; i < sizeof(encodeType) / sizeof(CRYPT_ENCDEC_TYPE); ++i) {
if (CRYPT_EAL_DecodeFileKey(BSL_FORMAT_ASN1, encodeType[i], inFilePath, NULL, 0, &pkey) == CRYPT_SUCCESS) {
break;
}
}
if (pkey == NULL) {
AppPrintError("Failed to read the private key from \"%s\".\n", inFilePath);
return NULL;
}
return pkey;
}
CRYPT_EAL_PkeyCtx *HITLS_APP_LoadPrvKey(const char *inFilePath, BSL_ParseFormat informat, char **passin)
{
if (inFilePath == NULL && informat == BSL_FORMAT_ASN1) {
AppPrintError("The \"-inform DER or -keyform DER\" requires using the \"-in\" option.\n");
return NULL;
}
if (!CheckFilePath(inFilePath)) {
return NULL;
}
if (informat == BSL_FORMAT_ASN1) {
return LoadPrvDerKey(inFilePath);
}
char *prvkeyName = NULL;
bool isEncrypted = false;
uint8_t *data = NULL;
uint32_t dataLen = 0;
if (ReadPemKeyFile(inFilePath, &data, &dataLen, &prvkeyName, &isEncrypted) != HITLS_APP_SUCCESS) {
PrintFileOrStdinError(inFilePath, "Failed to read the private key");
return NULL;
}
uint8_t *pass = NULL;
uint32_t passLen = 0;
BSL_UI_ReadPwdParam passParam = { "passwd", inFilePath, false };
if (isEncrypted && (HITLS_APP_GetPasswd(&passParam, passin, &pass, &passLen) != HITLS_APP_SUCCESS)) {
BSL_SAL_FREE(data);
BSL_SAL_FREE(prvkeyName);
return NULL;
}
BSL_Buffer encode = { data, dataLen };
CRYPT_EAL_PkeyCtx *pkey = ReadPemPrvKey(&encode, prvkeyName, pass, passLen);
if (pkey == NULL) {
PrintFileOrStdinError(inFilePath, "Failed to read the private key");
}
BSL_SAL_FREE(data);
BSL_SAL_FREE(prvkeyName);
return pkey;
}
CRYPT_EAL_PkeyCtx *HITLS_APP_LoadPubKey(const char *inFilePath, BSL_ParseFormat informat)
{
if (informat != BSL_FORMAT_PEM) {
AppPrintError("Reading public key from non-PEM files is not supported.\n");
return NULL;
}
char *pubKeyName = NULL;
uint8_t *data = NULL;
uint32_t dataLen = 0;
bool isEncrypted = false;
if (!CheckFilePath(inFilePath) ||
(ReadPemKeyFile(inFilePath, &data, &dataLen, &pubKeyName, &isEncrypted) != HITLS_APP_SUCCESS)) {
PrintFileOrStdinError(inFilePath, "Failed to read the public key");
return NULL;
}
BSL_Buffer encode = { data, dataLen };
CRYPT_EAL_PkeyCtx *pkey = ReadPemPubKey(&encode, pubKeyName);
if (pkey == NULL) {
PrintFileOrStdinError(inFilePath, "Failed to read the public key");
}
BSL_SAL_FREE(data);
BSL_SAL_FREE(pubKeyName);
return pkey;
}
int32_t HITLS_APP_PrintPubKey(CRYPT_EAL_PkeyCtx *pkey, const char *outFilePath, BSL_ParseFormat outformat)
{
if (!CheckFilePath(outFilePath)) {
return HITLS_APP_INVALID_ARG;
}
BSL_Buffer pubKeyBuf = { 0 };
if (CRYPT_EAL_EncodeBuffKey(pkey, NULL, outformat, CRYPT_PUBKEY_SUBKEY, &pubKeyBuf) != CRYPT_SUCCESS) {
AppPrintError("Failed to export the public key.\n");
return HITLS_APP_ENCODE_KEY_FAIL;
}
BSL_UIO *wPubKeyUio = HITLS_APP_UioOpen(outFilePath, 'w', 0);
if (wPubKeyUio == NULL) {
BSL_SAL_FREE(pubKeyBuf.data);
return HITLS_APP_UIO_FAIL;
}
int32_t ret = HITLS_APP_OptWriteUio(wPubKeyUio, pubKeyBuf.data, pubKeyBuf.dataLen, HITLS_APP_FORMAT_PEM);
BSL_SAL_FREE(pubKeyBuf.data);
BSL_UIO_SetIsUnderlyingClosedByUio(wPubKeyUio, true);
BSL_UIO_Free(wPubKeyUio);
return ret;
}
int32_t HITLS_APP_PrintPrvKey(CRYPT_EAL_PkeyCtx *pkey, const char *outFilePath, BSL_ParseFormat outformat,
int32_t cipherAlgCid, char **passout)
{
if (!CheckFilePath(outFilePath)) {
return HITLS_APP_INVALID_ARG;
}
BSL_UIO *wPrvUio = HITLS_APP_UioOpen(outFilePath, 'w', 0);
if (wPrvUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
AppKeyPrintParam param = { outFilePath, outformat, cipherAlgCid, false, false};
int32_t ret = HITLS_APP_PrintPrvKeyByUio(wPrvUio, pkey, ¶m, passout);
BSL_UIO_SetIsUnderlyingClosedByUio(wPrvUio, true);
BSL_UIO_Free(wPrvUio);
return ret;
}
int32_t HITLS_APP_PrintPrvKeyByUio(BSL_UIO *uio, CRYPT_EAL_PkeyCtx *pkey, AppKeyPrintParam *printKeyParam,
char **passout)
{
int32_t ret = printKeyParam->text ? CRYPT_EAL_PrintPrikey(0, pkey, uio) : HITLS_APP_SUCCESS;
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to print the private key text, errCode = 0x%x.\n", ret);
return HITLS_APP_CRYPTO_FAIL;
}
if (printKeyParam->noout) {
return HITLS_APP_SUCCESS;
}
int32_t type =
printKeyParam->cipherAlgCid != CRYPT_CIPHER_MAX ? CRYPT_PRIKEY_PKCS8_ENCRYPT : CRYPT_PRIKEY_PKCS8_UNENCRYPT;
uint8_t *pass = NULL;
uint32_t passLen = 0;
BSL_UI_ReadPwdParam passParam = { "passwd", printKeyParam->name, true };
if ((type == CRYPT_PRIKEY_PKCS8_ENCRYPT) &&
(HITLS_APP_GetPasswd(&passParam, passout, &pass, &passLen) != HITLS_APP_SUCCESS)) {
return HITLS_APP_PASSWD_FAIL;
}
CRYPT_Pbkdf2Param param = { 0 };
param.pbesId = BSL_CID_PBES2;
param.pbkdfId = BSL_CID_PBKDF2;
param.hmacId = CRYPT_MAC_HMAC_SHA256;
param.symId = printKeyParam->cipherAlgCid;
param.pwd = pass;
param.saltLen = DEFAULT_SALTLEN;
param.pwdLen = passLen;
param.itCnt = DEFAULT_ITCNT;
CRYPT_EncodeParam paramEx = { CRYPT_DERIVE_PBKDF2, ¶m };
BSL_Buffer prvKeyBuf = { 0 };
if (CRYPT_EAL_EncodeBuffKey(pkey, ¶mEx, printKeyParam->outformat, type, &prvKeyBuf) != CRYPT_SUCCESS) {
AppPrintError("Failed to export the private key.\n");
return HITLS_APP_ENCODE_KEY_FAIL;
}
ret = HITLS_APP_OptWriteUio(uio, prvKeyBuf.data, prvKeyBuf.dataLen, HITLS_APP_FORMAT_PEM);
BSL_SAL_FREE(prvKeyBuf.data);
return ret;
}
int32_t HITLS_APP_GetAndCheckCipherOpt(const char *name, int32_t *symId)
{
if (symId == NULL) {
return HITLS_APP_INVALID_ARG;
}
uint32_t cid = (uint32_t)HITLS_APP_GetCidByName(name, HITLS_APP_LIST_OPT_CIPHER_ALG);
if (cid == CRYPT_CIPHER_MAX) {
(void)AppPrintError("%s: Use the [list -cipher-algorithms] command to view supported encryption algorithms.\n",
HITLS_APP_GetProgName());
return HITLS_APP_OPT_UNKOWN;
}
if (!CRYPT_EAL_CipherIsValidAlgId(cid)) {
AppPrintError("%s: %s ciphers not supported.\n", HITLS_APP_GetProgName(), name);
return HITLS_APP_OPT_UNKOWN;
}
uint32_t isAeadId = 1;
if (CRYPT_EAL_CipherGetInfo((CRYPT_CIPHER_AlgId)cid, CRYPT_INFO_IS_AEAD, &isAeadId) != CRYPT_SUCCESS) {
AppPrintError("%s: The encryption algorithm is not supported\n", HITLS_APP_GetProgName());
return HITLS_APP_INVALID_ARG;
}
if (isAeadId == 1) {
AppPrintError("%s: The AEAD encryption algorithm is not supported\n", HITLS_APP_GetProgName());
return HITLS_APP_INVALID_ARG;
}
*symId = cid;
return HITLS_APP_SUCCESS;
}
static int32_t ReadPemByUioSymbol(BSL_UIO *memUio, BSL_UIO *rUio, BSL_PEM_Symbol *symbol)
{
int32_t ret = HITLS_APP_UIO_FAIL;
char buf[APP_LINESIZE + 1];
uint32_t lineLen;
bool hasHead = false;
uint32_t writeMemLen;
int64_t dataLen = 0;
while (true) {
lineLen = APP_LINESIZE + 1;
(void)memset_s(buf, lineLen, 0, lineLen);
// Reads a row of data.
if ((BSL_UIO_Gets(rUio, buf, &lineLen) != BSL_SUCCESS) || (lineLen == 0)) {
break;
}
ret = BSL_UIO_Ctrl(rUio, BSL_UIO_GET_READ_NUM, sizeof(int64_t), &dataLen);
if (ret != BSL_SUCCESS || dataLen > APP_FILE_MAX_SIZE) {
AppPrintError("The maximum file size is %zukb.\n", APP_FILE_MAX_SIZE_KB);
ret = HITLS_APP_UIO_FAIL;
break;
}
if (!hasHead) {
// Check whether it is the head.
if (strncmp(buf, symbol->head, strlen(symbol->head)) != 0) {
continue;
}
if (BSL_UIO_Puts(memUio, (const char *)buf, &writeMemLen) != BSL_SUCCESS || writeMemLen != lineLen) {
break;
}
hasHead = true;
continue;
}
// Copy the intermediate content.
if (BSL_UIO_Puts(memUio, (const char *)buf, &writeMemLen) != BSL_SUCCESS || writeMemLen != lineLen) {
break;
}
// Check whether it is the tail.
if (strncmp(buf, symbol->tail, strlen(symbol->tail)) == 0) {
ret = HITLS_APP_SUCCESS;
break;
}
}
return ret;
}
static int32_t ReadPemFromStdin(BSL_BufMem **data, BSL_PEM_Symbol *symbol)
{
int32_t ret = HITLS_APP_UIO_FAIL;
BSL_UIO *memUio = BSL_UIO_New(BSL_UIO_MemMethod());
if (memUio == NULL) {
return ret;
}
// Read from stdin or file.
BSL_UIO *rUio = HITLS_APP_UioOpen(NULL, 'r', 1);
if (rUio == NULL) {
BSL_UIO_Free(memUio);
return ret;
}
BSL_UIO_SetIsUnderlyingClosedByUio(rUio, true);
ret = ReadPemByUioSymbol(memUio, rUio, symbol);
BSL_UIO_Free(rUio);
if (ret == HITLS_APP_SUCCESS) {
if (BSL_UIO_Ctrl(memUio, BSL_UIO_MEM_GET_PTR, sizeof(BSL_BufMem *), data) == BSL_SUCCESS) {
BSL_UIO_SetIsUnderlyingClosedByUio(memUio, false);
BSL_SAL_Free(BSL_UIO_GetCtx(memUio));
BSL_UIO_SetCtx(memUio, NULL);
} else {
ret = HITLS_APP_UIO_FAIL;
}
}
BSL_UIO_Free(memUio);
return ret;
}
static int32_t ReadFileData(const char *path, BSL_Buffer *data)
{
int32_t ret = CheckFileSizeByPath(path, NULL);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = BSL_SAL_ReadFile(path, &data->data, &data->dataLen);
if (ret != BSL_SUCCESS) {
AppPrintError("Read file failed: %s.\n", path);
}
return ret;
}
static int32_t ReadData(const char *path, BSL_PEM_Symbol *symbol, char *fileName, BSL_Buffer *data)
{
if (path == NULL) {
BSL_BufMem *buf = NULL;
if (ReadPemFromStdin(&buf, symbol) != HITLS_APP_SUCCESS) {
AppPrintError("Failed to read %s from stdin.\n", fileName);
return HITLS_APP_UIO_FAIL;
}
data->data = (uint8_t *)buf->data;
data->dataLen = buf->length;
BSL_SAL_Free(buf);
return HITLS_APP_SUCCESS;
} else {
return ReadFileData(path, data);
}
}
HITLS_X509_Cert *HITLS_APP_LoadCert(const char *inPath, BSL_ParseFormat inform)
{
if (inPath == NULL && inform == BSL_FORMAT_ASN1) {
AppPrintError("Reading DER files from stdin is not supported.\n");
return NULL;
}
if (!CheckFilePath(inPath)) {
AppPrintError("Invalid cert path: \"%s\".", inPath == NULL ? "" : inPath);
return NULL;
}
BSL_Buffer data = { 0 };
BSL_PEM_Symbol symbol = { BSL_PEM_CERT_BEGIN_STR, BSL_PEM_CERT_END_STR };
int32_t ret = ReadData(inPath, &symbol, "cert", &data);
if (ret != HITLS_APP_SUCCESS) {
return NULL;
}
HITLS_X509_Cert *cert = NULL;
if (HITLS_X509_CertParseBuff(inform, &data, &cert) != 0) {
AppPrintError("Failed to parse cert: \"%s\".\n", inPath == NULL ? "stdin" : inPath);
BSL_SAL_Free(data.data);
return NULL;
}
BSL_SAL_Free(data.data);
return cert;
}
HITLS_X509_Csr *HITLS_APP_LoadCsr(const char *inPath, BSL_ParseFormat inform)
{
if (inPath == NULL && inform == BSL_FORMAT_ASN1) {
AppPrintError("Reading DER files from stdin is not supported.\n");
return NULL;
}
if (!CheckFilePath(inPath)) {
AppPrintError("Invalid csr path: \"%s\".", inPath == NULL ? "" : inPath);
return NULL;
}
BSL_Buffer data = { 0 };
BSL_PEM_Symbol symbol = { BSL_PEM_CERT_REQ_BEGIN_STR, BSL_PEM_CERT_REQ_END_STR };
int32_t ret = ReadData(inPath, &symbol, "csr", &data);
if (ret != HITLS_APP_SUCCESS) {
return NULL;
}
HITLS_X509_Csr *csr = NULL;
if (HITLS_X509_CsrParseBuff(inform, &data, &csr) != 0) {
AppPrintError("Failed to parse csr: \"%s\".\n", inPath == NULL ? "stdin" : inPath);
BSL_SAL_Free(data.data);
return NULL;
}
BSL_SAL_Free(data.data);
return csr;
}
int32_t HITLS_APP_GetAndCheckHashOpt(const char *name, int32_t *hashId)
{
if (hashId == NULL) {
return HITLS_APP_INVALID_ARG;
}
uint32_t cid = (uint32_t)HITLS_APP_GetCidByName(name, HITLS_APP_LIST_OPT_DGST_ALG);
if (cid == BSL_CID_UNKNOWN) {
(void)AppPrintError("%s: Use the [list -digest-algorithms] command to view supported digest algorithms.\n",
HITLS_APP_GetProgName());
return HITLS_APP_OPT_UNKOWN;
}
if (!CRYPT_EAL_MdIsValidAlgId(cid)) {
AppPrintError("%s: %s digest not supported.\n", HITLS_APP_GetProgName(), name);
return HITLS_APP_OPT_UNKOWN;
}
*hashId = cid;
return HITLS_APP_SUCCESS;
}
int32_t HITLS_APP_PrintText(const BSL_Buffer *csrBuf, const char *outFileName)
{
BSL_UIO *wCsrUio = HITLS_APP_UioOpen(outFileName, 'w', 0);
if (wCsrUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
int32_t ret = HITLS_APP_OptWriteUio(wCsrUio, csrBuf->data, csrBuf->dataLen, HITLS_APP_FORMAT_TEXT);
BSL_UIO_SetIsUnderlyingClosedByUio(wCsrUio, true);
BSL_UIO_Free(wCsrUio);
return ret;
}
CRYPT_EAL_PkeyCtx *HITLS_APP_GenRsaPkeyCtx(uint32_t bits)
{
CRYPT_EAL_PkeyCtx *pkey = CRYPT_EAL_ProviderPkeyNewCtx(NULL, CRYPT_PKEY_RSA,
CRYPT_EAL_PKEY_UNKNOWN_OPERATE, "provider=default");
if (pkey == NULL) {
AppPrintError("%s: Failed to initialize the RSA private key.\n", HITLS_APP_GetProgName());
return NULL;
}
CRYPT_EAL_PkeyPara *para = BSL_SAL_Calloc(sizeof(CRYPT_EAL_PkeyPara), 1);
if (para == NULL) {
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
static uint8_t e[] = {0x01, 0x00, 0x01}; // Default E value
para->id = CRYPT_PKEY_RSA;
para->para.rsaPara.bits = bits;
para->para.rsaPara.e = e;
para->para.rsaPara.eLen = sizeof(e);
if (CRYPT_EAL_PkeySetPara(pkey, para) != CRYPT_SUCCESS) {
AppPrintError("%s: Failed to set RSA parameters.\n", HITLS_APP_GetProgName());
BSL_SAL_FREE(para);
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
BSL_SAL_FREE(para);
if (CRYPT_EAL_PkeyGen(pkey) != CRYPT_SUCCESS) {
AppPrintError("%s: Failed to generate the RSA private key.\n", HITLS_APP_GetProgName());
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
int32_t padType = CRYPT_EMSA_PKCSV15;
if (CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_SET_RSA_PADDING, &padType, sizeof(padType)) != CRYPT_SUCCESS) {
AppPrintError("%s: Failed to set rsa padding.\n", HITLS_APP_GetProgName());
CRYPT_EAL_PkeyFreeCtx(pkey);
return NULL;
}
return pkey;
}
void HITLS_APP_PrintPassErrlog(void)
{
AppPrintError("The password length is incorrect. It should be in the range of %d to %d.\n", APP_MIN_PASS_LENGTH,
APP_MAX_PASS_LENGTH);
}
int32_t HITLS_APP_HexToByte(const char *hex, uint8_t **bin, uint32_t *len)
{
uint32_t prefixLen = strlen(APP_HEX_HEAD);
if (strncmp(hex, APP_HEX_HEAD, prefixLen) != 0 || strlen(hex) <= prefixLen) {
AppPrintError("Invalid hex value, should start with '0x'.\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
const char *num = hex + prefixLen;
uint32_t hexLen = strlen(num);
// Skip the preceding zeros.
for (uint32_t i = 0; i < hexLen; ++i) {
if (num[i] != '0' && (i + 1) != hexLen) {
num += i;
hexLen -= i;
break;
}
}
*len = (hexLen + 1) / HEX_TO_BYTE;
uint8_t *res = BSL_SAL_Malloc(*len);
if (res == NULL) {
AppPrintError("Allocate memory failed.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
uint32_t hexIdx = 0;
uint32_t binIdx = 0;
char *endptr;
char tmp[] = {'0', '0', '\0'};
while (hexIdx < hexLen) {
if (hexIdx == 0 && hexLen % HEX_TO_BYTE == 1) {
tmp[0] = '0';
} else {
tmp[0] = num[hexIdx++];
}
tmp[1] = num[hexIdx++];
res[binIdx++] = (uint32_t)strtol(tmp, &endptr, 16); // 16: hex
if (*endptr != '\0') {
BSL_SAL_Free(res);
return HITLS_APP_OPT_VALUE_INVALID;
}
}
*bin = res;
return HITLS_APP_SUCCESS;
} | 2302_82127028/openHiTLS-examples_5062 | apps/src/app_utils.c | C | unknown | 31,126 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_verify.h"
#include <stddef.h>
#include <stdbool.h>
#include <linux/limits.h>
#include "string.h"
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_errno.h"
#include "crypt_errno.h"
#include "app_function.h"
#include "bsl_list.h"
#include "app_errno.h"
#include "app_opt.h"
#include "app_help.h"
#include "app_print.h"
#include "app_conf.h"
#include "app_utils.h"
#include "crypt_eal_rand.h"
#include "hitls_pki_errno.h"
#include "hitls_cert_local.h"
typedef enum OptionChoice {
HITLS_APP_OPT_VERIFY_ERR = -1,
HITLS_APP_OPT_VERIFY_EOF = 0,
HITLS_APP_OPT_VERIFY_CERTS = HITLS_APP_OPT_VERIFY_EOF,
HITLS_APP_OPT_VERIFY_HELP = 1,
HITLS_APP_OPT_VERIFY_CAFILE,
HITLS_APP_OPT_VERIFY_VERBOSE,
HITLS_APP_OPT_VERIFY_NOKEYUSAGE
} HITLSOptType;
const HITLS_CmdOption g_verifyOpts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
{"nokeyusage", HITLS_APP_OPT_VERIFY_NOKEYUSAGE, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Set not to verify keyUsage"},
{"CAfile", HITLS_APP_OPT_VERIFY_CAFILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input ca file"},
{"verbose", HITLS_APP_OPT_VERIFY_VERBOSE, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print extra information"},
{"certs", HITLS_APP_OPT_VERIFY_CERTS, HITLS_APP_OPT_VALUETYPE_PARAMTERS, "Input certs"},
{NULL}
};
static bool g_verbose = false;
static bool g_noVerifyKeyUsage = false;
void PrintCertErr(HITLS_X509_Cert *cert)
{
if (!g_verbose) {
return;
}
BSL_Buffer subjectName = { NULL, 0 };
if (HITLS_X509_CertCtrl(cert, HITLS_X509_GET_SUBJECT_DN_STR, &subjectName, sizeof(BSL_Buffer)) ==
HITLS_PKI_SUCCESS) {
(void)AppPrintError("%s\n", subjectName.data);
BSL_SAL_FREE(subjectName.data);
}
}
bool CheckCertKeyUsage(HITLS_X509_Cert *cert, const char *certfile, uint32_t usage)
{
if (g_noVerifyKeyUsage) {
return true;
}
uint32_t keyUsage = 0;
int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_GET_KUSAGE, &keyUsage, sizeof(keyUsage));
if (ret != HITLS_PKI_SUCCESS) {
(void)AppPrintError("Failed to get the key usage of file %s, errCode = %d.\n", certfile, ret);
return false;
}
// Check only if the keyusage extension is present.
if (keyUsage == HITLS_X509_EXT_KU_NONE) {
return true;
}
if ((keyUsage & usage) == 0) {
PrintCertErr(cert);
(void)AppPrintError("Failed to check the key usage of file %s.\n", certfile);
return false;
}
return true;
}
int32_t InitVerify(HITLS_X509_StoreCtx *store, const char *cafile)
{
int32_t depth = 20; // HITLS_X509_STORECTX_SET_PARAM_DEPTH can be set to a maximum of 20
int32_t ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_PARAM_DEPTH, &depth, sizeof(int32_t));
if (ret != HITLS_PKI_SUCCESS) {
(void)AppPrintError("Failed to set the maximum depth of the certificate chain, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
int64_t timeval = BSL_SAL_CurrentSysTimeGet();
ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_SET_TIME, &timeval, sizeof(timeval));
if (ret != HITLS_PKI_SUCCESS) {
(void)AppPrintError("Failed to set time of the certificate chain, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_List *certlist = NULL;
ret = HITLS_X509_CertParseBundleFile(BSL_FORMAT_PEM, cafile, &certlist);
if (ret != HITLS_PKI_SUCCESS) {
(void)AppPrintError("Failed to parse certificate <%s>, errCode = %d.\n", cafile, ret);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_Cert **cert = BSL_LIST_First(certlist);
while (cert != NULL) {
if (!CheckCertKeyUsage(*cert, cafile, HITLS_X509_EXT_KU_KEY_CERT_SIGN)) {
ret = HITLS_APP_X509_FAIL;
break;
}
ret = HITLS_X509_StoreCtxCtrl(store, HITLS_X509_STORECTX_DEEP_COPY_SET_CA, *cert, sizeof(HITLS_X509_Cert));
if (ret != HITLS_PKI_SUCCESS) {
PrintCertErr(*cert);
ret = HITLS_APP_X509_FAIL;
(void)AppPrintError("Failed to add the certificate <%s> to the trust store, errCode = %d.\n", cafile, ret);
break;
}
cert = BSL_LIST_Next(certlist);
}
BSL_LIST_FREE(certlist, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
return ret;
}
static int32_t AddCertToChain(HITLS_X509_List *chain, HITLS_X509_Cert *cert)
{
int ref;
int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_REF_UP, &ref, sizeof(int));
if (ret != HITLS_PKI_SUCCESS) {
return ret;
}
ret = BSL_LIST_AddElement(chain, cert, BSL_LIST_POS_END);
if (ret != HITLS_PKI_SUCCESS) {
return ret;
}
return ret;
}
static int32_t VerifyCert(HITLS_X509_StoreCtx *storeCtx, const char *fileName)
{
HITLS_X509_Cert *cert = HITLS_APP_LoadCert(fileName, BSL_FORMAT_PEM);
if (cert == NULL) {
return HITLS_APP_X509_FAIL;
}
const char *errStr = fileName == NULL ? "stdin" : fileName;
if (!CheckCertKeyUsage(cert, errStr, HITLS_X509_EXT_KU_KEY_ENCIPHERMENT)) {
HITLS_X509_CertFree(cert);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_List *chain = BSL_LIST_New(sizeof(HITLS_X509_Cert *));
if (chain == NULL) {
AppPrintError("Failed to create the certificate chain from %s.\n", errStr);
HITLS_X509_CertFree(cert);
return HITLS_APP_X509_FAIL;
}
int32_t ret = AddCertToChain(chain, cert);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("Failed to add the chain from %s, errCode = %d.\n", errStr, ret);
HITLS_X509_CertFree(cert);
BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CertVerify(storeCtx, chain);
if (ret != HITLS_PKI_SUCCESS) {
PrintCertErr(cert);
HITLS_X509_CertFree(cert);
BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
(void)AppPrintError("error %s: verification failed, errCode = %d.\n", errStr, ret);
return HITLS_APP_X509_FAIL;
}
HITLS_X509_CertFree(cert);
BSL_LIST_FREE(chain, (BSL_LIST_PFUNC_FREE)HITLS_X509_CertFree);
(void)AppPrintError("%s: OK\n", errStr);
return HITLS_APP_SUCCESS;
}
static int32_t VerifyCerts(HITLS_X509_StoreCtx *storeCtx, int argc, char **argv)
{
int32_t ret = HITLS_APP_SUCCESS;
if (argc == 0) {
return VerifyCert(storeCtx, NULL);
} else {
for (int i = 0; i < argc; ++i) {
ret = VerifyCert(storeCtx, argv[i]);
if (ret != HITLS_APP_SUCCESS) {
return HITLS_APP_X509_FAIL;
}
}
}
return ret;
}
static int32_t OptParse(char **cafile)
{
HITLSOptType optType;
int ret = HITLS_APP_SUCCESS;
while ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_VERIFY_EOF) {
switch (optType) {
case HITLS_APP_OPT_VERIFY_EOF:
case HITLS_APP_OPT_VERIFY_ERR:
ret = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("verify: Use -help for summary.\n");
return ret;
case HITLS_APP_OPT_VERIFY_HELP:
ret = HITLS_APP_HELP;
(void)HITLS_APP_OptHelpPrint(g_verifyOpts);
return ret;
case HITLS_APP_OPT_VERIFY_CAFILE:
*cafile = HITLS_APP_OptGetValueStr();
if (*cafile == NULL || strlen(*cafile) >= PATH_MAX) {
AppPrintError("The length of CA file error, range is (0, 4096).\n");
return HITLS_APP_OPT_VALUE_INVALID;
}
break;
case HITLS_APP_OPT_VERIFY_VERBOSE:
g_verbose = true;
break;
case HITLS_APP_OPT_VERIFY_NOKEYUSAGE:
g_noVerifyKeyUsage = true;
break;
default:
return HITLS_APP_OPT_UNKOWN;
}
}
return HITLS_APP_SUCCESS;
}
int32_t HITLS_VerifyMain(int argc, char *argv[])
{
HITLS_X509_StoreCtx *store = NULL;
char *cafile = NULL;
int32_t mainRet = HITLS_APP_SUCCESS;
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR,
"provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) {
mainRet = HITLS_APP_CRYPTO_FAIL;
goto end;
}
mainRet = HITLS_APP_OptBegin(argc, argv, g_verifyOpts);
if (mainRet != HITLS_APP_SUCCESS) {
(void)AppPrintError("error in opt begin.\n");
goto end;
}
mainRet = OptParse(&cafile);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
if (cafile == NULL) {
mainRet = HITLS_APP_OPT_UNKOWN;
(void)AppPrintError("Failed to complete the verification because the CAfile file is not obtained\n");
goto end;
}
store = HITLS_X509_StoreCtxNew();
if (store == NULL) {
mainRet = HITLS_APP_X509_FAIL;
(void)AppPrintError("Failed to create the store context.\n");
goto end;
}
mainRet = InitVerify(store, cafile);
if (mainRet != HITLS_APP_SUCCESS) {
goto end;
}
int unParseParamNum = HITLS_APP_GetRestOptNum();
char **unParseParam = HITLS_APP_GetRestOpt();
mainRet = VerifyCerts(store, unParseParamNum, unParseParam);
end:
HITLS_X509_StoreCtxFree(store);
HITLS_APP_OptEnd();
CRYPT_EAL_RandDeinitEx(NULL);
return mainRet;
} | 2302_82127028/openHiTLS-examples_5062 | apps/src/app_verify.c | C | unknown | 9,988 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "app_x509.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <securec.h>
#include <linux/limits.h>
#include "bsl_list.h"
#include "bsl_print.h"
#include "bsl_buffer.h"
#include "bsl_conf.h"
#include "bsl_errno.h"
#include "crypt_errno.h"
#include "crypt_eal_rand.h"
#include "crypt_encode_decode_key.h"
#include "crypt_eal_codecs.h"
#include "crypt_eal_md.h"
#include "hitls_pki_errno.h"
#include "app_errno.h"
#include "app_help.h"
#include "app_print.h"
#include "app_conf.h"
#include "app_opt.h"
#include "app_utils.h"
#include "app_list.h"
#define X509_DEFAULT_CERT_DAYS 30
#define X509_DEFAULT_SERIAL_SIZE 20
#define X509_DAY_SECONDS (24 * 60 * 60)
#define X509_SET_SERIAL_PREFIX "0x"
#define X509_MAX_MD_LEN 64
#define X509_SHAKE128_DIGEST_LEN 16
#define X509_SHAKE256_DIGEST_LEN 32
typedef enum {
HITLS_APP_OPT_IN = 2,
HITLS_APP_OPT_INFORM,
HITLS_APP_OPT_REQ,
HITLS_APP_OPT_OUT,
HITLS_APP_OPT_OUTFORM,
HITLS_APP_OPT_NOOUT,
HITLS_APP_OPT_TEXT,
HITLS_APP_OPT_ISSUER,
HITLS_APP_OPT_SUBJECT,
HITLS_APP_OPT_NAMEOPT,
HITLS_APP_OPT_SUBJECT_HASH,
HITLS_APP_OPT_FINGERPRINT,
HITLS_APP_OPT_PUBKEY,
HITLS_APP_OPT_DAYS,
HITLS_APP_OPT_SET_SERIAL,
HITLS_APP_OPT_EXT_FILE,
HITLS_APP_OPT_EXT_SECTION,
HITLS_APP_OPT_MD_ALG,
HITLS_APP_OPT_SIGN_KEY,
HITLS_APP_OPT_PASSIN,
HITLS_APP_OPT_CA,
HITLS_APP_OPT_CA_KEY,
HITLS_APP_OPT_USERID,
} HITLSOptType;
const HITLS_CmdOption g_x509Opts[] = {
{"help", HITLS_APP_OPT_HELP, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Display this function summary"},
/* General opts */
{"in", HITLS_APP_OPT_IN, HITLS_APP_OPT_VALUETYPE_IN_FILE, "Input file"},
{"inform", HITLS_APP_OPT_INFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Input format"},
{"req", HITLS_APP_OPT_REQ, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Input is a csr, sign and output"},
{"out", HITLS_APP_OPT_OUT, HITLS_APP_OPT_VALUETYPE_OUT_FILE, "Output file"},
{"outform", HITLS_APP_OPT_OUTFORM, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, "Output format"},
{"noout", HITLS_APP_OPT_NOOUT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "No Cert output "},
/* Print opts */
{"nameopt", HITLS_APP_OPT_NAMEOPT, HITLS_APP_OPT_VALUETYPE_STRING,
"Cert name options: oneline|multiline|rfc2253 - def oneline"},
{"issuer", HITLS_APP_OPT_ISSUER, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print issuer DN"},
{"subject", HITLS_APP_OPT_SUBJECT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print subject DN"},
{"hash", HITLS_APP_OPT_SUBJECT_HASH, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print subject DN hash"},
{"fingerprint", HITLS_APP_OPT_FINGERPRINT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print fingerprint"},
{"pubkey", HITLS_APP_OPT_PUBKEY, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Output the pubkey"},
{"text", HITLS_APP_OPT_TEXT, HITLS_APP_OPT_VALUETYPE_NO_VALUE, "Print x509 cert in text"},
/* Certificate output opts */
{"days", HITLS_APP_OPT_DAYS, HITLS_APP_OPT_VALUETYPE_POSITIVE_INT,
"How long before the certificate expires - def 30 days"},
{"set_serial", HITLS_APP_OPT_SET_SERIAL, HITLS_APP_OPT_VALUETYPE_STRING, "Cer serial number"},
{"extfile", HITLS_APP_OPT_EXT_FILE, HITLS_APP_OPT_VALUETYPE_IN_FILE, "File with x509v3 extension to add"},
{"extensions", HITLS_APP_OPT_EXT_SECTION, HITLS_APP_OPT_VALUETYPE_STRING, "Section from config file to use"},
{"md", HITLS_APP_OPT_MD_ALG, HITLS_APP_OPT_VALUETYPE_STRING, "Any supported digest algorithm."},
{"signkey", HITLS_APP_OPT_SIGN_KEY, HITLS_APP_OPT_VALUETYPE_IN_FILE,
"Privkey file for self sign cert, must be PEM format"},
{"passin", HITLS_APP_OPT_PASSIN, HITLS_APP_OPT_VALUETYPE_STRING, "Private key and cert file pass-phrase source"},
{"CA", HITLS_APP_OPT_CA, HITLS_APP_OPT_VALUETYPE_IN_FILE, "CA certificate, must be PEM format"},
{"CAkey", HITLS_APP_OPT_CA_KEY, HITLS_APP_OPT_VALUETYPE_IN_FILE, "CA key, must be PEM format"},
{"userId", HITLS_APP_OPT_USERID, HITLS_APP_OPT_VALUETYPE_STRING, "sm2 userId, default is null"},
{NULL},
};
typedef struct {
bool req;
char *inPath;
BSL_ParseFormat inForm;
char *outPath;
BSL_ParseFormat outForm;
bool noout;
char *passInArg;
} X509GeneralOpts;
typedef struct {
int32_t nameOpt;
bool issuer;
bool subject;
bool subjectHash;
bool text;
int32_t mdId;
bool fingerprint;
bool pubKey;
} X509PrintOpts;
typedef struct {
int32_t mdId;
int64_t days; // default to 30.
uint8_t *serial; // If this parameter is not specified, the value is generated randomly.
uint32_t serialLen;
char *extFile;
char *extSection;
char *signKeyPath;
char *caPath;
char *caKeyPath;
} X509CertOpts;
typedef struct {
X509GeneralOpts generalOpts;
X509PrintOpts printOpts;
X509CertOpts certOpts;
BSL_UIO *outUio;
BSL_CONF *conf;
HITLS_X509_Cert *cert;
HITLS_X509_Cert *ca;
HITLS_X509_Csr *csr;
HITLS_X509_Ext *certExt;
CRYPT_EAL_PkeyCtx *privKey;
char *passin; // pass of privkey
BSL_Buffer encodeCert;
char *userId;
} X509OptCtx;
typedef int32_t (*X509OptHandleFunc)(X509OptCtx *);
typedef struct {
int optType;
X509OptHandleFunc func;
} X509OptHandleFuncMap;
typedef int32_t (*ExtConfHandleFunc)(char *cnfValue, X509OptCtx *optCtx);
typedef struct {
char *extName;
ExtConfHandleFunc func;
} X509ExtHandleFuncMap;
typedef struct {
const char *nameopt;
int32_t printFlag;
} X509NamePrintFlag;
typedef int32_t (*PrintX509Func)(const X509OptCtx *);
/**
* 6 types of data printing:
* 1. issuer
* 2. subject
* 3. hash
* 4. fingerprint
* 5. pubKey
* 6. cert
*/
PrintX509Func g_printX509FuncList[] = {NULL, NULL, NULL, NULL, NULL, NULL};
#define PRINT_X509_FUNC_LIST_CNT (sizeof(g_printX509FuncList) / sizeof(PrintX509Func))
static void AppPushPrintX509Func(PrintX509Func func)
{
for (size_t i = 0; i < PRINT_X509_FUNC_LIST_CNT; ++i) {
if ((g_printX509FuncList[i] == NULL) || (g_printX509FuncList[i] == func)) {
g_printX509FuncList[i] = func;
return;
}
}
}
static int32_t AppPrintX509(const X509OptCtx *optCtx)
{
int32_t ret = HITLS_APP_SUCCESS;
for (size_t i = 0; i < PRINT_X509_FUNC_LIST_CNT; ++i) {
if ((g_printX509FuncList[i] != NULL)) {
ret = g_printX509FuncList[i](optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
}
}
return ret;
}
static void ResetPrintX509FuncList(void)
{
for (size_t i = 0; i < PRINT_X509_FUNC_LIST_CNT; ++i) {
g_printX509FuncList[i] = NULL;
}
}
static int32_t PrintIssuer(const X509OptCtx *optCtx)
{
BslList *issuer = NULL;
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_GET_ISSUER_DN, &issuer, sizeof(BslList *));
if (ret != 0) {
AppPrintError("x509: Get issuer name failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = BSL_PRINT_Fmt(0, optCtx->outUio,
optCtx->printOpts.nameOpt == HITLS_PKI_PRINT_DN_MULTILINE ? "Issuer=\n" : "Issuer=");
if (ret != 0) {
AppPrintError("x509: Print issuer name failed, errCode=%d.\n", ret);
return HITLS_APP_BSL_FAIL;
}
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_DNNAME, issuer, sizeof(BslList), optCtx->outUio);
if (ret != 0) {
AppPrintError("x509: Print issuer failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t PrintSubject(const X509OptCtx *optCtx)
{
BslList *subject = NULL;
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_GET_SUBJECT_DN, &subject, sizeof(BslList *));
if (ret != 0) {
AppPrintError("x509: Get subject name failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = BSL_PRINT_Fmt(0, optCtx->outUio,
optCtx->printOpts.nameOpt == HITLS_PKI_PRINT_DN_MULTILINE ? "Subject=\n" : "Subject=");
if (ret != 0) {
AppPrintError("x509: Print subject name failed, errCode=%d.\n", ret);
return HITLS_APP_BSL_FAIL;
}
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_DNNAME, subject, sizeof(BslList), optCtx->outUio);
if (ret != 0) {
AppPrintError("x509: Print subject failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t PrintSubjectHash(const X509OptCtx *optCtx)
{
BslList *subject = NULL;
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_GET_SUBJECT_DN, &subject, sizeof(BslList *));
if (ret != 0) {
AppPrintError("x509: Get subject name for hash failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_DNNAME_HASH, subject, sizeof(BslList), optCtx->outUio);
if (ret != 0) {
AppPrintError("x509: Print subject hash failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t PrintFingerPrint(const X509OptCtx *optCtx)
{
uint8_t md[X509_MAX_MD_LEN] = {0};
uint32_t mdLen = X509_MAX_MD_LEN;
if (optCtx->printOpts.mdId == CRYPT_MD_SHAKE128) {
mdLen = X509_SHAKE128_DIGEST_LEN;
} else if (optCtx->printOpts.mdId == CRYPT_MD_SHAKE256) {
mdLen = X509_SHAKE256_DIGEST_LEN;
}
int32_t ret = HITLS_X509_CertDigest(optCtx->cert, optCtx->printOpts.mdId, md, &mdLen);
if (ret != 0) {
AppPrintError("x509: Get cert digest failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = BSL_PRINT_Fmt(0, optCtx->outUio, "%s Fingerprint=",
HITLS_APP_GetNameByCid(optCtx->printOpts.mdId, HITLS_APP_LIST_OPT_DGST_ALG));
if (ret != 0) {
AppPrintError("x509: Print fingerprint failed, errCode=%d.\n", ret);
return HITLS_APP_BSL_FAIL;
}
ret = BSL_PRINT_Hex(0, true, md, mdLen, optCtx->outUio);
if (ret != 0) {
AppPrintError("x509: Print fingerprint failed, errCode=%d.\n", ret);
return HITLS_APP_BSL_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t PrintCert(const X509OptCtx *optCtx)
{
int32_t ret = HITLS_PKI_PrintCtrl(HITLS_PKI_PRINT_CERT, optCtx->cert, sizeof(HITLS_X509_Cert *), optCtx->outUio);
if (ret != 0) {
AppPrintError("x509: Print cert failed, errCode=%d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509OptErr(X509OptCtx *optCtx)
{
(void)optCtx;
AppPrintError("x509: Use -help for summary.\n");
return HITLS_APP_OPT_UNKOWN;
}
static int32_t X509OptHelp(X509OptCtx *optCtx)
{
(void)optCtx;
HITLS_APP_OptHelpPrint(g_x509Opts);
return HITLS_APP_HELP;
}
static int32_t X509OptIn(X509OptCtx *optCtx)
{
optCtx->generalOpts.inPath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptOut(X509OptCtx *optCtx)
{
optCtx->generalOpts.outPath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptInForm(X509OptCtx *optCtx)
{
char *str = HITLS_APP_OptGetValueStr();
int32_t ret =
HITLS_APP_OptGetFormatType(str, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, (uint32_t *)&optCtx->generalOpts.inForm);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("x509: Invalid format \"%s\" for -inform.\nx509: Use -help for summary.\n", str);
}
return ret;
}
static int32_t X509OptOutForm(X509OptCtx *optCtx)
{
char *str = HITLS_APP_OptGetValueStr();
int32_t ret =
HITLS_APP_OptGetFormatType(str, HITLS_APP_OPT_VALUETYPE_FMT_PEMDER, (uint32_t *)&optCtx->generalOpts.outForm);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("x509: Invalid format \"%s\" for -outform.\nx509: Use -help for summary.\n", str);
}
return ret;
}
static int32_t X509OptReq(X509OptCtx *optCtx)
{
optCtx->generalOpts.req = true;
return HITLS_APP_SUCCESS;
}
static int32_t X509OptNoout(X509OptCtx *optCtx)
{
optCtx->generalOpts.noout = true;
return HITLS_APP_SUCCESS;
}
static int32_t X509OptIssuer(X509OptCtx *optCtx)
{
optCtx->printOpts.issuer = true;
AppPushPrintX509Func(PrintIssuer);
return HITLS_APP_SUCCESS;
}
static int32_t X509OptSubject(X509OptCtx *optCtx)
{
optCtx->printOpts.subject = true;
AppPushPrintX509Func(PrintSubject);
return HITLS_APP_SUCCESS;
}
static int32_t X509OptNameOpt(X509OptCtx *optCtx)
{
static const X509NamePrintFlag printFlags[] = {
{"oneline", HITLS_PKI_PRINT_DN_ONELINE},
{"multiline", HITLS_PKI_PRINT_DN_MULTILINE},
{"rfc2253", HITLS_PKI_PRINT_DN_RFC2253},
};
char *str = HITLS_APP_OptGetValueStr();
for (size_t i = 0; i < (sizeof(printFlags) / sizeof(X509NamePrintFlag)); ++i) {
if (strcmp(printFlags[i].nameopt, str) == 0) {
optCtx->printOpts.nameOpt = printFlags[i].printFlag;
return HITLS_APP_SUCCESS;
}
}
AppPrintError("x509: Invalid nameopt %s.\nx509: Use -help for summary.\n", str);
return HITLS_APP_OPT_VALUE_INVALID;
}
static int32_t X509OptSubjectHash(X509OptCtx *optCtx)
{
(void)optCtx;
AppPushPrintX509Func(PrintSubjectHash);
return HITLS_APP_SUCCESS;
}
static int32_t X509OptFingerprint(X509OptCtx *optCtx)
{
(void)optCtx;
AppPushPrintX509Func(PrintFingerPrint);
return HITLS_APP_SUCCESS;
}
static int32_t X509OptText(X509OptCtx *optCtx)
{
optCtx->printOpts.text = true;
AppPushPrintX509Func(PrintCert);
return HITLS_APP_SUCCESS;
}
static int32_t X509OptPubkey(X509OptCtx *optCtx)
{
(void)optCtx;
optCtx->printOpts.pubKey = true;
return HITLS_APP_SUCCESS;
}
static int32_t X509OptMdId(X509OptCtx *optCtx)
{
optCtx->certOpts.mdId = HITLS_APP_GetCidByName(HITLS_APP_OptGetValueStr(), HITLS_APP_LIST_OPT_DGST_ALG);
optCtx->printOpts.mdId = optCtx->certOpts.mdId;
return optCtx->certOpts.mdId == BSL_CID_UNKNOWN ? HITLS_APP_OPT_VALUE_INVALID : HITLS_APP_SUCCESS;
}
static int32_t X509OptDays(X509OptCtx *optCtx)
{
int32_t ret = HITLS_APP_OptGetUint32(HITLS_APP_OptGetValueStr(), (uint32_t *)&optCtx->certOpts.days);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("x509: Invalid days.\nx509: Use -help for summary.\n");
}
return ret;
}
static int32_t X509OptSetSerial(X509OptCtx *optCtx)
{
char *str = HITLS_APP_OptGetValueStr();
int32_t ret = HITLS_APP_HexToByte(str, &optCtx->certOpts.serial, &optCtx->certOpts.serialLen);
if (ret != HITLS_APP_SUCCESS) {
AppPrintError("x509: Invalid serial: %s.\n", str);
}
return ret;
}
static int32_t X509OptExtFile(X509OptCtx *optCtx)
{
optCtx->certOpts.extFile = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptExtSection(X509OptCtx *optCtx)
{
optCtx->certOpts.extSection = HITLS_APP_OptGetValueStr();
if (strlen(optCtx->certOpts.extSection) > BSL_CONF_SEC_SIZE) {
AppPrintError("x509: Invalid extensions, size should less than %d.\n", BSL_CONF_SEC_SIZE);
return HITLS_APP_OPT_VALUE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509OptSignKey(X509OptCtx *optCtx)
{
optCtx->certOpts.signKeyPath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptPassin(X509OptCtx *optCtx)
{
optCtx->generalOpts.passInArg = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptCa(X509OptCtx *optCtx)
{
optCtx->certOpts.caPath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509OptCaKey(X509OptCtx *optCtx)
{
optCtx->certOpts.caKeyPath = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static int32_t X509UserId(X509OptCtx *optCtx)
{
optCtx->userId = HITLS_APP_OptGetValueStr();
return HITLS_APP_SUCCESS;
}
static const X509OptHandleFuncMap g_x509OptHandleFuncMap[] = {
{HITLS_APP_OPT_ERR, X509OptErr},
{HITLS_APP_OPT_HELP, X509OptHelp},
{HITLS_APP_OPT_IN, X509OptIn},
{HITLS_APP_OPT_INFORM, X509OptInForm},
{HITLS_APP_OPT_REQ, X509OptReq},
{HITLS_APP_OPT_OUT, X509OptOut},
{HITLS_APP_OPT_OUTFORM, X509OptOutForm},
{HITLS_APP_OPT_NOOUT, X509OptNoout},
{HITLS_APP_OPT_ISSUER, X509OptIssuer},
{HITLS_APP_OPT_SUBJECT, X509OptSubject},
{HITLS_APP_OPT_NAMEOPT, X509OptNameOpt},
{HITLS_APP_OPT_SUBJECT_HASH, X509OptSubjectHash},
{HITLS_APP_OPT_FINGERPRINT, X509OptFingerprint},
{HITLS_APP_OPT_PUBKEY, X509OptPubkey},
{HITLS_APP_OPT_TEXT, X509OptText},
{HITLS_APP_OPT_MD_ALG, X509OptMdId},
{HITLS_APP_OPT_DAYS, X509OptDays},
{HITLS_APP_OPT_SET_SERIAL, X509OptSetSerial},
{HITLS_APP_OPT_EXT_FILE, X509OptExtFile},
{HITLS_APP_OPT_EXT_SECTION, X509OptExtSection},
{HITLS_APP_OPT_SIGN_KEY, X509OptSignKey},
{HITLS_APP_OPT_PASSIN, X509OptPassin},
{HITLS_APP_OPT_CA, X509OptCa},
{HITLS_APP_OPT_CA_KEY, X509OptCaKey},
{HITLS_APP_OPT_USERID, X509UserId},
};
static int32_t ParseX509Opt(int argc, char *argv[], X509OptCtx *optCtx)
{
int32_t ret = HITLS_APP_OptBegin(argc, argv, g_x509Opts);
if (ret != HITLS_APP_SUCCESS) {
HITLS_APP_OptEnd();
AppPrintError("error in opt begin.\n");
return ret;
}
int optType = HITLS_APP_OPT_ERR;
while ((ret == HITLS_APP_SUCCESS) && ((optType = HITLS_APP_OptNext()) != HITLS_APP_OPT_EOF)) {
for (size_t i = 0; i < (sizeof(g_x509OptHandleFuncMap) / sizeof(g_x509OptHandleFuncMap[0])); ++i) {
if (optType == g_x509OptHandleFuncMap[i].optType) {
ret = g_x509OptHandleFuncMap[i].func(optCtx);
break;
}
}
}
// Obtain the number of parameters that cannot be parsed in the current version,
// and print the error information and help list.
if ((ret == HITLS_APP_SUCCESS) && (HITLS_APP_GetRestOptNum() != 0)) {
AppPrintError("x509: Extra arguments given.\nx509: Use -help for summary.\n");
ret = HITLS_APP_OPT_UNKOWN;
}
HITLS_APP_OptEnd();
return ret;
}
static int32_t GetCertPubkeyEncodeBuff(
HITLS_X509_Cert *cert, BSL_ParseFormat format, bool isComplete, BSL_Buffer *encode)
{
CRYPT_EAL_PkeyCtx *pubKey = NULL;
int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_GET_PUBKEY, &pubKey, 0);
if (ret != 0) {
AppPrintError("x509: Get pubKey from cert failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = CRYPT_EAL_EncodePubKeyBuffInternal(pubKey, format, CRYPT_PUBKEY_SUBKEY, isComplete, encode);
CRYPT_EAL_PkeyFreeCtx(pubKey);
if (ret != CRYPT_SUCCESS) {
AppPrintError("x509: Encode pubKey failed, errCode = %d.\n", ret);
return HITLS_APP_ENCODE_KEY_FAIL;
}
return HITLS_APP_SUCCESS;
}
/**
* RFC 5280:
* section 4.1
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING
* }
* AlgorithmIdentifier ::= SEQUENCE { ... }
*
* section 4.2.1.2
* (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the value of the
* BIT STRING subjectPublicKey (excluding the tag, length, and number of unused bits).
*/
static int32_t GetCertKid(HITLS_X509_Cert *cert, BSL_ParseFormat format, BSL_Buffer *buff)
{
// 1. Get the encode value of algotithm and subjectPublicKey.
BSL_Buffer info = {0};
int32_t ret = GetCertPubkeyEncodeBuff(cert, format, false, &info);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// 2. Skip the algorithm
uint8_t *enc = info.data;
uint32_t encLen = info.dataLen;
uint32_t vLen = 0;
ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, &enc, &encLen, &vLen);
if (ret != 0) {
AppPrintError("x509: Decode pubKey failed, errCode = %d.\n", ret);
ret = HITLS_APP_DECODE_FAIL;
goto EXIT;
}
enc += vLen;
encLen -= vLen;
// 3. Skip the tag, length and unusedBits of bitstring
ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_BITSTRING, &enc, &encLen, &vLen);
if (ret != 0) {
AppPrintError("x509: Decode pubKey failed, errCode = %d.\n", ret);
ret = HITLS_APP_DECODE_FAIL;
goto EXIT;
}
enc += 1; // 1: skip the unusedBits of bitstring
encLen -= 1;
// 4. sha1
buff->data = BSL_SAL_Malloc(20); // 20: CRYPT_SHA1_DIGESTSIZE
if (buff->data == NULL) {
AppPrintError("x509: Allocate memory for kid failed.\n");
ret = HITLS_APP_MEM_ALLOC_FAIL;
goto EXIT;
}
buff->dataLen = 20; // 20: CRYPT_SHA1_DIGESTSIZE
ret = CRYPT_EAL_Md(CRYPT_MD_SHA1, enc, encLen, buff->data, &buff->dataLen);
if (ret != CRYPT_SUCCESS) {
BSL_SAL_FREE(buff->data);
buff->dataLen = 0;
AppPrintError("x509: Failed to calculate the kid, errCode = %d.\n", ret);
ret = HITLS_APP_CRYPTO_FAIL;
goto EXIT;
}
ret = HITLS_APP_SUCCESS;
EXIT:
BSL_SAL_Free(info.data);
return ret;
}
static int32_t LoadConf(X509OptCtx *optCtx)
{
if (optCtx->certOpts.extFile == NULL || optCtx->certOpts.extSection == NULL) {
return HITLS_APP_SUCCESS;
}
optCtx->conf = BSL_CONF_New(BSL_CONF_DefaultMethod());
if (optCtx->conf == NULL) {
AppPrintError("x509: New conf failed.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
int32_t ret = BSL_CONF_Load(optCtx->conf, optCtx->certOpts.extFile);
if (ret != 0) {
BSL_CONF_Free(optCtx->conf);
optCtx->conf = NULL;
AppPrintError("x509: Load extfile %s failed, errCode = %d.\n", optCtx->certOpts.extFile, ret);
return HITLS_APP_CONF_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t LoadRelatedFiles(X509OptCtx *optCtx)
{
// Load and verify csr
optCtx->csr = HITLS_APP_LoadCsr(optCtx->generalOpts.inPath, optCtx->generalOpts.inForm);
if (optCtx->csr == NULL) {
AppPrintError("x509: Load csr failed\n");
return HITLS_APP_LOAD_CSR_FAIL;
}
int32_t ret;
if (optCtx->userId != NULL) {
ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_SET_VFY_SM2_USER_ID, optCtx->userId, strlen(optCtx->userId));
if (ret != 0) {
AppPrintError("x509: set userId failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
ret = HITLS_X509_CsrVerify(optCtx->csr);
if (ret != 0) {
AppPrintError("x509: Verify csr failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
if (HITLS_APP_ParsePasswd(optCtx->generalOpts.passInArg, &optCtx->passin) != HITLS_APP_SUCCESS) {
return HITLS_APP_PASSWD_FAIL;
}
// Load private key
if (optCtx->certOpts.signKeyPath != NULL) {
optCtx->privKey = HITLS_APP_LoadPrvKey(optCtx->certOpts.signKeyPath, BSL_FORMAT_PEM, &optCtx->passin);
} else if (optCtx->certOpts.caKeyPath != NULL) {
optCtx->privKey = HITLS_APP_LoadPrvKey(optCtx->certOpts.caKeyPath, BSL_FORMAT_PEM, &optCtx->passin);
}
if (optCtx->privKey == NULL) {
AppPrintError("x509: Load signkey or cakey failed.\n");
return HITLS_APP_LOAD_KEY_FAIL;
}
if (optCtx->userId != NULL) {
ret = CRYPT_EAL_PkeyCtrl(optCtx->privKey, CRYPT_CTRL_SET_SM2_USER_ID, optCtx->userId, strlen(optCtx->userId));
if (ret != 0) {
AppPrintError("x509: set userId failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
// Load ca
if (optCtx->certOpts.caPath != NULL) {
optCtx->ca = HITLS_APP_LoadCert(optCtx->certOpts.caPath, BSL_FORMAT_PEM);
if (optCtx->ca == NULL) {
AppPrintError("x509: Load ca failed\n");
return HITLS_APP_LOAD_CERT_FAIL;
}
CRYPT_EAL_PkeyCtx *pubKey = NULL;
ret = HITLS_X509_CertCtrl(optCtx->ca, HITLS_X509_GET_PUBKEY, &pubKey, 0);
if (ret != 0) {
AppPrintError("x509: Get pubKey from ca failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = CRYPT_EAL_PkeyPairCheck(pubKey, optCtx->privKey);
CRYPT_EAL_PkeyFreeCtx(pubKey);
if (ret != 0) {
AppPrintError("x509: CA public key and CA private key do not match, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
return LoadConf(optCtx);
}
static int32_t SetSerial(X509OptCtx *optCtx)
{
int32_t ret;
if (optCtx->certOpts.serial == NULL) {
optCtx->certOpts.serial = BSL_SAL_Malloc(X509_DEFAULT_SERIAL_SIZE);
if (optCtx->certOpts.serial == NULL) {
AppPrintError("x509: Allocate serial memory failed.\n");
return HITLS_APP_MEM_ALLOC_FAIL;
}
optCtx->certOpts.serialLen = X509_DEFAULT_SERIAL_SIZE;
if ((ret = CRYPT_EAL_RandbytesEx(NULL, optCtx->certOpts.serial, optCtx->certOpts.serialLen)) != 0) {
BSL_SAL_FREE(optCtx->certOpts.serial);
AppPrintError("x509: Generate serial number failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
ret = HITLS_X509_CertCtrl(
optCtx->cert, HITLS_X509_SET_SERIALNUM, optCtx->certOpts.serial, optCtx->certOpts.serialLen);
if (ret != 0) {
AppPrintError("x509: Set serial number failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetValidity(X509OptCtx *optCtx)
{
int64_t startTime = BSL_SAL_CurrentSysTimeGet();
if (startTime == 0) {
AppPrintError("x509: Get system time failed.\n");
return HITLS_APP_SAL_FAIL;
}
if (optCtx->certOpts.days > (INT64_MAX - startTime) / X509_DAY_SECONDS) {
AppPrintError("x509: The sum of the current time and -days %lld outside integer range.\n", optCtx->certOpts.days);
return HITLS_APP_SAL_FAIL;
}
int64_t endTime = startTime + optCtx->certOpts.days * X509_DAY_SECONDS;
if (endTime >= 253402272000) { // 253402272000: utctime of 10000-01-01 00:00:00
AppPrintError("x509: The end time of cert is greatter than 9999 years.\n");
return HITLS_APP_INVALID_ARG;
}
BSL_TIME start = {0};
BSL_TIME end = {0};
if (BSL_SAL_UtcTimeToDateConvert(startTime, &start) != 0 || BSL_SAL_UtcTimeToDateConvert(endTime, &end) != 0) {
AppPrintError("x509: Time convert failed.\n");
return HITLS_APP_SAL_FAIL;
}
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_BEFORE_TIME, &start, sizeof(BSL_TIME));
if (ret != 0) {
AppPrintError("x509: Set start time failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_AFTER_TIME, &end, sizeof(BSL_TIME));
if (ret != 0) {
AppPrintError("x509: Set end time failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetCertDn(X509OptCtx *optCtx)
{
BslList *subject = NULL;
int32_t ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_GET_SUBJECT_DN, &subject, sizeof(BslList *));
if (ret != 0) {
AppPrintError("x509: Get subject from csr failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_SUBJECT_DN, subject, sizeof(BslList));
if (ret != 0) {
AppPrintError("x509: Set subject failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
BslList *issuer = subject;
if (optCtx->ca != NULL) {
ret = HITLS_X509_CertCtrl(optCtx->ca, HITLS_X509_GET_SUBJECT_DN, &issuer, sizeof(BslList *));
if (ret != 0) {
AppPrintError("x509: Get subject from ca failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_ISSUER_DN, issuer, sizeof(BslList));
if (ret != 0) {
AppPrintError("x509: Set issuer failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t CopyExtensionsFromCsr(X509OptCtx *optCtx)
{
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_CSR_EXT, optCtx->csr, 0);
if (ret == HITLS_X509_ERR_ATTR_NOT_FOUND) {
return HITLS_APP_SUCCESS;
}
if (ret != 0) {
AppPrintError("x509: Copy csr extensions failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
int32_t version = HITLS_X509_VERSION_3;
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_VERSION, &version, sizeof(version));
if (ret != 0) {
AppPrintError("x509: Set cert version failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509SetBasicConstraints(HITLS_X509_ExtBCons *bCons, X509OptCtx *optCtx)
{
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_SET_BCONS, bCons, sizeof(HITLS_X509_ExtBCons));
if (ret != 0) {
AppPrintError("x509: Set basicConstraints failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509SetKeyUsage(HITLS_X509_ExtKeyUsage *ku, X509OptCtx *optCtx)
{
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_SET_KUSAGE, ku, sizeof(HITLS_X509_ExtKeyUsage));
if (ret != 0) {
AppPrintError("x509: Set keyUsage failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509SetExtendKeyUsage(HITLS_X509_ExtExKeyUsage *exku, X509OptCtx *optCtx)
{
int32_t ret =
HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_SET_EXKUSAGE, exku, sizeof(HITLS_X509_ExtExKeyUsage));
if (ret != 0) {
AppPrintError("x509: Set extendKeyUsage failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509SetSubjectAltName(HITLS_X509_ExtSan *san, X509OptCtx *optCtx)
{
int32_t ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_SET_SAN, san, sizeof(HITLS_X509_ExtSan));
if (ret != 0) {
AppPrintError("x509: Set subjectAltName failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509SetSubjectKeyIdentifier(HITLS_X509_ExtSki *ski, HITLS_X509_Cert *cert, bool needFree)
{
int32_t ret = GetCertKid(cert, BSL_FORMAT_ASN1, &ski->kid);
if (ret != 0) {
return ret;
}
ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_SKI, ski, sizeof(HITLS_X509_ExtSki));
if (needFree) {
BSL_SAL_FREE(ski->kid.data);
}
if (ret != 0) {
AppPrintError("x509: Set subjectKeyIdentifier failed, errCode = %d.\n", ret);
BSL_SAL_FREE(ski->kid.data);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetSelfSignedCertAki(HITLS_CFG_ExtAki *cfgAki, HITLS_X509_Cert *cert)
{
// [keyid] set ski, kid is from csr or self-generated
// [keyid:always] set ski and aki, aki = ski
bool isSkiExist;
HITLS_X509_ExtAki aki = cfgAki->aki;
HITLS_X509_ExtSki ski = {0};
int32_t ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_CHECK_SKI, &isSkiExist, sizeof(bool));
if (ret != 0) {
AppPrintError("x509: Check cert subjectKeyIdentifier failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
if (isSkiExist && (cfgAki->flag & HITLS_CFG_X509_EXT_AKI_KID_ALWAYS) == 0) {
// Ski has been set and the cnf does not contain 'always'.
return HITLS_APP_SUCCESS;
}
if (isSkiExist) {
// get ski from cert
ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_GET_SKI, &ski, sizeof(HITLS_X509_ExtSki));
if (ret != 0) {
AppPrintError("x509: Get cert subjectKeyIdentifier failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
} else {
// generate ski and set ski
ret = X509SetSubjectKeyIdentifier(&ski, cert, false);
if (ret != 0) {
return ret;
}
if ((cfgAki->flag & HITLS_CFG_X509_EXT_AKI_KID_ALWAYS) == 0) {
BSL_SAL_Free(ski.kid.data);
return ret;
}
}
aki.kid = ski.kid;
ret = HITLS_X509_CertCtrl(cert, HITLS_X509_EXT_SET_AKI, &aki, sizeof(HITLS_X509_ExtAki));
if (!isSkiExist) {
BSL_SAL_Free(ski.kid.data);
}
if (ret != 0) {
AppPrintError("x509: Set cert authorityKeyIdentifier failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetNonSelfSignedCertAki(HITLS_CFG_ExtAki *cfgAki, X509OptCtx *optCtx)
{
// [keyid] set ski and aki, aki.kid is from issuer cert
HITLS_X509_ExtSki caSki = {0};
HITLS_X509_ExtAki aki = cfgAki->aki;
bool isSkiExist;
int32_t ret = HITLS_X509_CertCtrl(optCtx->ca, HITLS_X509_EXT_GET_SKI, &caSki, sizeof(HITLS_X509_ExtSki));
if (ret != 0) {
AppPrintError("x509: Get issuer keyId failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
aki.kid = caSki.kid;
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_SET_AKI, &aki, sizeof(HITLS_X509_ExtAki));
if (ret != 0) {
AppPrintError("x509: Set non-self-signed cert authorityKeyIdentifier failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_EXT_CHECK_SKI, &isSkiExist, sizeof(bool));
if (ret != 0) {
AppPrintError("x509: Check cert subjectKeyIdentifier failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
if (isSkiExist) {
return HITLS_APP_SUCCESS;
}
return X509SetSubjectKeyIdentifier(&caSki, optCtx->cert, true);
}
static int32_t X509SetAuthKeyIdentifier(HITLS_CFG_ExtAki *cfgAki, X509OptCtx *optCtx)
{
if (optCtx->ca == NULL) {
return SetSelfSignedCertAki(cfgAki, optCtx->cert);
} else {
return SetNonSelfSignedCertAki(cfgAki, optCtx);
}
}
static int32_t X509ProcExt(BslCid cid, void *val, X509OptCtx *optCtx)
{
if (val == NULL) {
return HITLS_APP_INTERNAL_EXCEPTION;
}
switch (cid) {
case BSL_CID_CE_BASICCONSTRAINTS:
return X509SetBasicConstraints(val, optCtx);
case BSL_CID_CE_KEYUSAGE:
return X509SetKeyUsage(val, optCtx);
case BSL_CID_CE_EXTKEYUSAGE:
return X509SetExtendKeyUsage(val, optCtx);
case BSL_CID_CE_AUTHORITYKEYIDENTIFIER:
return X509SetAuthKeyIdentifier(val, optCtx);
case BSL_CID_CE_SUBJECTKEYIDENTIFIER:
return X509SetSubjectKeyIdentifier(val, optCtx->cert, true);
case BSL_CID_CE_SUBJECTALTNAME:
return X509SetSubjectAltName(val, optCtx);
default:
AppPrintError("x509: Unsupported extension: %d.\n", (int32_t)cid);
return HITLS_APP_X509_FAIL;
}
}
static int32_t SetCertExtensionsByConf(X509OptCtx *optCtx)
{
if (optCtx->conf == NULL) {
return HITLS_APP_SUCCESS;
}
int32_t ret =
HITLS_APP_CONF_ProcExt(optCtx->conf, optCtx->certOpts.extSection, (ProcExtCallBack)X509ProcExt, optCtx);
if (ret != HITLS_APP_SUCCESS && ret != HITLS_APP_NO_EXT) {
return ret;
}
if (ret == HITLS_APP_NO_EXT) {
return HITLS_APP_SUCCESS;
}
int32_t version = HITLS_X509_VERSION_3;
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_VERSION, &version, sizeof(version));
if (ret != 0) {
AppPrintError("x509: Set cert version failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetPubKey(X509OptCtx *optCtx)
{
int32_t ret;
CRYPT_EAL_PkeyCtx *pubKey = NULL;
if (optCtx->ca == NULL) {
// self-signed cert
pubKey = optCtx->privKey;
} else {
// non self-signed cert
ret = HITLS_X509_CsrCtrl(optCtx->csr, HITLS_X509_GET_PUBKEY, &pubKey, 0);
if (ret != 0) {
AppPrintError("x509: Get pubKey from csr failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
ret = HITLS_X509_CertCtrl(optCtx->cert, HITLS_X509_SET_PUBKEY, pubKey, 0);
if (optCtx->ca != NULL) {
CRYPT_EAL_PkeyFreeCtx(pubKey);
}
if (ret != 0) {
AppPrintError("x509: Set public key failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t SetCertCont(X509OptCtx *optCtx)
{
// Pubkey must be set first, which will be used in set extensions
int32_t ret = SetPubKey(optCtx);
if (ret != 0) {
return ret;
}
ret = CopyExtensionsFromCsr(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = SetCertExtensionsByConf(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = SetSerial(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = SetValidity(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return SetCertDn(optCtx);
}
static int32_t GenCert(X509OptCtx *optCtx)
{
int32_t ret = LoadRelatedFiles(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
optCtx->cert = HITLS_X509_CertNew();
if (optCtx->cert == NULL) {
AppPrintError("x509: Failed to new a cert.\n");
return HITLS_APP_X509_FAIL;
}
ret = SetCertCont(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
ret = HITLS_X509_CertSign(optCtx->certOpts.mdId, optCtx->privKey, NULL, optCtx->cert);
if (ret != 0) {
AppPrintError("x509: sign cert failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
ret = HITLS_X509_CertGenBuff(optCtx->generalOpts.outForm, optCtx->cert, &optCtx->encodeCert);
if (ret != 0) {
AppPrintError("x509: encode cert failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t LoadCert(X509OptCtx *optCtx)
{
optCtx->cert = HITLS_APP_LoadCert(optCtx->generalOpts.inPath, optCtx->generalOpts.inForm);
if (optCtx->cert == NULL) {
return HITLS_APP_LOAD_CERT_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t OutputPubkey(X509OptCtx *optCtx)
{
if (!optCtx->printOpts.pubKey) {
return HITLS_APP_SUCCESS;
}
BSL_Buffer encodePubkey = {0};
int32_t ret = GetCertPubkeyEncodeBuff(optCtx->cert, BSL_FORMAT_PEM, true, &encodePubkey);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
uint32_t writeLen = 0;
ret = BSL_UIO_Write(optCtx->outUio, encodePubkey.data, encodePubkey.dataLen, &writeLen);
BSL_SAL_Free(encodePubkey.data);
if (ret != 0 || writeLen != encodePubkey.dataLen) {
AppPrintError("x509: write pubKey failed, errCode = %d, writeLen = %u.\n", ret, writeLen);
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static int32_t X509Output(X509OptCtx *optCtx)
{
int32_t ret;
optCtx->outUio = HITLS_APP_UioOpen(optCtx->generalOpts.outPath, 'w', 0);
if (optCtx->outUio == NULL) {
return HITLS_APP_UIO_FAIL;
}
BSL_UIO_SetIsUnderlyingClosedByUio(optCtx->outUio, true);
// Output cert info
if (optCtx->printOpts.issuer || optCtx->printOpts.subject || optCtx->printOpts.text) {
ret = HITLS_PKI_PrintCtrl(HITLS_PKI_SET_PRINT_FLAG, (void *)&optCtx->printOpts.nameOpt, sizeof(int32_t), NULL);
if (ret != 0) {
AppPrintError("x509: Set DN print flag failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
ret = AppPrintX509(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// Output pubKey
ret = OutputPubkey(optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
// Output cert der/pem
if (optCtx->generalOpts.noout) {
return HITLS_APP_SUCCESS;
}
if (optCtx->encodeCert.data == NULL) {
ret = HITLS_X509_CertGenBuff(optCtx->generalOpts.outForm, optCtx->cert, &optCtx->encodeCert);
if (ret != 0) {
AppPrintError("x509: encode cert failed, errCode = %d.\n", ret);
return HITLS_APP_X509_FAIL;
}
}
uint32_t writeLen = 0;
ret = BSL_UIO_Write(optCtx->outUio, optCtx->encodeCert.data, optCtx->encodeCert.dataLen, &writeLen);
if (ret != 0 || writeLen != optCtx->encodeCert.dataLen) {
AppPrintError("x509: write cert failed, errCode = %d, writeLen = %u.\n", ret, writeLen);
return HITLS_APP_UIO_FAIL;
}
return HITLS_APP_SUCCESS;
}
static bool CheckGenCertOpt(X509OptCtx *optCtx)
{
if (optCtx->certOpts.caPath != NULL) {
if (optCtx->certOpts.signKeyPath != NULL) {
AppPrintError("x509: Cannot use both -signkey and -CA.\n");
return false;
}
} else {
if (optCtx->certOpts.caKeyPath != NULL) {
if (optCtx->certOpts.signKeyPath != NULL) {
AppPrintError("x509: Cannot use both -CAkey and -signkey.\n");
return false;
} else {
AppPrintError("x509: Should use both -CA and -CAkey.\n");
return false;
}
}
}
if (optCtx->certOpts.signKeyPath == NULL && optCtx->certOpts.caKeyPath == NULL) {
AppPrintError("x509: We need a private key to genetate cert, use -signkey or -CAkey.\n");
return false;
}
if (optCtx->certOpts.extFile != NULL && optCtx->certOpts.extSection == NULL) {
AppPrintError("x509: Warning: ignoring -extFile since -extensions is not given.\n");
optCtx->certOpts.extFile = NULL;
}
if (optCtx->certOpts.extFile == NULL && optCtx->certOpts.extSection != NULL) {
AppPrintError("x509: Warning: ignoring -extensions since -extFile is not given.\n");
optCtx->certOpts.extSection = NULL;
}
return true;
}
static bool CheckOpt(X509OptCtx *optCtx)
{
if (optCtx->generalOpts.req) { // new cert
return CheckGenCertOpt(optCtx);
} else {
if (optCtx->certOpts.signKeyPath != NULL || optCtx->certOpts.caKeyPath != NULL ||
optCtx->certOpts.caPath != NULL) {
AppPrintError("x509: Warning: ignoring -signkey, -CA, -CAkey since -req is not given.\n");
optCtx->certOpts.caKeyPath = NULL;
optCtx->certOpts.signKeyPath = NULL;
optCtx->certOpts.caPath = NULL;
}
if (optCtx->certOpts.serialLen != 0) {
AppPrintError("x509: Warning: ignoring -set_serial since -req is not given.\n");
BSL_SAL_FREE(optCtx->certOpts.serial);
optCtx->certOpts.serialLen = 0;
}
if (optCtx->certOpts.extFile != NULL || optCtx->certOpts.extSection != NULL) {
AppPrintError("x509: Warning: ignoring -extfile or -extensions since -req is not given.\n");
optCtx->certOpts.extFile = NULL;
optCtx->certOpts.extSection = NULL;
}
}
return true;
}
int32_t HandleX509Opt(int argc, char *argv[], X509OptCtx *optCtx)
{
int32_t ret = ParseX509Opt(argc, argv, optCtx);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
if (!CheckOpt(optCtx)) {
return HITLS_APP_OPT_TYPE_INVALID;
}
return HITLS_APP_SUCCESS;
}
static void InitX509OptCtx(X509OptCtx *optCtx)
{
optCtx->generalOpts.inForm = BSL_FORMAT_PEM;
optCtx->generalOpts.outForm = BSL_FORMAT_PEM;
optCtx->generalOpts.req = false;
optCtx->generalOpts.noout = false;
optCtx->printOpts.nameOpt = HITLS_PKI_PRINT_DN_ONELINE;
optCtx->certOpts.days = X509_DEFAULT_CERT_DAYS;
optCtx->certOpts.mdId = CRYPT_MD_SHA256;
optCtx->printOpts.mdId = CRYPT_MD_SHA1;
}
static void UnInitX509OptCtx(X509OptCtx *optCtx)
{
BSL_UIO_Free(optCtx->outUio);
optCtx->outUio = NULL;
BSL_CONF_Free(optCtx->conf);
optCtx->conf = NULL;
HITLS_X509_CertFree(optCtx->cert);
optCtx->cert = NULL;
HITLS_X509_CertFree(optCtx->ca);
optCtx->ca = NULL;
HITLS_X509_CsrFree(optCtx->csr);
optCtx->csr = NULL;
CRYPT_EAL_PkeyFreeCtx(optCtx->privKey);
optCtx->privKey = NULL;
BSL_SAL_FREE(optCtx->certOpts.serial);
BSL_SAL_FREE(optCtx->encodeCert.data);
if (optCtx->passin != NULL) {
BSL_SAL_ClearFree(optCtx->passin, strlen(optCtx->passin));
}
}
// x509 main function
int32_t HITLS_X509Main(int argc, char *argv[])
{
ResetPrintX509FuncList();
X509OptCtx optCtx = {0};
InitX509OptCtx(&optCtx);
int32_t ret = HITLS_APP_SUCCESS;
do {
// Init rand: Generate a serial number or signature certificate.
ret = HandleX509Opt(argc, argv, &optCtx);
if (ret != HITLS_APP_SUCCESS) {
break;
}
if (optCtx.generalOpts.req) {
if (CRYPT_EAL_ProviderRandInitCtx(NULL, CRYPT_RAND_AES128_CTR,
"provider=default", NULL, 0, NULL) != CRYPT_SUCCESS) {
ret = HITLS_APP_CRYPTO_FAIL;
break;
}
ret = GenCert(&optCtx);
} else {
ret = LoadCert(&optCtx);
}
if (ret != HITLS_APP_SUCCESS) {
break;
}
ret = X509Output(&optCtx);
} while (false);
UnInitX509OptCtx(&optCtx);
CRYPT_EAL_RandDeinitEx(NULL);
return ret;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/app_x509.c | C | unknown | 45,965 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include <stdio.h>
#include "securec.h"
#include "app_errno.h"
#include "bsl_sal.h"
#include "bsl_errno.h"
#include "app_function.h"
#include "app_print.h"
#include "app_help.h"
#include "app_provider.h"
static int AppInit(void)
{
int32_t ret = AppPrintErrorUioInit(stderr);
if (ret != HITLS_APP_SUCCESS) {
return ret;
}
return HITLS_APP_SUCCESS;
}
static void AppUninit(void)
{
AppPrintErrorUioUnInit();
return;
}
static void FreeNewArgv(char **newargv, int argc)
{
if (newargv != NULL) {
for (int i = 0; i < argc; i++) {
BSL_SAL_FREE(newargv[i]);
}
}
BSL_SAL_FREE(newargv);
}
static char **CopyArgs(int argc, char **argv, int *newArgc)
{
char **newargv = BSL_SAL_Calloc(argc + 1, sizeof(*newargv));
if (newargv == NULL) {
AppPrintError("SAL malloc failed.\n");
return NULL;
}
int i = 0;
for (i = 0; i < argc; i++) {
newargv[i] = (char *)BSL_SAL_Calloc(strlen(argv[i]) + 1, sizeof(char));
if (newargv[i] == NULL) {
AppPrintError("SAL malloc failed.\n");
goto EXIT;
}
if (strcpy_s(newargv[i], strlen(argv[i]) + 1, argv[i]) != EOK) {
AppPrintError("Failed to copy argv.\n");
goto EXIT;
}
}
newargv[i] = NULL;
*newArgc = i;
return newargv;
EXIT:
FreeNewArgv(newargv, i);
return NULL;
}
int main(int argc, char *argv[])
{
int ret = AppInit();
if (ret != HITLS_APP_SUCCESS) {
return HITLS_APP_INIT_FAILED;
}
if (argc == 1) {
AppPrintError("There is only one input parameter. Please enter help to obtain the support list.\n");
return HITLS_APP_INVALID_ARG;
}
int paramNum = argc;
char** paramVal = argv;
--paramNum;
++paramVal;
int newArgc = 0;
char **newArgv = CopyArgs(paramNum, paramVal, &newArgc);
if (newArgv == NULL) {
AppPrintError("Copy args failed.\n");
ret = HITLS_APP_COPY_ARGS_FAILED;
goto end;
}
HITLS_CmdFunc func = { 0 };
char *proName = newArgv[0];
ret = AppGetProgFunc(proName, &func);
if (ret != 0) {
AppPrintError("Please enter help to obtain the support list.\n");
FreeNewArgv(newArgv, newArgc);
goto end;
}
if (APP_GetCurrent_LibCtx() == NULL) {
if (APP_Create_LibCtx() == NULL) {
(void)AppPrintError("Create g_libCtx failed\n");
ret = HITLS_APP_INVALID_ARG;
goto end;
}
}
ret = func.main(newArgc, newArgv);
FreeNewArgv(newArgv, newArgc);
end:
HITLS_APP_FreeLibCtx(APP_GetCurrent_LibCtx());
AppUninit();
return ret;
}
| 2302_82127028/openHiTLS-examples_5062 | apps/src/hitls.c | C | unknown | 3,229 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef PRIVPASS_TOKEN_H
#define PRIVPASS_TOKEN_H
#include <stdint.h>
#include "bsl_types.h"
#include "bsl_params.h"
#include "auth_params.h"
#include "auth_privpass_token.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Constants for Private Pass Token */
#define PRIVPASS_PUBLIC_VERIFY_TOKENTYPE ((uint16_t)0x0002)
#define PRIVPASS_TOKEN_NK 256 // RSA-2048 key size in bytes
#define PRIVPASS_TOKEN_SHA256_SIZE 32 // SHA256 hash size in bytes
#define PRIVPASS_TOKEN_NONCE_LEN 32 // Random nonce length
#define PRIVPASS_MAX_ISSUER_NAME_LEN 65535
#define PRIVPASS_REDEMPTION_LEN 32
#define PRIVPASS_MAX_ORIGIN_INFO_LEN 65535
// 2(tokenType) + 32(nonce) + 32(challengeDigest) + 32(tokenKeyId)
#define HITLS_AUTH_PRIVPASS_TOKEN_INPUT_LEN (2 + 32 + 32 + 32)
/* Structure for token challenge request */
typedef struct {
uint8_t *challengeReq; // Challenge request data
uint32_t challengeReqLen; // Length of challenge request
} PrivPass_TokenChallengeReq;
/* Structure for token challenge from server */
typedef struct {
uint16_t tokenType; // Token type (e.g., Blind RSA 2048-bit)
BSL_Buffer issuerName; // Name of the token issuer
BSL_Buffer redemption; // Redemption information
BSL_Buffer originInfo; // Origin information
} PrivPass_TokenChallenge;
typedef struct {
uint16_t tokenType;
uint8_t truncatedTokenKeyId;
BSL_Buffer blindedMsg;
} PrivPass_TokenRequest;
typedef struct {
uint8_t *blindSig;
uint32_t blindSigLen;
} PrivPass_TokenPubResponse;
typedef enum {
HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB = 1,
} PrivPass_TokenResponseType;
typedef struct {
int32_t type;
union {
PrivPass_TokenPubResponse pubResp;
} st;
} PrivPass_TokenResponse;
typedef struct {
uint16_t tokenType;
uint8_t nonce[PRIVPASS_TOKEN_NONCE_LEN];
uint8_t challengeDigest[PRIVPASS_TOKEN_SHA256_SIZE];
uint8_t tokenKeyId[PRIVPASS_TOKEN_SHA256_SIZE];
BSL_Buffer authenticator;
} PrivPass_TokenInstance;
struct PrivPass_Token {
int32_t type;
union {
PrivPass_TokenChallengeReq *tokenChallengeReq;
PrivPass_TokenChallenge *tokenChallenge;
PrivPass_TokenRequest *tokenRequest;
PrivPass_TokenResponse *tokenResponse;
PrivPass_TokenInstance *token;
} st;
};
typedef struct {
HITLS_AUTH_PrivPassNewPkeyCtx newPkeyCtx;
HITLS_AUTH_PrivPassFreePkeyCtx freePkeyCtx;
HITLS_AUTH_PrivPassDigest digest;
HITLS_AUTH_PrivPassBlind blind;
HITLS_AUTH_PrivPassUnblind unBlind;
HITLS_AUTH_PrivPassSignData signData;
HITLS_AUTH_PrivPassVerify verify;
HITLS_AUTH_PrivPassDecodePubKey decodePubKey;
HITLS_AUTH_PrivPassDecodePrvKey decodePrvKey;
HITLS_AUTH_PrivPassCheckKeyPair checkKeyPair;
HITLS_AUTH_PrivPassRandom random;
} PrivPassCryptCb;
/* Main context structure for Private Pass operations */
struct PrivPass_Ctx {
void *prvKeyCtx; // Private key context
void *pubKeyCtx; // Public key context
uint8_t tokenKeyId[PRIVPASS_TOKEN_SHA256_SIZE]; // Token key identifier
uint8_t nonce[PRIVPASS_TOKEN_NONCE_LEN]; // Random nonce
PrivPassCryptCb method; // Cryptographic callbacks
};
/**
* @brief Get the default cryptographic callback functions.
* @retval PrivPassCryptCb structure containing default callbacks.
*/
PrivPassCryptCb PrivPassCryptPubCb(void);
#ifdef __cplusplus
}
#endif
#endif // PRIVPASS_TOKEN_H
| 2302_82127028/openHiTLS-examples_5062 | auth/privpass_token/include/privpass_token.h | C | unknown | 3,994 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include <stdint.h>
#include "securec.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "bsl_bytes.h"
#include "auth_errno.h"
#include "auth_params.h"
#include "auth_privpass_token.h"
#include "privpass_token.h"
#define PRIVPASS_TOKEN_MAX_ENCODE_PUBKEY_LEN 1024
static int32_t SetAndValidateTokenType(const BSL_Param *param, PrivPass_TokenChallenge *tokenChallenge)
{
const BSL_Param *temp = BSL_PARAM_FindConstParam(param, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_TYPE);
if (temp == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_TYPE);
return HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_TYPE;
}
uint32_t tokenTypeLen = (uint32_t)sizeof(tokenChallenge->tokenType);
uint16_t tokenType = 0;
int32_t ret = BSL_PARAM_GetValue(temp, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_TYPE, BSL_PARAM_TYPE_UINT16,
&tokenType, &tokenTypeLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
tokenChallenge->tokenType = tokenType;
return HITLS_AUTH_SUCCESS;
}
static int32_t SetIssuerName(const BSL_Param *param, PrivPass_TokenChallenge *tokenChallenge)
{
const BSL_Param *temp = BSL_PARAM_FindConstParam(param, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ISSUERNAME);
if (temp == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_ISSUERNAME);
return HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_ISSUERNAME;
}
if (temp->valueLen == 0 || temp->valueLen > PRIVPASS_MAX_ISSUER_NAME_LEN) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_ISSUER_NAME);
return HITLS_AUTH_PRIVPASS_INVALID_ISSUER_NAME;
}
tokenChallenge->issuerName.data = BSL_SAL_Dump(temp->value, temp->valueLen);
if (tokenChallenge->issuerName.data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenChallenge->issuerName.dataLen = temp->valueLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t SetOptionalFields(const BSL_Param *param, PrivPass_TokenChallenge *tokenChallenge)
{
// Set redemption
const BSL_Param *temp = BSL_PARAM_FindConstParam(param, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_REDEMPTION);
if (temp == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_REDEMPTION);
return HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_REDEMPTION;
}
if (temp->valueLen != 0) {
if (temp->valueLen != PRIVPASS_REDEMPTION_LEN) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_REDEMPTION);
return HITLS_AUTH_PRIVPASS_INVALID_REDEMPTION;
}
tokenChallenge->redemption.data = BSL_SAL_Dump(temp->value, temp->valueLen);
if (tokenChallenge->redemption.data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenChallenge->redemption.dataLen = temp->valueLen;
}
// Set originInfo (optional)
temp = BSL_PARAM_FindConstParam(param, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ORIGININFO);
if (temp != NULL && temp->valueLen > 0) {
if (temp->valueLen > PRIVPASS_MAX_ORIGIN_INFO_LEN) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_ORIGIN_INFO);
return HITLS_AUTH_PRIVPASS_INVALID_ORIGIN_INFO;
}
tokenChallenge->originInfo.data = BSL_SAL_Dump(temp->value, temp->valueLen);
if (tokenChallenge->originInfo.data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenChallenge->originInfo.dataLen = temp->valueLen;
}
return HITLS_AUTH_SUCCESS;
}
int32_t HITLS_AUTH_PrivPassGenTokenChallenge(HITLS_AUTH_PrivPassCtx *ctx, const BSL_Param *param,
HITLS_AUTH_PrivPassToken **challenge)
{
(void)ctx;
if (param == NULL || challenge == NULL || *challenge != NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
HITLS_AUTH_PrivPassToken *output = HITLS_AUTH_PrivPassNewToken(HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE);
if (output == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
uint64_t challengeLen;
PrivPass_TokenChallenge *tokenChallenge = output->st.tokenChallenge;
int32_t ret = SetAndValidateTokenType(param, tokenChallenge);
if (ret != HITLS_AUTH_SUCCESS) {
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
ret = SetIssuerName(param, tokenChallenge);
if (ret != HITLS_AUTH_SUCCESS) {
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
ret = SetOptionalFields(param, tokenChallenge);
if (ret != HITLS_AUTH_SUCCESS) {
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
challengeLen = sizeof(tokenChallenge->tokenType) + tokenChallenge->issuerName.dataLen +
tokenChallenge->redemption.dataLen + tokenChallenge->originInfo.dataLen;
if (challengeLen > UINT32_MAX) {
HITLS_AUTH_PrivPassFreeToken(output);
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_PARAM);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_PARAM;
}
*challenge = output;
return HITLS_AUTH_SUCCESS;
}
static int32_t ParamCheckOfGenTokenReq(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
HITLS_AUTH_PrivPassToken **tokenRequest)
{
if (ctx == NULL || ctx->method.blind == NULL || ctx->method.digest == NULL || ctx->method.random == NULL ||
tokenChallenge == NULL || tokenChallenge->type != HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE ||
tokenRequest == NULL || *tokenRequest != NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (tokenChallenge->st.tokenChallenge->tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
return HITLS_AUTH_SUCCESS;
}
static uint32_t ObtainAuthenticatorLen(uint16_t tokenType)
{
if (tokenType == PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
return (uint32_t)PRIVPASS_TOKEN_NK;
}
return 0;
}
static int32_t GenerateChallengeDigest(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
uint8_t *challengeDigest)
{
uint8_t *challenge = NULL;
uint32_t challengeLen = 0;
uint32_t challengeDigestLen = PRIVPASS_TOKEN_SHA256_SIZE;
int32_t ret = HITLS_AUTH_PrivPassSerialization(ctx, tokenChallenge, NULL, &challengeLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
challenge = BSL_SAL_Malloc(challengeLen);
if (challenge == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
ret = HITLS_AUTH_PrivPassSerialization(ctx, tokenChallenge, challenge, &challengeLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_SAL_Free(challenge);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = ctx->method.digest(NULL, NULL, HITLS_AUTH_PRIVPASS_CRYPTO_SHA256, challenge, challengeLen, challengeDigest,
&challengeDigestLen);
BSL_SAL_Free(challenge);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t HITLS_AUTH_PrivPassGenTokenReq(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
HITLS_AUTH_PrivPassToken **tokenRequest)
{
int32_t ret = ParamCheckOfGenTokenReq(ctx, tokenChallenge, tokenRequest);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
HITLS_AUTH_PrivPassToken *output = HITLS_AUTH_PrivPassNewToken(HITLS_AUTH_PRIVPASS_TOKEN_REQUEST);
if (output == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
uint8_t challengeDigest[PRIVPASS_TOKEN_SHA256_SIZE];
const PrivPass_TokenChallenge *challenge = tokenChallenge->st.tokenChallenge;
PrivPass_TokenRequest *request = output->st.tokenRequest;
uint32_t authenticatorLen = ObtainAuthenticatorLen(challenge->tokenType); // challenge->tokenType has been checked.
// Construct token_input = concat(token_type, nonce, challenge_digest, token_key_id)
uint8_t tokenInput[HITLS_AUTH_PRIVPASS_TOKEN_INPUT_LEN];
size_t offset = 0;
// Copy token type from challenge
request->tokenType = challenge->tokenType;
request->truncatedTokenKeyId = ctx->tokenKeyId[PRIVPASS_TOKEN_SHA256_SIZE - 1];
// cal tokenChallengeDigest
ret = GenerateChallengeDigest(ctx, tokenChallenge, challengeDigest);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// Generate nonce
ret = ctx->method.random(ctx->nonce, PRIVPASS_TOKEN_NONCE_LEN);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// Add token type (2 bytes)
BSL_Uint16ToByte(challenge->tokenType, tokenInput);
offset += 2; // offset 2 bytes.
// Add nonce
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_NONCE_LEN, ctx->nonce, PRIVPASS_TOKEN_NONCE_LEN);
offset += PRIVPASS_TOKEN_NONCE_LEN;
// Add challenge digest
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_SHA256_SIZE, challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Add token key id
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_SHA256_SIZE, ctx->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE);
// Calculate blinded message
request->blindedMsg.data = BSL_SAL_Malloc(authenticatorLen);
if (request->blindedMsg.data == NULL) {
ret = BSL_MALLOC_FAIL;
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
goto ERR;
}
request->blindedMsg.dataLen = authenticatorLen;
ret = ctx->method.blind(ctx->pubKeyCtx, HITLS_AUTH_PRIVPASS_CRYPTO_SHA384, tokenInput,
HITLS_AUTH_PRIVPASS_TOKEN_INPUT_LEN, request->blindedMsg.data, &request->blindedMsg.dataLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
*tokenRequest = output;
return HITLS_AUTH_SUCCESS;
ERR:
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
static int32_t ParamCheckOfGenTokenResp(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenRequest,
HITLS_AUTH_PrivPassToken **tokenResponse)
{
if (ctx == NULL || ctx->method.signData == NULL ||
tokenRequest == NULL || tokenRequest->type != HITLS_AUTH_PRIVPASS_TOKEN_REQUEST ||
tokenResponse == NULL || *tokenResponse != NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (tokenRequest->st.tokenRequest->tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
if (ctx->prvKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PRVKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PRVKEY_INFO;
}
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
return HITLS_AUTH_SUCCESS;
}
int32_t HITLS_AUTH_PrivPassGenTokenResponse(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenRequest,
HITLS_AUTH_PrivPassToken **tokenResponse)
{
int32_t ret = ParamCheckOfGenTokenResp(ctx, tokenRequest, tokenResponse);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
const PrivPass_TokenRequest *request = tokenRequest->st.tokenRequest;
uint32_t authenticatorLen = ObtainAuthenticatorLen(request->tokenType); // request->tokenType has been checked.
if (request->truncatedTokenKeyId != ctx->tokenKeyId[PRIVPASS_TOKEN_SHA256_SIZE - 1]) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_KEYID);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_KEYID;
}
if (request->blindedMsg.dataLen != authenticatorLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_BLINDED_MSG);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_BLINDED_MSG;
}
HITLS_AUTH_PrivPassToken *output = HITLS_AUTH_PrivPassNewToken(HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE);
if (output == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
PrivPass_TokenResponse *response = output->st.tokenResponse;
response->type = HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB;
// Calculate blind signature
response->st.pubResp.blindSig = BSL_SAL_Malloc(authenticatorLen);
if (response->st.pubResp.blindSig == NULL) {
ret = BSL_MALLOC_FAIL;
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
goto ERR;
}
response->st.pubResp.blindSigLen = authenticatorLen;
ret = ctx->method.signData(ctx->prvKeyCtx, request->blindedMsg.data, request->blindedMsg.dataLen,
response->st.pubResp.blindSig, &response->st.pubResp.blindSigLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
*tokenResponse = output;
return HITLS_AUTH_SUCCESS;
ERR:
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
static int32_t ParamCheckOfGenToken(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
const HITLS_AUTH_PrivPassToken *tokenResponse, HITLS_AUTH_PrivPassToken **token)
{
if (ctx == NULL || ctx->method.unBlind == NULL ||
tokenChallenge == NULL || tokenChallenge->type != HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE ||
tokenResponse == NULL || tokenResponse->type != HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE ||
token == NULL || *token != NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
if (tokenChallenge->st.tokenChallenge->tokenType == PRIVPASS_PUBLIC_VERIFY_TOKENTYPE &&
tokenResponse->st.tokenResponse->type == HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB) {
return HITLS_AUTH_SUCCESS;
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
int32_t HITLS_AUTH_PrivPassGenToken(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
const HITLS_AUTH_PrivPassToken *tokenResponse, HITLS_AUTH_PrivPassToken **token)
{
int32_t ret = ParamCheckOfGenToken(ctx, tokenChallenge, tokenResponse, token);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
HITLS_AUTH_PrivPassToken *output = HITLS_AUTH_PrivPassNewToken(HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE);
if (output == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
uint8_t challengeDigest[PRIVPASS_TOKEN_SHA256_SIZE];
PrivPass_TokenInstance *finalToken = output->st.token;
const PrivPass_TokenChallenge *challenge = tokenChallenge->st.tokenChallenge;
const PrivPass_TokenResponse *response = tokenResponse->st.tokenResponse;
uint32_t outputLen = ObtainAuthenticatorLen(challenge->tokenType);
// Copy token type from challenge
finalToken->tokenType = challenge->tokenType;
// cal tokenChallengeDigest
ret = GenerateChallengeDigest(ctx, tokenChallenge, challengeDigest);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
// Copy nonce from ctx
(void)memcpy_s(finalToken->nonce, PRIVPASS_TOKEN_NONCE_LEN, ctx->nonce, PRIVPASS_TOKEN_NONCE_LEN);
// Copy challenge digest from ctx
(void)memcpy_s(finalToken->challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE,
challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE);
// Copy token key ID from ctx
(void)memcpy_s(finalToken->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE, ctx->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE);
// Copy authenticator from tokenResponse
finalToken->authenticator.data = BSL_SAL_Malloc(outputLen);
if (finalToken->authenticator.data == NULL) {
ret = BSL_MALLOC_FAIL;
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
goto ERR;
}
ret = ctx->method.unBlind(ctx->pubKeyCtx, response->st.pubResp.blindSig, response->st.pubResp.blindSigLen,
finalToken->authenticator.data, &outputLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
finalToken->authenticator.dataLen = outputLen;
*token = output;
return HITLS_AUTH_SUCCESS;
ERR:
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
static int32_t ParamCheckOfVerifyToken(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
const HITLS_AUTH_PrivPassToken *token)
{
if (ctx == NULL || ctx->method.verify == NULL ||
tokenChallenge == NULL || tokenChallenge->type != HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE ||
token == NULL || token->type != HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (tokenChallenge->st.tokenChallenge->tokenType != token->st.token->tokenType) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (tokenChallenge->st.tokenChallenge->tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
PrivPass_TokenInstance *finalToken = token->st.token;
if (memcmp(finalToken->tokenKeyId, ctx->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE) != 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_KEYID);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_KEYID;
}
uint8_t challengeDigest[PRIVPASS_TOKEN_SHA256_SIZE];
int32_t ret = GenerateChallengeDigest(ctx, tokenChallenge, challengeDigest);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (memcmp(finalToken->challengeDigest, challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE) != 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_DIGEST);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_DIGEST;
}
return HITLS_AUTH_SUCCESS;
}
int32_t HITLS_AUTH_PrivPassVerifyToken(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *tokenChallenge,
const HITLS_AUTH_PrivPassToken *token)
{
int32_t ret = ParamCheckOfVerifyToken(ctx, tokenChallenge, token);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
PrivPass_TokenInstance *finalToken = token->st.token;
uint32_t authenticatorLen = ObtainAuthenticatorLen(finalToken->tokenType);
if (finalToken->authenticator.data == NULL || authenticatorLen != finalToken->authenticator.dataLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_INSTANCE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_INSTANCE;
}
// Construct token_input = concat(token_type, nonce, challenge_digest, token_key_id)
uint8_t tokenInput[HITLS_AUTH_PRIVPASS_TOKEN_INPUT_LEN];
size_t offset = 0;
// Add token type (2 bytes)
BSL_Uint16ToByte(finalToken->tokenType, tokenInput);
offset += 2; // offset 2 bytes.
// Add nonce
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_NONCE_LEN, finalToken->nonce, PRIVPASS_TOKEN_NONCE_LEN);
offset += PRIVPASS_TOKEN_NONCE_LEN;
// Add challenge digest
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_SHA256_SIZE,
finalToken->challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Add token key id
(void)memcpy_s(tokenInput + offset, PRIVPASS_TOKEN_SHA256_SIZE, finalToken->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE);
// Verify the token using ctx's verify method
ret = ctx->method.verify(ctx->pubKeyCtx, HITLS_AUTH_PRIVPASS_CRYPTO_SHA384, tokenInput,
HITLS_AUTH_PRIVPASS_TOKEN_INPUT_LEN, finalToken->authenticator.data, PRIVPASS_TOKEN_NK);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t HITLS_AUTH_PrivPassSetPubkey(HITLS_AUTH_PrivPassCtx *ctx, uint8_t *pki, uint32_t pkiLen)
{
if (ctx == NULL || ctx->method.decodePubKey == NULL || ctx->method.freePkeyCtx == NULL ||
ctx->method.digest == NULL || pki == NULL || pkiLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
uint32_t tokenKeyIdLen = PRIVPASS_TOKEN_SHA256_SIZE;
void *pubKeyCtx = NULL;
int32_t ret = ctx->method.decodePubKey(NULL, NULL, pki, pkiLen, &pubKeyCtx);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (ctx->prvKeyCtx != NULL) {
if (ctx->method.checkKeyPair == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_KEYPAIR_CHECK_CALLBACK);
ret = HITLS_AUTH_PRIVPASS_NO_KEYPAIR_CHECK_CALLBACK;
goto ERR;
}
ret = ctx->method.checkKeyPair(pubKeyCtx, ctx->prvKeyCtx);
if (ret != HITLS_AUTH_SUCCESS) {
ret = HITLS_AUTH_PRIVPASS_CHECK_KEYPAIR_FAILED;
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_CHECK_KEYPAIR_FAILED);
goto ERR;
}
}
ret = ctx->method.digest(NULL, NULL, HITLS_AUTH_PRIVPASS_CRYPTO_SHA256, pki, pkiLen, ctx->tokenKeyId,
&tokenKeyIdLen);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto ERR;
}
if (ctx->pubKeyCtx != NULL) {
ctx->method.freePkeyCtx(ctx->pubKeyCtx);
}
ctx->pubKeyCtx = pubKeyCtx;
return HITLS_AUTH_SUCCESS;
ERR:
ctx->method.freePkeyCtx(pubKeyCtx);
return ret;
}
int32_t HITLS_AUTH_PrivPassSetPrvkey(HITLS_AUTH_PrivPassCtx *ctx, void *param, uint8_t *ski, uint32_t skiLen)
{
if (ctx == NULL || ctx->method.decodePrvKey == NULL || ctx->method.freePkeyCtx == NULL ||
ski == NULL || skiLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
void *prvKeyCtx = NULL;
int32_t ret = ctx->method.decodePrvKey(NULL, NULL, param, ski, skiLen, &prvKeyCtx);
if (ret != HITLS_AUTH_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (ctx->pubKeyCtx != NULL) {
if (ctx->method.checkKeyPair == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_KEYPAIR_CHECK_CALLBACK);
ret = HITLS_AUTH_PRIVPASS_NO_KEYPAIR_CHECK_CALLBACK;
goto ERR;
}
ret = ctx->method.checkKeyPair(ctx->pubKeyCtx, prvKeyCtx);
if (ret != HITLS_AUTH_SUCCESS) {
ret = HITLS_AUTH_PRIVPASS_CHECK_KEYPAIR_FAILED;
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_CHECK_KEYPAIR_FAILED);
goto ERR;
}
}
if (ctx->prvKeyCtx != NULL) {
ctx->method.freePkeyCtx(ctx->prvKeyCtx);
}
ctx->prvKeyCtx = prvKeyCtx;
return HITLS_AUTH_SUCCESS;
ERR:
ctx->method.freePkeyCtx(prvKeyCtx);
return ret;
}
| 2302_82127028/openHiTLS-examples_5062 | auth/privpass_token/src/privpass_token.c | C | unknown | 24,225 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include <stdint.h>
#include "securec.h"
#include "bsl_errno.h"
#include "auth_errno.h"
#include "auth_privpass_token.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "bsl_bytes.h"
#include "privpass_token.h"
static int32_t DecodeTokenChallengeReq(PrivPass_TokenChallengeReq *tokenChallengeReq, const uint8_t *buffer,
uint32_t buffLen)
{
// Allocate memory for the new buffer
uint8_t *data = (uint8_t *)BSL_SAL_Dump(buffer, buffLen);
if (data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenChallengeReq->challengeReq = data;
tokenChallengeReq->challengeReqLen = buffLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t EncodeTokenChallengeReq(const PrivPass_TokenChallengeReq *tokenChallengeReq, uint8_t *buffer,
uint32_t *buffLen)
{
if (tokenChallengeReq->challengeReqLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_REQ);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE_REQ;
}
if (buffer == NULL) {
*buffLen = tokenChallengeReq->challengeReqLen;
return HITLS_AUTH_SUCCESS;
}
if (*buffLen < tokenChallengeReq->challengeReqLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(buffer, tokenChallengeReq->challengeReqLen, tokenChallengeReq->challengeReq,
tokenChallengeReq->challengeReqLen);
*buffLen = tokenChallengeReq->challengeReqLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t ValidateInitialParams(uint32_t remainLen)
{
// MinLength: tokenType(2) + issuerNameLen(2) + redemptionLen(1) + originInfoLen(2)
if (remainLen < 2 + 2 + 1 + 2) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeTokenTypeAndValidate(uint16_t *tokenType, const uint8_t **curr, uint32_t *remainLen)
{
*tokenType = BSL_ByteToUint16(*curr);
if (*tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
*curr += 2; // offset 2 bytes.
*remainLen -= 2;
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeIssuerName(uint8_t **issueName, uint32_t *issuerNameLen, const uint8_t **curr, uint32_t *remainLen)
{
*issuerNameLen = (uint32_t)BSL_ByteToUint16(*curr);
*curr += 2; // offset 2 bytes.
*remainLen -= 2;
if (*issuerNameLen == 0 || *remainLen < *issuerNameLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
*issueName = BSL_SAL_Dump(*curr, *issuerNameLen);
if (*issueName == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
*curr += *issuerNameLen;
*remainLen -= *issuerNameLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeRedemption(uint8_t **redemption, uint32_t *redemptionLen, const uint8_t **curr,
uint32_t *remainLen)
{
if (*remainLen < 1) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
*redemptionLen = (uint32_t)**curr;
*curr += 1;
*remainLen -= 1;
if (*remainLen < *redemptionLen || (*redemptionLen != PRIVPASS_REDEMPTION_LEN && *redemptionLen != 0)) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
if (*redemptionLen != 0) {
*redemption = BSL_SAL_Dump(*curr, *redemptionLen);
if (*redemption == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
*curr += *redemptionLen;
*remainLen -= *redemptionLen;
}
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeOriginInfo(uint8_t **originInfo, uint32_t *originInfoLen, const uint8_t **curr,
uint32_t *remainLen)
{
if (*remainLen < 2) { // len needs 2 bytes to store.
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
*originInfoLen = (uint32_t)BSL_ByteToUint16(*curr);
*curr += 2; // offset 2 bytes.
*remainLen -= 2;
if (*remainLen != *originInfoLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
if (*originInfoLen > 0) {
*originInfo = BSL_SAL_Dump(*curr, *originInfoLen);
if (*originInfo == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
}
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeTokenChallenge(PrivPass_TokenChallenge *challenge, const uint8_t *buffer, uint32_t buffLen)
{
int32_t ret = ValidateInitialParams(buffLen);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
const uint8_t *curr = buffer;
uint32_t remainLen = buffLen;
// Decode each component
ret = DecodeTokenTypeAndValidate(&challenge->tokenType, &curr, &remainLen);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
ret = DecodeIssuerName(&challenge->issuerName.data, &challenge->issuerName.dataLen, &curr, &remainLen);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
ret = DecodeRedemption(&challenge->redemption.data, &challenge->redemption.dataLen, &curr, &remainLen);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
return DecodeOriginInfo(&challenge->originInfo.data, &challenge->originInfo.dataLen, &curr, &remainLen);
}
static int32_t CheckTokenChallengeParam(const PrivPass_TokenChallenge *challenge)
{
if (challenge->issuerName.dataLen == 0 || challenge->issuerName.dataLen > PRIVPASS_MAX_ISSUER_NAME_LEN ||
challenge->originInfo.dataLen > PRIVPASS_MAX_ORIGIN_INFO_LEN ||
(challenge->redemption.dataLen != 0 && challenge->redemption.dataLen != PRIVPASS_REDEMPTION_LEN)) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
return HITLS_AUTH_SUCCESS;
}
static int32_t EncodeTokenChallenge(const PrivPass_TokenChallenge *challenge,
uint8_t *buffer, uint32_t *outBuffLen)
{
int32_t ret = CheckTokenChallengeParam(challenge);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
// 2(tokenType) + 2(issuerNameLen) + issuerName + 1(redemptionLen) + redemption + 2(originInfoLen) + originInfo
uint64_t totalLen = 2 + 2 + challenge->issuerName.dataLen + 1 + challenge->redemption.dataLen + 2 +
(uint64_t)challenge->originInfo.dataLen;
if (totalLen > UINT32_MAX) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_CHALLENGE;
}
if (buffer == NULL) {
*outBuffLen = (uint32_t)totalLen;
return HITLS_AUTH_SUCCESS;
}
if (*outBuffLen < (uint32_t)totalLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
uint8_t *curr = buffer;
BSL_Uint16ToByte(challenge->tokenType, curr); // Write tokenType (2 bytes)
BSL_Uint16ToByte((uint16_t)challenge->issuerName.dataLen, curr + 2); // Write IssuerName length (2 bytes) and data
curr += 4; // offset 4 bytes.
if (challenge->issuerName.dataLen > 0 && challenge->issuerName.data != NULL) {
(void)memcpy_s(curr, challenge->issuerName.dataLen, challenge->issuerName.data,
challenge->issuerName.dataLen);
curr += challenge->issuerName.dataLen;
}
// Write redemptionContext (1 byte)
*curr++ = (uint8_t)challenge->redemption.dataLen;
if (challenge->redemption.dataLen > 0 && challenge->redemption.data != NULL) {
(void)memcpy_s(curr, challenge->redemption.dataLen, challenge->redemption.data,
challenge->redemption.dataLen);
curr += challenge->redemption.dataLen;
}
// Write originInfo length (2 bytes) and data
BSL_Uint16ToByte((uint16_t)challenge->originInfo.dataLen, curr);
curr += 2; // offset 2 bytes.
if (challenge->originInfo.dataLen > 0 && challenge->originInfo.data != NULL) {
(void)memcpy_s(curr, challenge->originInfo.dataLen, challenge->originInfo.data,
challenge->originInfo.dataLen);
}
*outBuffLen = (uint32_t)totalLen;
return HITLS_AUTH_SUCCESS;
}
static uint32_t ObtainAuthenticatorLen(uint16_t tokenType)
{
if (tokenType == PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
return (uint32_t)PRIVPASS_TOKEN_NK;
}
return 0;
}
static int32_t DecodeTokenRequest(PrivPass_TokenRequest *tokenRequest, const uint8_t *buffer, uint32_t buffLen)
{
// Check minimum length for tokenType (2 bytes)
if (buffLen < 2) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
// Decode and verify tokenType first (2 bytes, network byte order)
uint16_t tokenType = BSL_ByteToUint16(buffer);
if (tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_REQUEST);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_REQUEST;
}
uint32_t blindedMsgLen = ObtainAuthenticatorLen(tokenType);
// Now check the complete buffer length: 2(tokenType) + 1(truncatedTokenKeyId) + blindedMsgLen
if (buffLen != (2 + 1 + blindedMsgLen)) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
int32_t offset = 2; // Skip tokenType which we've already processed
// Decode truncatedTokenKeyId (1 byte)
uint8_t truncatedTokenKeyId = buffer[offset++];
// Decode blindedMsg
uint8_t *blindedMsg = (uint8_t *)BSL_SAL_Dump(buffer + offset, blindedMsgLen);
if (blindedMsg == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenRequest->tokenType = tokenType;
tokenRequest->blindedMsg.data = blindedMsg;
tokenRequest->blindedMsg.dataLen = blindedMsgLen;
tokenRequest->truncatedTokenKeyId = truncatedTokenKeyId;
return HITLS_AUTH_SUCCESS;
}
static int32_t CheckTokenRequest(const PrivPass_TokenRequest *request)
{
if (request->tokenType == PRIVPASS_PUBLIC_VERIFY_TOKENTYPE &&
(request->blindedMsg.data != NULL && request->blindedMsg.dataLen == PRIVPASS_TOKEN_NK)) {
return HITLS_AUTH_SUCCESS;
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_REQUEST);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_REQUEST;
}
static int32_t EncodeTokenRequest(const PrivPass_TokenRequest *request, uint8_t *buffer, uint32_t *outBuffLen)
{
// Verify tokenType
int32_t ret = CheckTokenRequest(request);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
uint32_t authenticatorLen = ObtainAuthenticatorLen(request->tokenType);
// Calculate total length: 2(tokenType) + 1(truncatedTokenKeyId) + (blindedMsg)
uint32_t totalLen = 2 + 1 + authenticatorLen;
if (buffer == NULL) {
*outBuffLen = totalLen;
return HITLS_AUTH_SUCCESS;
}
if (*outBuffLen < totalLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
// Encode data
int32_t offset = 0;
// Encode tokenType (2 bytes, network byte order)
BSL_Uint16ToByte(request->tokenType, buffer);
offset += 2; // offset 2 bytes.
// Encode truncatedTokenKeyId (1 byte)
buffer[offset++] = request->truncatedTokenKeyId;
// Encode blindedMsg
(void)memcpy_s(buffer + offset, authenticatorLen, request->blindedMsg.data, authenticatorLen);
*outBuffLen = totalLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodePubTokenResp(PrivPass_TokenResponse *tokenResp, const uint8_t *buffer, uint32_t buffLen)
{
// Allocate memory for the new buffer
tokenResp->st.pubResp.blindSig = (uint8_t *)BSL_SAL_Dump(buffer, buffLen);
if (tokenResp->st.pubResp.blindSig == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
tokenResp->st.pubResp.blindSigLen = buffLen;
tokenResp->type = HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB;
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeTokenResp(PrivPass_TokenResponse *tokenResp, const uint8_t *buffer, uint32_t buffLen)
{
if (buffLen == PRIVPASS_TOKEN_NK) {
return DecodePubTokenResp(tokenResp, buffer, buffLen);
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
static int32_t EncodeTokenPubResp(const PrivPass_TokenPubResponse *resp, uint8_t *buffer, uint32_t *buffLen)
{
if (resp->blindSig == NULL || resp->blindSigLen != PRIVPASS_TOKEN_NK) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_RESPONSE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_RESPONSE;
}
if (buffer == NULL) {
*buffLen = resp->blindSigLen;
return HITLS_AUTH_SUCCESS;
}
// Check buffer length
if (*buffLen < resp->blindSigLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
// Copy token data to buffer
(void)memcpy_s(buffer, resp->blindSigLen, resp->blindSig, resp->blindSigLen);
*buffLen = resp->blindSigLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t EncodeTokenResp(const PrivPass_TokenResponse *resp, uint8_t *buffer, uint32_t *buffLen)
{
if (resp->type == HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB) {
return EncodeTokenPubResp(&resp->st.pubResp, buffer, buffLen);
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_RESPONSE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_RESPONSE;
}
static int32_t CheckToken(const PrivPass_TokenInstance *token)
{
if (token->tokenType == PRIVPASS_PUBLIC_VERIFY_TOKENTYPE &&
(token->authenticator.data != NULL && token->authenticator.dataLen == PRIVPASS_TOKEN_NK)) {
return HITLS_AUTH_SUCCESS;
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_INSTANCE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_INSTANCE;
}
static int32_t EncodeToken(const PrivPass_TokenInstance *token, uint8_t *buffer, uint32_t *outBuffLen)
{
// Verify tokenType
int32_t ret = CheckToken(token);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
// Calculate total length: 2(tokenType) + 32(nonce) + 32(challengeDigest) + 32(tokenKeyId) + authenticatorLen
uint32_t totalLen = 2 + PRIVPASS_TOKEN_NONCE_LEN + PRIVPASS_TOKEN_SHA256_SIZE + PRIVPASS_TOKEN_SHA256_SIZE +
token->authenticator.dataLen;
if (buffer == NULL) {
*outBuffLen = totalLen;
return HITLS_AUTH_SUCCESS;
}
if (*outBuffLen < totalLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
int32_t offset = 0;
// Encode tokenType (network byte order)
BSL_Uint16ToByte(token->tokenType, buffer);
offset += 2; // offset 2 bytes.
// Encode nonce
(void)memcpy_s(buffer + offset, PRIVPASS_TOKEN_NONCE_LEN, token->nonce, PRIVPASS_TOKEN_NONCE_LEN);
offset += PRIVPASS_TOKEN_NONCE_LEN;
// Encode challengeDigest
(void)memcpy_s(buffer + offset, PRIVPASS_TOKEN_SHA256_SIZE, token->challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Encode tokenKeyId
(void)memcpy_s(buffer + offset, PRIVPASS_TOKEN_SHA256_SIZE, token->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Encode authenticator
(void)memcpy_s(buffer + offset, token->authenticator.dataLen, token->authenticator.data,
token->authenticator.dataLen);
*outBuffLen = totalLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t DecodeToken(PrivPass_TokenInstance *token, const uint8_t *buffer, uint32_t buffLen)
{
// First check if there are enough bytes to read tokenType(2 bytes).
if (buffLen < 2) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
// Decode and verify tokenType first (network byte order)
uint16_t tokenType = BSL_ByteToUint16(buffer);
if (tokenType != PRIVPASS_PUBLIC_VERIFY_TOKENTYPE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
token->tokenType = tokenType;
uint32_t authenticatorLen = ObtainAuthenticatorLen(tokenType);
// Calculate total length: 2(tokenType) + 32(nonce) + 32(challengeDigest) + 32(tokenKeyId) + authenticatorLen
if (buffLen != (2 + PRIVPASS_TOKEN_NONCE_LEN + PRIVPASS_TOKEN_SHA256_SIZE + PRIVPASS_TOKEN_SHA256_SIZE +
authenticatorLen)) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
int32_t offset = 2; // Skip tokenType which we've already read
// Decode nonce
(void)memcpy_s(token->nonce, PRIVPASS_TOKEN_NONCE_LEN, buffer + offset, PRIVPASS_TOKEN_NONCE_LEN);
offset += PRIVPASS_TOKEN_NONCE_LEN;
// Decode challengeDigest
(void)memcpy_s(token->challengeDigest, PRIVPASS_TOKEN_SHA256_SIZE, buffer + offset, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Decode tokenKeyId
(void)memcpy_s(token->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE, buffer + offset, PRIVPASS_TOKEN_SHA256_SIZE);
offset += PRIVPASS_TOKEN_SHA256_SIZE;
// Decode authenticator
token->authenticator.data = (uint8_t *)BSL_SAL_Dump(buffer + offset, authenticatorLen);
if (token->authenticator.data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_DUMP_FAIL);
return BSL_DUMP_FAIL;
}
token->authenticator.dataLen = authenticatorLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t CheckDeserializationInput(int32_t tokenType, const uint8_t *buffer, uint32_t buffLen,
HITLS_AUTH_PrivPassToken **object)
{
if (buffer == NULL || buffLen == 0 || object == NULL || *object != NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
switch (tokenType) {
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST:
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE:
case HITLS_AUTH_PRIVPASS_TOKEN_REQUEST:
case HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE:
case HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE:
return HITLS_AUTH_SUCCESS;
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
}
int32_t HITLS_AUTH_PrivPassDeserialization(HITLS_AUTH_PrivPassCtx *ctx, int32_t tokenType, const uint8_t *buffer,
uint32_t buffLen, HITLS_AUTH_PrivPassToken **object)
{
(void)ctx;
int32_t ret = CheckDeserializationInput(tokenType, buffer, buffLen, object);
if (ret != HITLS_AUTH_SUCCESS) {
return ret;
}
// Allocate the token object
HITLS_AUTH_PrivPassToken *output = HITLS_AUTH_PrivPassNewToken(tokenType);
if (output == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
switch (tokenType) {
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST:
ret = DecodeTokenChallengeReq(output->st.tokenChallengeReq, buffer, buffLen);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE:
ret = DecodeTokenChallenge(output->st.tokenChallenge, buffer, buffLen);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_REQUEST:
ret = DecodeTokenRequest(output->st.tokenRequest, buffer, buffLen);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE:
ret = DecodeTokenResp(output->st.tokenResponse, buffer, buffLen);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE:
ret = DecodeToken(output->st.token, buffer, buffLen);
break;
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
ret = HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
break;
}
if (ret != HITLS_AUTH_SUCCESS) {
HITLS_AUTH_PrivPassFreeToken(output);
return ret;
}
*object = output;
return HITLS_AUTH_SUCCESS;
}
int32_t HITLS_AUTH_PrivPassSerialization(HITLS_AUTH_PrivPassCtx *ctx, const HITLS_AUTH_PrivPassToken *object,
uint8_t *buffer, uint32_t *outBuffLen)
{
(void)ctx;
if (object == NULL || outBuffLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
switch (object->type) {
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST:
return EncodeTokenChallengeReq(object->st.tokenChallengeReq, buffer, outBuffLen);
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE:
return EncodeTokenChallenge(object->st.tokenChallenge, buffer, outBuffLen);
case HITLS_AUTH_PRIVPASS_TOKEN_REQUEST:
return EncodeTokenRequest(object->st.tokenRequest, buffer, outBuffLen);
case HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE:
return EncodeTokenResp(object->st.tokenResponse, buffer, outBuffLen);
case HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE:
return EncodeToken(object->st.token, buffer, outBuffLen);
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE;
}
}
HITLS_AUTH_PrivPassToken *HITLS_AUTH_PrivPassNewToken(int32_t tokenType)
{
HITLS_AUTH_PrivPassToken *object = (HITLS_AUTH_PrivPassToken *)BSL_SAL_Calloc(1u, sizeof(HITLS_AUTH_PrivPassToken));
if (object == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
switch (tokenType) {
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST:
object->st.tokenChallengeReq = (PrivPass_TokenChallengeReq *)BSL_SAL_Calloc(1u,
sizeof(PrivPass_TokenChallengeReq));
if (object->st.tokenChallengeReq == NULL) {
goto ERR;
}
break;
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE:
object->st.tokenChallenge = (PrivPass_TokenChallenge *)BSL_SAL_Calloc(1u, sizeof(PrivPass_TokenChallenge));
if (object->st.tokenChallenge == NULL) {
goto ERR;
}
break;
case HITLS_AUTH_PRIVPASS_TOKEN_REQUEST:
object->st.tokenRequest = (PrivPass_TokenRequest *)BSL_SAL_Calloc(1u, sizeof(PrivPass_TokenRequest));
if (object->st.tokenRequest == NULL) {
goto ERR;
}
break;
case HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE:
object->st.tokenResponse = (PrivPass_TokenResponse *)BSL_SAL_Calloc(1u, sizeof(PrivPass_TokenResponse));
if (object->st.tokenResponse == NULL) {
goto ERR;
}
break;
case HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE:
object->st.token = (PrivPass_TokenInstance *)BSL_SAL_Calloc(1u, sizeof(PrivPass_TokenInstance));
if (object->st.token == NULL) {
goto ERR;
}
break;
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOKEN_TYPE);
BSL_SAL_Free(object);
return NULL;
}
object->type = tokenType;
return object;
ERR:
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
BSL_SAL_Free(object);
return NULL;
}
static void FreeTokenChallengeReq(PrivPass_TokenChallengeReq *challengeReq)
{
if (challengeReq == NULL) {
return;
}
BSL_SAL_FREE(challengeReq->challengeReq);
BSL_SAL_Free(challengeReq);
}
static void FreeTokenChallenge(PrivPass_TokenChallenge *challenge)
{
if (challenge == NULL) {
return;
}
BSL_SAL_FREE(challenge->issuerName.data);
BSL_SAL_FREE(challenge->originInfo.data);
BSL_SAL_FREE(challenge->redemption.data);
BSL_SAL_Free(challenge);
}
static void FreeTokenResponse(PrivPass_TokenResponse *response)
{
if (response == NULL) {
return;
}
if (response->type == HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE_PUB) {
BSL_SAL_FREE(response->st.pubResp.blindSig);
}
BSL_SAL_Free(response);
}
static void FreeTokenRequest(PrivPass_TokenRequest *request)
{
if (request == NULL) {
return;
}
BSL_SAL_FREE(request->blindedMsg.data);
BSL_SAL_Free(request);
}
static void FreeToken(PrivPass_TokenInstance *token)
{
if (token == NULL) {
return;
}
BSL_SAL_FREE(token->authenticator.data);
BSL_SAL_Free(token);
}
void HITLS_AUTH_PrivPassFreeToken(HITLS_AUTH_PrivPassToken *object)
{
if (object == NULL) {
return;
}
switch (object->type) {
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST:
FreeTokenChallengeReq(object->st.tokenChallengeReq);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE:
FreeTokenChallenge(object->st.tokenChallenge);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_REQUEST:
FreeTokenRequest(object->st.tokenRequest);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE:
FreeTokenResponse(object->st.tokenResponse);
break;
case HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE:
FreeToken(object->st.token);
break;
default:
break;
}
BSL_SAL_Free(object);
}
HITLS_AUTH_PrivPassCtx *HITLS_AUTH_PrivPassNewCtx(int32_t protocolType)
{
if (protocolType != HITLS_AUTH_PRIVPASS_PUB_VERIFY_TOKENS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_TOEKN_PROTOCOL_TYPE);
return NULL;
}
HITLS_AUTH_PrivPassCtx *ctx = (HITLS_AUTH_PrivPassCtx *)BSL_SAL_Calloc(1u, sizeof(HITLS_AUTH_PrivPassCtx));
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
ctx->method = PrivPassCryptPubCb();
return ctx;
}
void HITLS_AUTH_PrivPassFreeCtx(HITLS_AUTH_PrivPassCtx *ctx)
{
if (ctx == NULL) {
return;
}
if (ctx->method.freePkeyCtx != NULL) {
if (ctx->prvKeyCtx != NULL) {
ctx->method.freePkeyCtx(ctx->prvKeyCtx);
}
if (ctx->pubKeyCtx != NULL) {
ctx->method.freePkeyCtx(ctx->pubKeyCtx);
}
}
BSL_SAL_Free(ctx);
}
int32_t HITLS_AUTH_PrivPassSetCryptCb(HITLS_AUTH_PrivPassCtx *ctx, int32_t cbType, void *cryptCb)
{
if (ctx == NULL || cryptCb == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
switch (cbType) {
case HITLS_AUTH_PRIVPASS_NEW_PKEY_CTX_CB:
ctx->method.newPkeyCtx = (HITLS_AUTH_PrivPassNewPkeyCtx)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_FREE_PKEY_CTX_CB:
ctx->method.freePkeyCtx = (HITLS_AUTH_PrivPassFreePkeyCtx)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_DIGEST_CB:
ctx->method.digest = (HITLS_AUTH_PrivPassDigest)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_BLIND_CB:
ctx->method.blind = (HITLS_AUTH_PrivPassBlind)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_UNBLIND_CB:
ctx->method.unBlind = (HITLS_AUTH_PrivPassUnblind)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_SIGNDATA_CB:
ctx->method.signData = (HITLS_AUTH_PrivPassSignData)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_VERIFY_CB:
ctx->method.verify = (HITLS_AUTH_PrivPassVerify)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_DECODE_PUBKEY_CB:
ctx->method.decodePubKey = (HITLS_AUTH_PrivPassDecodePubKey)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_DECODE_PRVKEY_CB:
ctx->method.decodePrvKey = (HITLS_AUTH_PrivPassDecodePrvKey)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_CHECK_KEYPAIR_CB:
ctx->method.checkKeyPair = (HITLS_AUTH_PrivPassCheckKeyPair)cryptCb;
break;
case HITLS_AUTH_PRIVPASS_RANDOM_CB:
ctx->method.random = (HITLS_AUTH_PrivPassRandom)cryptCb;
break;
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_CRYPTO_CALLBACK_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_CRYPTO_CALLBACK_TYPE;
}
return HITLS_AUTH_SUCCESS;
}
static int32_t PrivPassGetTokenChallengeRequest(HITLS_AUTH_PrivPassToken *ctx, BSL_Param *param)
{
if (param == NULL || ctx->type != HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE_REQUEST ||
ctx->st.tokenChallengeReq == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (ctx->st.tokenChallengeReq->challengeReq == NULL || ctx->st.tokenChallengeReq->challengeReqLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_REQUEST);
return HITLS_AUTH_PRIVPASS_NO_TOKEN_CHALLENGE_REQUEST;
}
BSL_Param *output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_REQUEST);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < ctx->st.tokenChallengeReq->challengeReqLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
(void)memcpy_s(output->value, output->valueLen, ctx->st.tokenChallengeReq->challengeReq,
ctx->st.tokenChallengeReq->challengeReqLen);
output->useLen = ctx->st.tokenChallengeReq->challengeReqLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t GetTokenChallengeContent(PrivPass_TokenChallenge *challenge, BSL_Param *param, int32_t target,
uint8_t *targetBuff, uint32_t targetLen)
{
BSL_Param *output = BSL_PARAM_FindParam(param, target);
if (target == AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_TYPE) {
if (output != NULL && output->valueType == BSL_PARAM_TYPE_UINT16) {
return BSL_PARAM_SetValue(output, target, BSL_PARAM_TYPE_UINT16, &challenge->tokenType, targetLen);
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < targetLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, targetBuff, targetLen);
output->useLen = targetLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t PrivPassGetTokenChallengeContent(HITLS_AUTH_PrivPassToken *obj, int32_t cmd, BSL_Param *param)
{
if (param == NULL || obj->type != HITLS_AUTH_PRIVPASS_TOKEN_CHALLENGE || obj->st.tokenChallenge == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
PrivPass_TokenChallenge *challenge = obj->st.tokenChallenge;
int32_t target = 0;
uint8_t *targetBuff = 0;
uint32_t targetLen = 0;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_TYPE:
target = AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_TYPE;
targetLen = (uint32_t)sizeof(challenge->tokenType);
break;
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_ISSUERNAME:
if (challenge->issuerName.data == NULL || challenge->issuerName.dataLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_ISSUERNAME);
return HITLS_AUTH_PRIVPASS_NO_ISSUERNAME;
}
target = AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ISSUERNAME;
targetBuff = challenge->issuerName.data;
targetLen = challenge->issuerName.dataLen;
break;
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_REDEMPTION:
target = AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_REDEMPTION;
targetBuff = challenge->redemption.data; // the redemption can be null
targetLen = challenge->redemption.dataLen;
break;
default:
target = AUTH_PARAM_PRIVPASS_TOKENCHALLENGE_ORIGININFO;
targetBuff = challenge->originInfo.data; // the originInfo can be null
targetLen = challenge->originInfo.dataLen;
break;
}
return GetTokenChallengeContent(challenge, param, target, targetBuff, targetLen);
}
static int32_t PrivPassGetTokenRequestContent(HITLS_AUTH_PrivPassToken *obj, int32_t cmd, BSL_Param *param)
{
if (param == NULL || obj->type != HITLS_AUTH_PRIVPASS_TOKEN_REQUEST || obj->st.tokenRequest == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
PrivPass_TokenRequest *request = obj->st.tokenRequest;
BSL_Param *output = NULL;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_TOKENREQUEST_TYPE:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_TOKENREQUEST_TYPE);
if (output != NULL && output->valueType == BSL_PARAM_TYPE_UINT16) {
return BSL_PARAM_SetValue(output, AUTH_PARAM_PRIVPASS_TOKENREQUEST_TYPE, BSL_PARAM_TYPE_UINT16,
&request->tokenType, (uint32_t)sizeof(request->tokenType));
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
case HITLS_AUTH_PRIVPASS_GET_TOKENREQUEST_TRUNCATEDTOKENKEYID:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_TOKENREQUEST_TRUNCATEDTOKENKEYID);
if (output != NULL && output->valueType == BSL_PARAM_TYPE_UINT8) {
return BSL_PARAM_SetValue(output, AUTH_PARAM_PRIVPASS_TOKENREQUEST_TRUNCATEDTOKENKEYID,
BSL_PARAM_TYPE_UINT8, &request->truncatedTokenKeyId, 1); // 1 byte.
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
default:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_TOKENREQUEST_BLINDEDMSG);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (request->blindedMsg.data == NULL || request->blindedMsg.dataLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_BLINDEDMSG);
return HITLS_AUTH_PRIVPASS_NO_BLINDEDMSG;
}
if (output->valueLen < request->blindedMsg.dataLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, request->blindedMsg.data, request->blindedMsg.dataLen);
output->useLen = request->blindedMsg.dataLen;
return HITLS_AUTH_SUCCESS;
}
}
static int32_t PrivPassGetTokenResponseContent(HITLS_AUTH_PrivPassToken *ctx, BSL_Param *param)
{
if (param == NULL || ctx->type != HITLS_AUTH_PRIVPASS_TOKEN_RESPONSE || ctx->st.tokenResponse == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (ctx->st.tokenResponse->st.pubResp.blindSig == NULL || ctx->st.tokenResponse->st.pubResp.blindSigLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_RESPONSE_INFO);
return HITLS_AUTH_PRIVPASS_NO_RESPONSE_INFO;
}
BSL_Param *output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_TOKENRESPONSE_INFO);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < ctx->st.tokenResponse->st.pubResp.blindSigLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, ctx->st.tokenResponse->st.pubResp.blindSig,
ctx->st.tokenResponse->st.pubResp.blindSigLen);
output->useLen = ctx->st.tokenResponse->st.pubResp.blindSigLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t CopyTokenContent(PrivPass_TokenInstance *token, BSL_Param *param, int32_t target, uint8_t *targetBuff,
uint32_t targetLen)
{
BSL_Param *output = BSL_PARAM_FindParam(param, target);
if (target == AUTH_PARAM_PRIVPASS_TOKEN_TYPE) {
if (output != NULL && output->valueType == BSL_PARAM_TYPE_UINT16) {
return BSL_PARAM_SetValue(output, target, BSL_PARAM_TYPE_UINT16, &token->tokenType,
(uint32_t)sizeof(token->tokenType));
}
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (target == AUTH_PARAM_PRIVPASS_TOKEN_AUTHENTICATOR && targetBuff == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_AUTHENTICATOR);
return HITLS_AUTH_PRIVPASS_NO_AUTHENTICATOR;
}
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < targetLen) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, targetBuff, targetLen);
output->useLen = targetLen;
return HITLS_AUTH_SUCCESS;
}
static int32_t PrivPassGetTokenContent(HITLS_AUTH_PrivPassToken *obj, int32_t cmd, BSL_Param *param)
{
if (param == NULL || obj->type != HITLS_AUTH_PRIVPASS_TOKEN_INSTANCE || obj->st.token == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
PrivPass_TokenInstance *token = obj->st.token;
int32_t target;
uint8_t *targetBuff = 0;
uint32_t targetLen = 0;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_TOKEN_TYPE:
target = AUTH_PARAM_PRIVPASS_TOKEN_TYPE;
targetLen = (uint32_t)sizeof(token->tokenType);
break;
case HITLS_AUTH_PRIVPASS_GET_TOKEN_NONCE:
target = AUTH_PARAM_PRIVPASS_TOKEN_NONCE;
targetBuff = token->nonce;
targetLen = PRIVPASS_TOKEN_NONCE_LEN;
break;
case HITLS_AUTH_PRIVPASS_GET_TOKEN_CHALLENGEDIGEST:
target = AUTH_PARAM_PRIVPASS_TOKEN_CHALLENGEDIGEST;
targetBuff = token->challengeDigest;
targetLen = PRIVPASS_TOKEN_SHA256_SIZE;
break;
case HITLS_AUTH_PRIVPASS_GET_TOKEN_TOKENKEYID:
target = AUTH_PARAM_PRIVPASS_TOKEN_TOKENKEYID;
targetBuff = token->tokenKeyId;
targetLen = PRIVPASS_TOKEN_SHA256_SIZE;
break;
default:
target = AUTH_PARAM_PRIVPASS_TOKEN_AUTHENTICATOR;
targetBuff = token->authenticator.data;
targetLen = token->authenticator.dataLen;
break;
}
return CopyTokenContent(token, param, target, targetBuff, targetLen);
}
int32_t HITLS_AUTH_PrivPassTokenCtrl(HITLS_AUTH_PrivPassToken *object, int32_t cmd, void *param, uint32_t paramLen)
{
if (object == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
(void)paramLen;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGEREQUEST_INFO:
return PrivPassGetTokenChallengeRequest(object, param);
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_TYPE:
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_ISSUERNAME:
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_REDEMPTION:
case HITLS_AUTH_PRIVPASS_GET_TOKENCHALLENGE_ORIGININFO:
return PrivPassGetTokenChallengeContent(object, cmd, param);
case HITLS_AUTH_PRIVPASS_GET_TOKENREQUEST_TYPE:
case HITLS_AUTH_PRIVPASS_GET_TOKENREQUEST_TRUNCATEDTOKENKEYID:
case HITLS_AUTH_PRIVPASS_GET_TOKENREQUEST_BLINDEDMSG:
return PrivPassGetTokenRequestContent(object, cmd, param);
case HITLS_AUTH_PRIVPASS_GET_TOKENRESPONSE_INFO:
return PrivPassGetTokenResponseContent(object, param);
case HITLS_AUTH_PRIVPASS_GET_TOKEN_TYPE:
case HITLS_AUTH_PRIVPASS_GET_TOKEN_NONCE:
case HITLS_AUTH_PRIVPASS_GET_TOKEN_CHALLENGEDIGEST:
case HITLS_AUTH_PRIVPASS_GET_TOKEN_TOKENKEYID:
case HITLS_AUTH_PRIVPASS_GET_TOKEN_AUTHENTICATOR:
return PrivPassGetTokenContent(object, cmd, param);
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_CMD);
return HITLS_AUTH_PRIVPASS_INVALID_CMD;
}
}
static int32_t PrivPassGetCtxContent(HITLS_AUTH_PrivPassCtx *ctx, int32_t cmd, BSL_Param *param)
{
BSL_Param *output = NULL;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_CTX_NONCE:
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_CTX_NONCE);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < PRIVPASS_TOKEN_NONCE_LEN) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, ctx->nonce, PRIVPASS_TOKEN_NONCE_LEN);
output->useLen = PRIVPASS_TOKEN_NONCE_LEN;
return HITLS_AUTH_SUCCESS;
case HITLS_AUTH_PRIVPASS_GET_CTX_TRUNCATEDTOKENKEYID:
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_CTX_TRUNCATEDTOKENKEYID);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_UINT8) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
return BSL_PARAM_SetValue(output, AUTH_PARAM_PRIVPASS_CTX_TRUNCATEDTOKENKEYID, BSL_PARAM_TYPE_UINT8,
&ctx->tokenKeyId[PRIVPASS_TOKEN_SHA256_SIZE - 1], 1); // 1 byte
default:
if (ctx->pubKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO);
return HITLS_AUTH_PRIVPASS_NO_PUBKEY_INFO;
}
output = BSL_PARAM_FindParam(param, AUTH_PARAM_PRIVPASS_CTX_TOKENKEYID);
if (output == NULL || output->valueType != BSL_PARAM_TYPE_OCTETS_PTR) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (output->valueLen < PRIVPASS_TOKEN_SHA256_SIZE) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH);
return HITLS_AUTH_PRIVPASS_BUFFER_NOT_ENOUGH;
}
(void)memcpy_s(output->value, output->valueLen, ctx->tokenKeyId, PRIVPASS_TOKEN_SHA256_SIZE);
output->useLen = PRIVPASS_TOKEN_SHA256_SIZE;
return HITLS_AUTH_SUCCESS;
}
}
int32_t HITLS_AUTH_PrivPassCtxCtrl(HITLS_AUTH_PrivPassCtx *ctx, int32_t cmd, void *param, uint32_t paramLen)
{
if (ctx == NULL || param == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
(void)paramLen;
switch (cmd) {
case HITLS_AUTH_PRIVPASS_GET_CTX_TOKENKEYID:
case HITLS_AUTH_PRIVPASS_GET_CTX_TRUNCATEDTOKENKEYID:
case HITLS_AUTH_PRIVPASS_GET_CTX_NONCE:
return PrivPassGetCtxContent(ctx, cmd, param);
default:
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_CMD);
return HITLS_AUTH_PRIVPASS_INVALID_CMD;
}
} | 2302_82127028/openHiTLS-examples_5062 | auth/privpass_token/src/privpass_token_util.c | C | unknown | 45,269 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "securec.h"
#include "crypt_eal_pkey.h"
#include "crypt_eal_rand.h"
#include "auth_params.h"
#include "auth_errno.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "crypt_eal_md.h"
#include "crypt_eal_rand.h"
#include "crypt_errno.h"
#include "crypt_eal_codecs.h"
#include "auth_privpass_token.h"
#include "privpass_token.h"
#include "bsl_sal.h"
void *PrivPassNewPkeyCtx(void *libCtx, const char *attrName, int32_t algId)
{
(void)libCtx;
(void)attrName;
return CRYPT_EAL_PkeyNewCtx(algId);
}
void PrivPassFreePkeyCtx(void *pkeyCtx)
{
CRYPT_EAL_PkeyFreeCtx(pkeyCtx);
}
int32_t PrivPassPubDigest(void *libCtx, const char *attrName, int32_t algId, const uint8_t *input, uint32_t inputLen,
uint8_t *digest, uint32_t *digestLen)
{
(void)libCtx;
(void)attrName;
if (input == NULL || inputLen == 0 || digest == NULL || digestLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
uint32_t mdSize = CRYPT_EAL_MdGetDigestSize(algId);
if (mdSize == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
if (*digestLen < mdSize) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_MdCTX *ctx = CRYPT_EAL_MdNewCtx(algId);
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
int32_t ret = CRYPT_EAL_MdInit(ctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_EAL_MdFreeCtx(ctx);
return ret;
}
ret = CRYPT_EAL_MdUpdate(ctx, input, inputLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_EAL_MdFreeCtx(ctx);
return ret;
}
ret = CRYPT_EAL_MdFinal(ctx, digest, digestLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
CRYPT_EAL_MdFreeCtx(ctx);
return ret;
}
CRYPT_EAL_MdFreeCtx(ctx);
return CRYPT_SUCCESS;
}
int32_t PrivPassPubBlind(void *pkeyCtx, int32_t algId, const uint8_t *data, uint32_t dataLen, uint8_t *blindedData,
uint32_t *blindedDataLen)
{
if (pkeyCtx == NULL || data == NULL || dataLen == 0 || blindedData == NULL || blindedDataLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = (CRYPT_EAL_PkeyCtx *)pkeyCtx;
uint32_t flag = CRYPT_RSA_BSSA;
uint32_t padType = 0;
int32_t ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(padType));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (padType != CRYPT_EMSA_PSS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_ALG);
return HITLS_AUTH_PRIVPASS_INVALID_ALG;
}
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_EAL_PkeyBlind(ctx, algId, data, dataLen, blindedData, blindedDataLen);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t PrivPassPubUnBlind(void *pkeyCtx, const uint8_t *blindedData, uint32_t blindedDataLen, uint8_t *data,
uint32_t *dataLen)
{
if (pkeyCtx == NULL || blindedData == NULL || blindedDataLen == 0 || data == NULL || dataLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = (CRYPT_EAL_PkeyCtx *)pkeyCtx;
return CRYPT_EAL_PkeyUnBlind(ctx, blindedData, blindedDataLen, data, dataLen);
}
int32_t PrivPassPubSignData(void *pkeyCtx, const uint8_t *data, uint32_t dataLen, uint8_t *sign, uint32_t *signLen)
{
if (pkeyCtx == NULL || data == NULL || dataLen == 0 || sign == NULL || signLen == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = (CRYPT_EAL_PkeyCtx *)pkeyCtx;
uint32_t flag = CRYPT_RSA_BSSA;
uint32_t padType = CRYPT_EMSA_PSS;
int32_t ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_PADDING, &padType, sizeof(padType));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return CRYPT_EAL_PkeySignData(ctx, data, dataLen, sign, signLen);
}
int32_t PrivPassPubVerify(void *pkeyCtx, int32_t algId, const uint8_t *data, uint32_t dataLen, const uint8_t *sign,
uint32_t signLen)
{
if (pkeyCtx == NULL || data == NULL || dataLen == 0 || sign == NULL || signLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = (CRYPT_EAL_PkeyCtx *)pkeyCtx;
uint32_t flag = CRYPT_RSA_BSSA;
uint32_t padType = 0;
int32_t ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(padType));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (padType != CRYPT_EMSA_PSS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_ALG);
return HITLS_AUTH_PRIVPASS_INVALID_ALG;
}
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_SET_RSA_FLAG, (void *)&flag, sizeof(uint32_t));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
return CRYPT_EAL_PkeyVerify(ctx, algId, data, dataLen, sign, signLen);
}
static int32_t PubKeyCheck(CRYPT_EAL_PkeyCtx *ctx)
{
uint32_t padType = 0;
uint32_t keyBits = 0;
CRYPT_MD_AlgId mdType = 0;
int32_t ret = CRYPT_EAL_PkeyGetId(ctx);
if (ret != CRYPT_PKEY_RSA) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_TYPE;
}
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(padType));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (padType != CRYPT_EMSA_PSS) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_PADDING_INFO);
return HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_PADDING_INFO;
}
ret = CRYPT_EAL_PkeyCtrl(ctx, CRYPT_CTRL_GET_RSA_MD, &mdType, sizeof(CRYPT_MD_AlgId));
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (mdType != CRYPT_MD_SHA384) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_PADDING_MD);
return HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_PADDING_MD;
}
keyBits = CRYPT_EAL_PkeyGetKeyBits(ctx);
if (keyBits != 2048) { // now only support rsa-2048
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_BITS);
return HITLS_AUTH_PRIVPASS_INVALID_PUBKEY_BITS;
}
return CRYPT_SUCCESS;
}
int32_t PrivPassPubDecodePubKey(void *libCtx, const char *attrName, uint8_t *pubKey, uint32_t pubKeyLen, void **pkeyCtx)
{
(void)libCtx;
(void)attrName;
if (pkeyCtx == NULL || *pkeyCtx != NULL || pubKey == NULL || pubKeyLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = NULL;
BSL_Buffer encode = {.data = pubKey, .dataLen = pubKeyLen};
int32_t ret = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_ASN1, CRYPT_PUBKEY_SUBKEY, &encode, NULL, 0, &ctx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = PubKeyCheck(ctx);
if (ret != CRYPT_SUCCESS) {
CRYPT_EAL_PkeyFreeCtx(ctx);
return ret;
}
*pkeyCtx = ctx;
return CRYPT_SUCCESS;
}
int32_t PrivPassPubDecodePrvKey(void *libCtx, const char *attrName, void *param, uint8_t *prvKey, uint32_t prvKeyLen,
void **pkeyCtx)
{
(void)libCtx;
(void)attrName;
(void)param;
if (pkeyCtx == NULL || *pkeyCtx != NULL || prvKey == NULL || prvKeyLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
CRYPT_EAL_PkeyCtx *ctx = NULL;
uint32_t keyBits = 0;
uint8_t *tmpBuff = BSL_SAL_Malloc(prvKeyLen + 1);
if (tmpBuff == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
(void)memcpy_s(tmpBuff, prvKeyLen, prvKey, prvKeyLen);
tmpBuff[prvKeyLen] = '\0';
BSL_Buffer encode = {.data = tmpBuff, .dataLen = prvKeyLen};
int32_t ret = CRYPT_EAL_DecodeBuffKey(BSL_FORMAT_PEM, CRYPT_PRIKEY_PKCS8_UNENCRYPT, &encode, NULL, 0, &ctx);
(void)memset_s(tmpBuff, prvKeyLen, 0, prvKeyLen);
BSL_SAL_Free(tmpBuff);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (CRYPT_EAL_PkeyGetId(ctx) != CRYPT_PKEY_RSA) {
CRYPT_EAL_PkeyFreeCtx(ctx);
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PRVKEY_TYPE);
return HITLS_AUTH_PRIVPASS_INVALID_PRVKEY_TYPE;
}
keyBits = CRYPT_EAL_PkeyGetKeyBits(ctx);
if (keyBits != 2048) { // now only support rsa-2048
CRYPT_EAL_PkeyFreeCtx(ctx);
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_PRVKEY_BITS);
return HITLS_AUTH_PRIVPASS_INVALID_PRVKEY_BITS;
}
*pkeyCtx = ctx;
return CRYPT_SUCCESS;
}
int32_t PrivPassPubCheckKeyPair(void *pubKeyCtx, void *prvKeyCtx)
{
if (pubKeyCtx == NULL || prvKeyCtx == NULL) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
int32_t ret = CRYPT_EAL_PkeyPairCheck(pubKeyCtx, prvKeyCtx);
if (ret != CRYPT_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t PrivPassPubRandom(uint8_t *buffer, uint32_t bufferLen)
{
if (buffer == NULL || bufferLen == 0) {
BSL_ERR_PUSH_ERROR(HITLS_AUTH_PRIVPASS_INVALID_INPUT);
return HITLS_AUTH_PRIVPASS_INVALID_INPUT;
}
return CRYPT_EAL_RandbytesEx(NULL, buffer, bufferLen);
}
PrivPassCryptCb PrivPassCryptPubCb(void)
{
PrivPassCryptCb method = {
.newPkeyCtx = PrivPassNewPkeyCtx,
.freePkeyCtx = PrivPassFreePkeyCtx,
.digest = PrivPassPubDigest,
.blind = PrivPassPubBlind,
.unBlind = PrivPassPubUnBlind,
.signData = PrivPassPubSignData,
.verify = PrivPassPubVerify,
.decodePubKey = PrivPassPubDecodePubKey,
.decodePrvKey = PrivPassPubDecodePrvKey,
.checkKeyPair = PrivPassPubCheckKeyPair,
.random = PrivPassPubRandom,
};
return method;
} | 2302_82127028/openHiTLS-examples_5062 | auth/privpass_token/src/privpass_token_wrapper.c | C | unknown | 11,338 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef BSL_ASN1_INTERNAL_H
#define BSL_ASN1_INTERNAL_H
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include "bsl_list.h"
#include "bsl_uio.h"
#include "bsl_asn1.h"
#ifdef __cplusplus
extern "C" {
#endif
#define BSL_ASN1_MAX_TEMPLATE_DEPTH 6
#define BSL_ASN1_UTCTIME_LEN 13 // YYMMDDHHMMSSZ
#define BSL_ASN1_GENERALIZEDTIME_LEN 15 // YYYYMMDDHHMMSSZ
typedef enum {
BSL_ASN1_TYPE_GET_ANY_TAG = 0,
BSL_ASN1_TYPE_CHECK_CHOICE_TAG = 1
} BSL_ASN1_CALLBACK_TYPE;
/**
* @ingroup bsl_asn1
* @brief Obtain the length of V or LV in an ASN1 TLV structure.
*
* @param encode [IN/OUT] Data to be decoded. Update the offset after decoding.
* @param encLen [IN/OUT] The length of the data to be decoded.
* @param completeLen [IN] True: Get the length of L+V; False: Get the length of V.
* @param len [OUT] Output.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_DecodeLen(uint8_t **encode, uint32_t *encLen, bool completeLen, uint32_t *len);
/**
* @ingroup bsl_asn1
* @brief Decoding of primitive type data.
*
* @param asn [IN] The data to be decoded.
* @param decodeData [OUT] Decoding result.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_DecodePrimitiveItem(BSL_ASN1_Buffer *asn, void *decodeData);
/**
* @ingroup bsl_asn1
* @brief Decode one asn1 item.
*
* @param encode [IN/OUT] Data to be decoded. Update the offset after decoding.
* @param encLen [IN/OUT] The length of the data to be decoded.
* @param asnItem [OUT] Output.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_DecodeItem(uint8_t **encode, uint32_t *encLen, BSL_ASN1_Buffer *asnItem);
/**
* @ingroup bsl_asn1
* @brief Obtain the length of an ASN1 TLV structure.
*
* @param data [IN] Data to be decoded. Update the offset after decoding.
* @param dataLen [OUT] Decoding result.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_GetCompleteLen(uint8_t *data, uint32_t *dataLen);
/**
* @ingroup bsl_asn1
* @brief Encode the smaller positive integer.
*
* @param tag [IN] BSL_ASN1_TAG_INTEGER or BSL_ASN1_TAG_ENUMERATED
* @param limb [IN] Positive integer.
* @param asn [OUT] Encoding result.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_EncodeLimb(uint8_t tag, uint64_t limb, BSL_ASN1_Buffer *asn);
/**
* @ingroup bsl_asn1
* @brief Calculate the total encoding length for a ASN.1 type through the content length.
*
* @param contentLen [IN] The length of the content to be encoded.
* @param encodeLen [OUT] The total number of bytes needed for DER encoding.
* @retval BSL_SUCCESS, success.
* Other error codes see the bsl_errno.h.
*/
int32_t BSL_ASN1_GetEncodeLen(uint32_t contentLen, uint32_t *encodeLen);
#ifdef __cplusplus
}
#endif
#endif // BSL_ASN1_INTERNAL_H
| 2302_82127028/openHiTLS-examples_5062 | bsl/asn1/include/bsl_asn1_internal.h | C | unknown | 3,544 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include <stdbool.h>
#include "securec.h"
#include "bsl_err.h"
#include "bsl_bytes.h"
#include "bsl_log_internal.h"
#include "bsl_binlog_id.h"
#include "bsl_asn1_local.h"
#include "bsl_sal.h"
#include "sal_time.h"
#define BSL_ASN1_INDEFINITE_LENGTH 0x80
#define BSL_ASN1_DEFINITE_MAX_CONTENT_OCTET_NUM 0x7F // 127
int32_t BSL_ASN1_DecodeLen(uint8_t **encode, uint32_t *encLen, bool completeLen, uint32_t *len)
{
if (encode == NULL || *encode == NULL || encLen == NULL || len == NULL) {
return BSL_NULL_INPUT;
}
uint8_t *temp = *encode;
uint32_t tempLen = *encLen;
uint32_t parseLen = 0;
if (tempLen < 1) {
return BSL_ASN1_ERR_DECODE_LEN;
}
if ((*temp & BSL_ASN1_INDEFINITE_LENGTH) == 0) {
parseLen = *temp;
temp++;
tempLen--;
parseLen += ((completeLen) ? 1 : 0);
} else {
uint32_t index = *temp - BSL_ASN1_INDEFINITE_LENGTH;
if (index > sizeof(int32_t)) {
return BSL_ASN1_ERR_MAX_LEN_NUM;
}
temp++;
tempLen--;
if (tempLen < index) {
return BSL_ASN1_ERR_BUFF_NOT_ENOUGH;
}
for (uint32_t iter = 0; iter < index; iter++) {
parseLen = (parseLen << 8) | *temp; // one byte = 8 bits
temp++;
tempLen--;
}
// anti-flip
if (parseLen >= ((((uint64_t)1 << 32) - 1) - index - 2)) { // 1<<32:U32_MAX; 2: Tag + length(0x8x)
return BSL_ASN1_ERR_MAX_LEN_NUM;
}
parseLen += ((completeLen) ? (index + 1) : 0);
}
uint32_t length = (completeLen) ? *encLen : tempLen;
/* The length supports a maximum of 4 bytes */
if (parseLen > length) {
return BSL_ASN1_ERR_DECODE_LEN;
}
*len = parseLen;
*encode = temp;
*encLen = tempLen;
return BSL_SUCCESS;
}
int32_t BSL_ASN1_GetCompleteLen(uint8_t *data, uint32_t *dataLen)
{
uint8_t *tmp = data;
uint32_t tmpLen = *dataLen;
uint32_t len = 0;
if (tmpLen < 1) {
return BSL_ASN1_ERR_BUFF_NOT_ENOUGH;
}
tmp++;
tmpLen--;
int32_t ret = BSL_ASN1_DecodeLen(&tmp, &tmpLen, true, &len);
if (ret != BSL_SUCCESS) {
return ret;
}
*dataLen = len + 1;
return BSL_SUCCESS;
}
int32_t BSL_ASN1_DecodeTagLen(uint8_t tag, uint8_t **encode, uint32_t *encLen, uint32_t *valLen)
{
if (encode == NULL || *encode == NULL || encLen == NULL || valLen == NULL) {
return BSL_NULL_INPUT;
}
uint8_t *temp = *encode;
uint32_t tempLen = *encLen;
if (tempLen < 1) {
return BSL_INVALID_ARG;
}
if (tag != *temp) {
return BSL_ASN1_ERR_MISMATCH_TAG;
}
temp++;
tempLen--;
uint32_t len;
int32_t ret = BSL_ASN1_DecodeLen(&temp, &tempLen, false, &len);
if (ret != BSL_SUCCESS) {
return ret;
}
if (len > tempLen) {
return BSL_ASN1_ERR_BUFF_NOT_ENOUGH;
}
*valLen = len;
*encode = temp;
*encLen = tempLen;
return BSL_SUCCESS;
}
int32_t BSL_ASN1_DecodeItem(uint8_t **encode, uint32_t *encLen, BSL_ASN1_Buffer *asnItem)
{
if (encode == NULL || *encode == NULL || encLen == NULL || asnItem == NULL) {
return BSL_NULL_INPUT;
}
uint8_t tag;
uint32_t len;
uint8_t *temp = *encode;
uint32_t tempLen = *encLen;
if (tempLen < 1) {
return BSL_INVALID_ARG;
}
tag = *temp;
temp++;
tempLen--;
int32_t ret = BSL_ASN1_DecodeLen(&temp, &tempLen, false, &len);
if (ret != BSL_SUCCESS) {
return ret;
}
asnItem->tag = tag;
asnItem->len = len;
asnItem->buff = temp;
temp += len;
tempLen -= len;
*encode = temp;
*encLen = tempLen;
return BSL_SUCCESS;
}
static int32_t ParseBool(uint8_t *val, uint32_t len, bool *decodeData)
{
if (len != 1) {
return BSL_ASN1_ERR_DECODE_BOOL;
}
*decodeData = (*val != 0) ? 1 : 0;
return BSL_SUCCESS;
}
static int32_t ParseInt(uint8_t *val, uint32_t len, int *decodeData)
{
uint8_t *temp = val;
if (len < 1 || len > sizeof(int)) {
return BSL_ASN1_ERR_DECODE_INT;
}
*decodeData = 0;
for (uint32_t i = 0; i < len; i++) {
*decodeData = (*decodeData << 8) | *temp;
temp++;
}
return BSL_SUCCESS;
}
static int32_t ParseBitString(uint8_t *val, uint32_t len, BSL_ASN1_BitString *decodeData)
{
if (len < 1 || *val > BSL_ASN1_VAL_MAX_BIT_STRING_LEN) {
return BSL_ASN1_ERR_DECODE_BIT_STRING;
}
decodeData->unusedBits = *val;
decodeData->buff = val + 1;
decodeData->len = len - 1;
return BSL_SUCCESS;
}
// len max support 4
static uint32_t DecodeAsciiNum(uint8_t **encode, uint32_t len)
{
uint32_t temp = 0;
uint8_t *data = *encode;
for (uint32_t i = 0; i < len; i++) {
temp *= 10; // 10: Process decimal numbers.
temp += (data[i] - '0');
}
*encode += len;
return temp;
}
static int32_t CheckTime(uint8_t *data, uint32_t len)
{
for (uint32_t i = 0; i < len; i++) {
if (data[i] > '9' || data[i] < '0') {
return BSL_ASN1_ERR_DECODE_TIME;
}
}
return BSL_SUCCESS;
}
// Support utcTime for YYMMDDHHMMSS[Z] and generalizedTime for YYYYMMDDHHMMSS[Z].
static int32_t ParseTime(uint8_t tag, uint8_t *val, uint32_t len, BSL_TIME *decodeData)
{
int32_t ret;
uint8_t *temp = val;
if (tag == BSL_ASN1_TAG_UTCTIME && (len != 12 && len != 13)) { // 12 YYMMDDHHMMSS, 13 YYMMDDHHMMSSZ
return BSL_ASN1_ERR_DECODE_UTC_TIME;
}
if (tag == BSL_ASN1_TAG_GENERALIZEDTIME && (len != 14 && len != 15)) { // 14 YYYYMMDDHHMMSS, 15 YYYYMMDDHHMMSSZ
return BSL_ASN1_ERR_DECODE_GENERAL_TIME;
}
// Check if the encoding is within the expected range and prepare for conversion
ret = tag == BSL_ASN1_TAG_UTCTIME ? CheckTime(val, 12) : CheckTime(val, 14); // 12|14: ignoring Z
if (ret != BSL_SUCCESS) {
return ret;
}
if (tag == BSL_ASN1_TAG_UTCTIME) {
decodeData->year = (uint16_t)DecodeAsciiNum(&temp, 2); // 2: YY
if (decodeData->year < 50) {
decodeData->year += 2000;
} else {
decodeData->year += 1900;
}
} else {
decodeData->year = (uint16_t)DecodeAsciiNum(&temp, 4); // 4: YYYY
}
decodeData->month = (uint8_t)DecodeAsciiNum(&temp, 2); // 2:MM
decodeData->day = (uint8_t)DecodeAsciiNum(&temp, 2); // 2: DD
decodeData->hour = (uint8_t)DecodeAsciiNum(&temp, 2); // 2: HH
decodeData->minute = (uint8_t)DecodeAsciiNum(&temp, 2); // 2: MM
decodeData->second = (uint8_t)DecodeAsciiNum(&temp, 2); // 2: SS
return BSL_DateTimeCheck(decodeData) ? BSL_SUCCESS : BSL_ASN1_ERR_CHECK_TIME;
}
static int32_t DecodeTwoLayerListInternal(uint32_t layer, BSL_ASN1_DecodeListParam *param, BSL_ASN1_Buffer *asn,
BSL_ASN1_ParseListAsnItem parseListItemCb, void *cbParam, BSL_ASN1_List *list)
{
int32_t ret;
uint8_t tag;
uint32_t encLen;
uint8_t *buff = asn->buff;
uint32_t len = asn->len;
BSL_ASN1_Buffer item;
while (len > 0) {
if (*buff != param->expTag[layer - 1]) {
return BSL_ASN1_ERR_MISMATCH_TAG;
}
tag = *buff;
buff++;
len--;
ret = BSL_ASN1_DecodeLen(&buff, &len, false, &encLen);
if (ret != BSL_SUCCESS) {
return ret;
}
item.tag = tag;
item.len = encLen;
item.buff = buff;
ret = parseListItemCb(layer, &item, cbParam, list);
if (ret != BSL_SUCCESS) {
return ret;
}
buff += encLen;
len -= encLen;
}
return BSL_SUCCESS;
}
static int32_t DecodeOneLayerList(BSL_ASN1_DecodeListParam *param, BSL_ASN1_Buffer *asn,
BSL_ASN1_ParseListAsnItem parseListItemCb, void *cbParam, BSL_ASN1_List *list)
{
return DecodeTwoLayerListInternal(1, param, asn, parseListItemCb, cbParam, list);
}
static int32_t DecodeTwoLayerList(BSL_ASN1_DecodeListParam *param, BSL_ASN1_Buffer *asn,
BSL_ASN1_ParseListAsnItem parseListItemCb, void *cbParam, BSL_ASN1_List *list)
{
int32_t ret;
uint8_t tag;
uint32_t encLen;
uint8_t *buff = asn->buff;
uint32_t len = asn->len;
BSL_ASN1_Buffer item;
while (len > 0) {
if (*buff != param->expTag[0]) {
return BSL_ASN1_ERR_MISMATCH_TAG;
}
tag = *buff;
buff++;
len--;
ret = BSL_ASN1_DecodeLen(&buff, &len, false, &encLen);
if (ret != BSL_SUCCESS) {
return ret;
}
item.tag = tag;
item.len = encLen;
item.buff = buff;
ret = parseListItemCb(1, &item, cbParam, list);
if (ret != BSL_SUCCESS) {
return ret;
}
ret = DecodeTwoLayerListInternal(2, param, &item, parseListItemCb, cbParam, list);
if (ret != BSL_SUCCESS) {
return ret;
}
buff += encLen;
len -= encLen;
}
return BSL_SUCCESS;
}
int32_t BSL_ASN1_DecodeListItem(BSL_ASN1_DecodeListParam *param, BSL_ASN1_Buffer *asn,
BSL_ASN1_ParseListAsnItem parseListItemCb, void *cbParam, BSL_ASN1_List *list)
{
if (param == NULL || asn == NULL || parseListItemCb == NULL || list == NULL) {
return BSL_INVALID_ARG;
}
// Currently, it supports a maximum of 2 layers
if (param->layer > BSL_ASN1_MAX_LIST_NEST_EPTH) {
return BSL_ASN1_ERR_EXCEED_LIST_DEPTH;
}
return param->layer == 1 ? DecodeOneLayerList(param, asn, parseListItemCb, cbParam, list)
: DecodeTwoLayerList(param, asn, parseListItemCb, cbParam, list);
}
static int32_t ParseBMPString(const uint8_t *bmp, uint32_t bmpLen, BSL_ASN1_Buffer *decode)
{
if (bmp == NULL || bmpLen == 0 || decode == NULL) {
return BSL_NULL_INPUT;
}
if (bmpLen % 2 != 0) { // multiple of 2
return BSL_INVALID_ARG;
}
uint8_t *tmp = (uint8_t *)BSL_SAL_Malloc(bmpLen / 2); // decodeLen = bmpLen/2
if (tmp == NULL) {
return BSL_MALLOC_FAIL;
}
for (uint32_t i = 0; i < bmpLen / 2; i++) { // decodeLen = bmpLen/2
tmp[i] = bmp[i * 2 + 1];
}
decode->buff = tmp;
decode->len = bmpLen / 2; // decodeLen = bmpLen/2
return BSL_SUCCESS;
}
static void EncodeBMPString(const uint8_t *in, uint32_t inLen, uint8_t *encode, uint32_t *offset)
{
uint8_t *output = encode + *offset;
for (uint32_t i = 0; i < inLen; i++) {
output[2 * i + 1] = in[i]; // need 2 space, [0,0] -> after encode = [0, data];
output[2 * i + 0] = 0;
}
*offset += inLen * 2; // encodeLen = 2 * inLen
return;
}
/**
* Big numbers do not need to call this interface,
* the filled leading 0 has no effect on the result of large numbers, big numbers can be directly used asn's buff.
*
* It has been ensured at parsing time that the content to which the buff points is security for length within asn'len
*/
int32_t BSL_ASN1_DecodePrimitiveItem(BSL_ASN1_Buffer *asn, void *decodeData)
{
if (asn == NULL || decodeData == NULL) {
return BSL_NULL_INPUT;
}
switch (asn->tag) {
case BSL_ASN1_TAG_BOOLEAN:
return ParseBool(asn->buff, asn->len, decodeData);
case BSL_ASN1_TAG_INTEGER:
case BSL_ASN1_TAG_ENUMERATED:
return ParseInt(asn->buff, asn->len, decodeData);
case BSL_ASN1_TAG_BITSTRING:
return ParseBitString(asn->buff, asn->len, decodeData);
case BSL_ASN1_TAG_UTCTIME:
case BSL_ASN1_TAG_GENERALIZEDTIME:
return ParseTime(asn->tag, asn->buff, asn->len, decodeData);
case BSL_ASN1_TAG_BMPSTRING:
return ParseBMPString(asn->buff, asn->len, decodeData);
default:
break;
}
return BSL_ASN1_FAIL;
}
static int32_t BSL_ASN1_AnyOrChoiceTagProcess(bool isAny, BSL_ASN1_AnyOrChoiceParam *tagCbinfo, uint8_t *tag)
{
if (tagCbinfo->tagCb == NULL) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05065, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: callback is null", 0, 0, 0, 0);
return BSL_ASN1_ERR_NO_CALLBACK;
}
int32_t type = isAny == true ? BSL_ASN1_TYPE_GET_ANY_TAG : BSL_ASN1_TYPE_CHECK_CHOICE_TAG;
int32_t ret = tagCbinfo->tagCb(type, tagCbinfo->idx, tagCbinfo->previousAsnOrTag, tag);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05066, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: callback is err %x", ret, 0, 0, 0);
}
return ret;
}
static int32_t BSL_ASN1_ProcessWithoutDefOrOpt(BSL_ASN1_AnyOrChoiceParam *tagCbinfo, uint8_t realTag, uint8_t *expTag)
{
int32_t ret;
uint8_t tag = *expTag;
// Any and choice will not have a coexistence scenario, which is meaningless.
if (tag == BSL_ASN1_TAG_CHOICE) {
tagCbinfo->previousAsnOrTag = &realTag;
return BSL_ASN1_AnyOrChoiceTagProcess(false, tagCbinfo, expTag);
}
// The tags of any and normal must be present
if (tag == BSL_ASN1_TAG_ANY) {
ret = BSL_ASN1_AnyOrChoiceTagProcess(true, tagCbinfo, &tag);
if (ret != BSL_SUCCESS) {
return ret;
}
}
if (tag != realTag) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05067, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: expected tag %x is not match %x", tag, realTag, 0, 0);
return BSL_ASN1_ERR_TAG_EXPECTED;
}
*expTag = realTag;
return BSL_SUCCESS;
}
/**
* Reference: X.690 Information technology - ASN.1 encoding rules: 8.3
* If the contents octect of an integer value encoding consist of more than one octet,
* then the bits of the first octet and bit 8 of the second octet:
* a): shall not all be ones; and
* b): shall not all be zero.
*
* Note: Currently, only positive integers are supported, and negative integers are not supported.
*/
int32_t ProcessIntegerType(uint8_t *temp, uint32_t len, BSL_ASN1_Buffer *asn)
{
// Check if it is a negative number
if (*temp & 0x80) {
return BSL_ASN1_ERR_DECODE_INT;
}
// Check if the first octet is 0 and the second octet is not 0
if (*temp == 0 && len > 1 && (*(temp + 1) & 0x80) == 0) {
return BSL_ASN1_ERR_DECODE_INT;
}
// Calculate the actual length (remove leading zeros)
uint32_t actualLen = len;
uint8_t *actualBuff = temp;
while (actualLen > 1 && *actualBuff == 0) {
actualLen--;
actualBuff++;
}
asn->len = actualLen;
asn->buff = actualBuff;
return BSL_SUCCESS;
}
static int32_t ProcessTag(uint8_t flags, BSL_ASN1_AnyOrChoiceParam *tagCbinfo, uint8_t *temp, uint32_t tempLen,
uint8_t *tag, BSL_ASN1_Buffer *asn)
{
int32_t ret = BSL_SUCCESS;
if ((flags & BSL_ASN1_FLAG_OPTIONAL_DEFAUL) != 0) {
if (tempLen < 1) {
asn->tag = 0;
asn->len = 0;
asn->buff = NULL;
return BSL_SUCCESS;
}
if (*tag == BSL_ASN1_TAG_ANY) {
ret = BSL_ASN1_AnyOrChoiceTagProcess(true, tagCbinfo, tag);
if (ret != BSL_SUCCESS) {
return ret;
}
}
if (*tag == BSL_ASN1_TAG_CHOICE) {
tagCbinfo->previousAsnOrTag = temp;
ret = BSL_ASN1_AnyOrChoiceTagProcess(false, tagCbinfo, tag);
if (ret != BSL_SUCCESS) {
return ret;
}
}
if (*tag == BSL_ASN1_TAG_EMPTY) {
return BSL_ASN1_ERR_TAG_EXPECTED;
}
if (*tag != *temp) { // The optional or default scene is not encoded
asn->tag = 0;
asn->len = 0;
asn->buff = NULL;
}
} else {
/* No optional or default scenes, tag must exist */
if (tempLen < 1) {
return BSL_ASN1_ERR_DECODE_LEN;
}
ret = BSL_ASN1_ProcessWithoutDefOrOpt(tagCbinfo, *temp, tag);
}
return ret;
}
static int32_t BSL_ASN1_ProcessNormal(BSL_ASN1_AnyOrChoiceParam *tagCbinfo,
BSL_ASN1_TemplateItem *item, uint8_t **encode, uint32_t *encLen, BSL_ASN1_Buffer *asn)
{
uint32_t len;
uint8_t tag = item->tag;
uint8_t *temp = *encode;
uint32_t tempLen = *encLen;
asn->tag = tag; // init tag
int32_t ret = ProcessTag(item->flags, tagCbinfo, temp, tempLen, &tag, asn);
if (ret != BSL_SUCCESS || asn->tag == 0) {
return ret;
}
temp++;
tempLen--;
ret = BSL_ASN1_DecodeLen(&temp, &tempLen, false, &len);
if (ret != BSL_SUCCESS) {
return ret;
}
asn->tag = tag; // update tag
if ((tag == BSL_ASN1_TAG_INTEGER || tag == BSL_ASN1_TAG_ENUMERATED) && len > 0) {
ret = ProcessIntegerType(temp, len, asn);
if (ret != BSL_SUCCESS) {
return ret;
}
} else {
asn->len = len;
asn->buff = (tag == BSL_ASN1_TAG_NULL) ? NULL : temp;
}
/* struct type, headerOnly flag is set, only the whole is parsed, otherwise the parsed content is traversed */
if (((item->tag & BSL_ASN1_TAG_CONSTRUCTED) != 0 && (item->flags & BSL_ASN1_FLAG_HEADERONLY) != 0) ||
(item->tag & BSL_ASN1_TAG_CONSTRUCTED) == 0) {
temp += len;
tempLen -= len;
}
*encode = temp;
*encLen = tempLen;
return BSL_SUCCESS;
}
uint32_t BSL_ASN1_SkipChildNode(uint32_t idx, BSL_ASN1_TemplateItem *item, uint32_t count)
{
uint32_t i = idx + 1;
for (; i < count; i++) {
if (item[i].depth <= item[idx].depth) {
break;
}
}
return i - idx;
}
static bool BSL_ASN1_IsConstructItem(BSL_ASN1_TemplateItem *item)
{
return item->tag & BSL_ASN1_TAG_CONSTRUCTED;
}
static int32_t BSL_ASN1_FillConstructItemWithNull(BSL_ASN1_Template *templ, uint32_t *templIdx,
BSL_ASN1_Buffer *asnArr, uint32_t arrNum, uint32_t *arrIdx)
{
// The construct type value is marked headeronly
if ((templ->templItems[*templIdx].flags & BSL_ASN1_FLAG_HEADERONLY) != 0) {
if (*arrIdx >= arrNum) {
return BSL_ASN1_ERR_OVERFLOW;
} else {
asnArr[*arrIdx].tag = 0;
asnArr[*arrIdx].len = 0;
asnArr[*arrIdx].buff = 0;
(*arrIdx)++;
}
(*templIdx) += BSL_ASN1_SkipChildNode(*templIdx, templ->templItems, templ->templNum);
} else {
// This scenario does not record information about the parent node
(*templIdx)++;
}
return BSL_SUCCESS;
}
int32_t BSL_ASN1_SkipChildNodeAndFill(uint32_t *idx, BSL_ASN1_Template *templ,
BSL_ASN1_Buffer *asnArr, uint32_t arrNum, uint32_t *arrIndex)
{
uint32_t arrIdx = *arrIndex;
uint32_t i = *idx;
for (; i < templ->templNum;) {
if (templ->templItems[i].depth <= templ->templItems[*idx].depth && i > *idx) {
break;
}
// There are also struct types under the processing parent
if (BSL_ASN1_IsConstructItem(&templ->templItems[i])) {
int32_t ret = BSL_ASN1_FillConstructItemWithNull(templ, &i, asnArr, arrNum, &arrIdx);
if (ret != BSL_SUCCESS) {
return ret;
}
} else {
asnArr[arrIdx].tag = 0;
asnArr[arrIdx].len = 0;
asnArr[arrIdx].buff = 0;
arrIdx++;
i++;
}
}
*arrIndex = arrIdx;
*idx = i;
return BSL_SUCCESS;
}
int32_t BSL_ASN1_ProcessConstructResult(BSL_ASN1_Template *templ, uint32_t *templIdx, BSL_ASN1_Buffer *asn,
BSL_ASN1_Buffer *asnArr, uint32_t arrNum, uint32_t *arrIdx)
{
int32_t ret;
// Optional or default construct type, without any data to be parsed, need to skip all child nodes
if ((templ->templItems[*templIdx].flags & BSL_ASN1_FLAG_OPTIONAL_DEFAUL) != 0 && asn->tag == 0) {
ret = BSL_ASN1_SkipChildNodeAndFill(templIdx, templ, asnArr, arrNum, arrIdx);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05068, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: skip and fill node err %x, idx %u", ret, *templIdx, 0, 0);
return ret;
}
return BSL_SUCCESS;
}
if ((templ->templItems[*templIdx].flags & BSL_ASN1_FLAG_HEADERONLY) != 0) {
if (*arrIdx >= arrNum) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05069, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: array idx %u, overflow %u, templ %u", *arrIdx, arrNum, *templIdx, 0);
return BSL_ASN1_ERR_OVERFLOW;
} else {
// Shallow copy of structure
asnArr[*arrIdx].tag = asn->tag;
asnArr[*arrIdx].len = asn->len;
asnArr[*arrIdx].buff = asn->buff;
(*arrIdx)++;
}
(*templIdx) += BSL_ASN1_SkipChildNode(*templIdx, templ->templItems, templ->templNum);
} else {
(*templIdx)++; // Non header only flags, do not fill this parse
}
return BSL_SUCCESS;
}
static inline bool IsInvalidTempl(BSL_ASN1_Template *templ)
{
return templ == NULL || templ->templNum == 0 || templ->templItems == NULL;
}
static inline bool IsInvalidAsns(BSL_ASN1_Buffer *asnArr, uint32_t arrNum)
{
return asnArr == NULL || arrNum == 0;
}
int32_t BSL_ASN1_DecodeTemplate(BSL_ASN1_Template *templ, BSL_ASN1_DecTemplCallBack decTemlCb,
uint8_t **encode, uint32_t *encLen, BSL_ASN1_Buffer *asnArr, uint32_t arrNum)
{
int32_t ret;
if (IsInvalidTempl(templ) || encode == NULL || *encode == NULL || encLen == NULL || IsInvalidAsns(asnArr, arrNum)) {
return BSL_NULL_INPUT;
}
uint8_t *temp = *encode;
uint32_t tempLen = *encLen;
BSL_ASN1_Buffer asn = {0}; // temp var
uint32_t arrIdx = 0;
BSL_ASN1_Buffer previousAsn = {0};
BSL_ASN1_AnyOrChoiceParam tagCbinfo = {0, NULL, decTemlCb};
for (uint32_t i = 0; i < templ->templNum;) {
if (templ->templItems[i].depth > BSL_ASN1_MAX_TEMPLATE_DEPTH) {
return BSL_ASN1_ERR_MAX_DEPTH;
}
tagCbinfo.previousAsnOrTag = &previousAsn;
tagCbinfo.idx = i;
if (BSL_ASN1_IsConstructItem(&templ->templItems[i])) {
ret = BSL_ASN1_ProcessNormal(&tagCbinfo, &templ->templItems[i], &temp, &tempLen, &asn);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05070, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: parse construct item err %x, idx %u", ret, i, 0, 0);
return ret;
}
ret = BSL_ASN1_ProcessConstructResult(templ, &i, &asn, asnArr, arrNum, &arrIdx);
if (ret != BSL_SUCCESS) {
return ret;
}
} else {
ret = BSL_ASN1_ProcessNormal(&tagCbinfo, &templ->templItems[i], &temp, &tempLen, &asn);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05071, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: parse primitive item err %x, idx %u", ret, i, 0, 0);
return ret;
}
// Process no construct result
if (arrIdx >= arrNum) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05072, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"asn1: array idx %u, overflow %u, templ %u", arrIdx, arrNum, i, 0);
return BSL_ASN1_ERR_OVERFLOW;
} else {
asnArr[arrIdx++] = asn; // Shallow copy of structure
}
i++;
}
previousAsn = asn;
}
*encode = temp;
*encLen = tempLen;
return BSL_SUCCESS;
}
/* Init the depth and flags of the items. */
static int32_t EncodeInitItemFlag(BSL_ASN1_EncodeItem *eItems, BSL_ASN1_TemplateItem *tItems, uint32_t eleNum)
{
uint32_t stack[BSL_ASN1_MAX_TEMPLATE_DEPTH + 1] = {0}; // store the index of the items
int32_t peek = 0;
/* Stack the first item */
if (tItems[0].depth > BSL_ASN1_MAX_TEMPLATE_DEPTH) {
return BSL_ASN1_ERR_MAX_DEPTH;
}
eItems[0].depth = tItems[0].depth;
eItems[0].optional = tItems[0].flags & BSL_ASN1_FLAG_OPTIONAL_DEFAUL;
stack[peek] = 0;
for (uint32_t i = 1; i < eleNum; i++) {
if (tItems[i].depth > BSL_ASN1_MAX_TEMPLATE_DEPTH) {
return BSL_ASN1_ERR_MAX_DEPTH;
}
eItems[i].depth = tItems[i].depth;
while (eItems[i].depth <= eItems[stack[peek]].depth) {
peek--;
}
/* After the above processing, the top of the stack is the parent node of the current node. */
/* The null type only inherits the optional tag of the parent node. */
eItems[i].optional = eItems[stack[peek]].optional;
if (tItems[i].tag != BSL_ASN1_TAG_NULL) {
eItems[i].optional |= (tItems[i].flags & BSL_ASN1_FLAG_OPTIONAL_DEFAUL);
}
eItems[i].skip = eItems[stack[peek]].skip == 1 || (tItems[stack[peek]].flags & BSL_ASN1_FLAG_HEADERONLY) != 0;
stack[++peek] = i;
}
return BSL_SUCCESS;
}
static inline bool IsAnyOrChoice(uint8_t tag)
{
return tag == BSL_ASN1_TAG_ANY || tag == BSL_ASN1_TAG_CHOICE;
}
static uint8_t GetOctetNumOfUint(uint64_t number)
{
uint8_t cnt = 0;
for (uint64_t i = number; i != 0; i >>= 8) { // one byte = 8 bits
cnt++;
}
return cnt;
}
static uint8_t GetLenOctetNum(uint32_t contentOctetNum)
{
return contentOctetNum <= BSL_ASN1_DEFINITE_MAX_CONTENT_OCTET_NUM ? 1 : 1 + GetOctetNumOfUint(contentOctetNum);
}
static int32_t GetContentLenOfInt(uint8_t *buff, uint32_t len, uint32_t *outLen)
{
if (len == 0) {
*outLen = 0;
return BSL_SUCCESS;
}
uint32_t res = len;
for (uint32_t i = 0; i < len; i++) {
if (buff[i] != 0) {
break;
}
res--;
}
if (res == 0) { // The current int value is 0
*outLen = 1;
return BSL_SUCCESS;
}
uint8_t high = buff[len - res] & 0x80;
if (high) {
if (res == UINT32_MAX) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
res++;
}
*outLen = res;
return BSL_SUCCESS;
}
static int32_t GetContentLen(BSL_ASN1_Buffer *asn, uint32_t *len)
{
if (asn == NULL || len == NULL) {
return BSL_NULL_INPUT;
}
switch (asn->tag) {
case BSL_ASN1_TAG_NULL:
*len = 0;
return BSL_SUCCESS;
case BSL_ASN1_TAG_INTEGER:
case BSL_ASN1_TAG_ENUMERATED:
return GetContentLenOfInt(asn->buff, asn->len, len);
case BSL_ASN1_TAG_BITSTRING:
*len = ((BSL_ASN1_BitString *)asn->buff)->len;
if (*len == UINT32_MAX) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
*len += 1;
return BSL_SUCCESS;
case BSL_ASN1_TAG_UTCTIME:
*len = BSL_ASN1_UTCTIME_LEN;
return BSL_SUCCESS;
case BSL_ASN1_TAG_GENERALIZEDTIME:
*len = BSL_ASN1_GENERALIZEDTIME_LEN;
return BSL_SUCCESS;
case BSL_ASN1_TAG_BMPSTRING:
if (asn->len > UINT32_MAX / 2) { // 2: Each character is 2 bytes
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
*len = asn->len * 2; // 2: Each character is 2 bytes
return BSL_SUCCESS;
default:
*len = asn->len;
return BSL_SUCCESS;
}
}
static int32_t ComputeOctetNum(bool optional, BSL_ASN1_EncodeItem *item, BSL_ASN1_Buffer *asn)
{
if (optional && asn->len == 0 && (asn->tag != BSL_ASN1_TAG_NULL)) {
return BSL_SUCCESS;
}
uint32_t contentOctetNum = 0;
if (asn->len != 0) {
int32_t ret = GetContentLen(asn, &contentOctetNum);
if (ret != BSL_SUCCESS) {
return ret;
}
}
item->lenOctetNum = GetLenOctetNum(contentOctetNum);
uint64_t tmp = (uint64_t)item->lenOctetNum + contentOctetNum;
if (tmp > UINT32_MAX - 1) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
item->asnOctetNum = 1 + item->lenOctetNum + contentOctetNum;
return BSL_SUCCESS;
}
static int32_t ComputeConstructAsnOctetNum(bool optional, BSL_ASN1_TemplateItem *templ, BSL_ASN1_EncodeItem *item,
uint32_t itemNum, uint32_t curIdx)
{
uint8_t curDepth = templ[curIdx].depth;
uint32_t contentOctetNum = 0;
for (uint32_t i = curIdx + 1; i < itemNum && templ[i].depth != curDepth; i++) {
if (templ[i].depth - curDepth == 1) {
if (item[i].asnOctetNum > UINT32_MAX - contentOctetNum) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
contentOctetNum += item[i].asnOctetNum;
}
}
if (contentOctetNum == 0 && optional) {
return BSL_SUCCESS;
}
item[curIdx].lenOctetNum = GetLenOctetNum(contentOctetNum);
// Use 64-bit math to prevent overflow during calculation
uint64_t totalLen = (uint64_t)item[curIdx].lenOctetNum + contentOctetNum;
// Check for 32-bit overflow (ASN.1 length must fit in uint32_t)
if (totalLen > UINT32_MAX - 1) { // -1 accounts for tag byte
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
item[curIdx].asnOctetNum = 1 + item[curIdx].lenOctetNum + contentOctetNum;
return BSL_SUCCESS;
}
/**
* ASN.1 Encode Init Item Content:
* 1. Reverse traversal template items (from deepest to root node)
* 2. Process two types:
* - Construct type (SEQUENCE/SET): Calculate total length of contained sub-items
* - Basic type: Validate tag and calculate encoding length
*/
static int32_t EncodeInitItemContent(BSL_ASN1_EncodeItem *eItems, BSL_ASN1_TemplateItem *tItems, uint32_t itemNum,
BSL_ASN1_Buffer *asnArr, uint32_t *asnNum)
{
int64_t asnIdx = (int64_t)*asnNum - 1;
uint8_t lastDepth = 0;
int32_t ret;
for (int64_t i = itemNum - 1; i >= 0; i--) {
if (eItems[i].skip == 1) {
continue;
}
if (tItems[i].depth < lastDepth) {
eItems[i].tag = tItems[i].tag;
ret = ComputeConstructAsnOctetNum(eItems[i].optional, tItems, eItems, itemNum, i);
if (ret != BSL_SUCCESS) {
return ret;
}
} else {
if (asnIdx < 0) {
return BSL_ASN1_ERR_ENCODE_ASN_LACK;
}
if (eItems[i].optional == false && asnArr[asnIdx].tag != tItems[i].tag && !IsAnyOrChoice(tItems[i].tag)) {
return BSL_ASN1_ERR_TAG_EXPECTED;
}
ret = ComputeOctetNum(eItems[i].optional, eItems + i, asnArr + asnIdx);
if (ret != BSL_SUCCESS) {
return ret;
}
eItems[i].tag = asnArr[asnIdx].tag;
eItems[i].asn = asnArr + asnIdx; // Shallow copy.
asnIdx--;
}
lastDepth = tItems[i].depth;
}
*asnNum = asnIdx + 1; // Update the number of used ASN buffers
return BSL_SUCCESS;
}
static void EncodeNumber(uint64_t data, uint32_t encodeLen, uint8_t *encode, uint32_t *offset)
{
uint64_t tmp = data;
/* Encode from back to front. */
uint32_t initOff = *offset + encodeLen - 1;
for (uint32_t i = 0; i < encodeLen; i++) {
*(encode + initOff - i) = (uint8_t)tmp;
tmp >>= 8; // one byte = 8 bits
}
*offset += encodeLen;
}
static void EncodeLength(uint8_t lenOctetNum, uint32_t contentOctetNum, uint8_t *encode, uint32_t *offset)
{
if (contentOctetNum <= BSL_ASN1_DEFINITE_MAX_CONTENT_OCTET_NUM) {
*(encode + *offset) = (uint8_t)contentOctetNum;
*offset += 1;
return;
}
// the initial octet
*(encode + *offset) = BSL_ASN1_INDEFINITE_LENGTH | (lenOctetNum - 1);
*offset += 1;
// the subsequent octets
EncodeNumber(contentOctetNum, lenOctetNum - 1, encode, offset);
}
static inline void EncodeBool(bool *data, uint8_t *encode, uint32_t *offset)
{
*(encode + *offset) = *data == true ? 0xFF : 0x00;
*offset += 1;
}
static void EncodeBitString(BSL_ASN1_BitString *data, uint32_t encodeLen, uint8_t *encode, uint32_t *offset)
{
*(encode + *offset) = data->unusedBits;
for (uint32_t i = 0; i < encodeLen - 1; i++) {
*(encode + *offset + i + 1) = *(data->buff + i);
}
// Last octet: Set unused bits to 0
*(encode + *offset + encodeLen - 1) >>= data->unusedBits;
*(encode + *offset + encodeLen - 1) <<= data->unusedBits;
*offset += encodeLen;
}
static void EncodeNum2Ascii(uint8_t *encode, uint32_t *offset, uint8_t encodeLen, uint16_t number)
{
uint16_t tmp = number;
/* Encode from back to front. */
uint32_t initOff = *offset + encodeLen - 1;
for (uint32_t i = 0; i < encodeLen; i++) {
*(encode + initOff - i) = tmp % 10 + '0'; // 10: Take the lowest digit of a decimal number.
tmp /= 10; // 10: Get the number in decimal except for the lowest bit.
}
*offset += encodeLen;
}
static void EncodeTime(BSL_TIME *time, uint8_t tag, uint8_t *encode, uint32_t *offset)
{
if (tag == BSL_ASN1_TAG_UTCTIME) {
EncodeNum2Ascii(encode, offset, 2, time->year % 100); // 2: YY, %100: Get the lower 2 digits of the number
} else {
EncodeNum2Ascii(encode, offset, 4, time->year); // 4: YYYY
}
EncodeNum2Ascii(encode, offset, 2, time->month); // 2: MM
EncodeNum2Ascii(encode, offset, 2, time->day); // 2: DD
EncodeNum2Ascii(encode, offset, 2, time->hour); // 2: HH
EncodeNum2Ascii(encode, offset, 2, time->minute); // 2: MM
EncodeNum2Ascii(encode, offset, 2, time->second); // 2: SS
*(encode + *offset) = 'Z';
*offset += 1;
}
static void EncodeInt(BSL_ASN1_Buffer *asn, uint32_t encodeLen, uint8_t *encode, uint32_t *offset)
{
if (encodeLen < asn->len) {
/* Skip the copying of high-order octets with all zeros. */
(void)memcpy_s(encode + *offset, encodeLen, asn->buff + (asn->len - encodeLen), encodeLen);
} else {
/* the high bit of positive number octet is 1 */
(void)memcpy_s(encode + *offset + (encodeLen - asn->len), asn->len, asn->buff, asn->len);
}
*offset += encodeLen;
}
static void EncodeContent(BSL_ASN1_Buffer *asn, uint32_t encodeLen, uint8_t *encode, uint32_t *offset)
{
switch (asn->tag) {
case BSL_ASN1_TAG_BOOLEAN:
EncodeBool((bool *)asn->buff, encode, offset);
return;
case BSL_ASN1_TAG_INTEGER:
case BSL_ASN1_TAG_ENUMERATED:
EncodeInt(asn, encodeLen, encode, offset);
return;
case BSL_ASN1_TAG_BITSTRING:
EncodeBitString((BSL_ASN1_BitString *)asn->buff, encodeLen, encode, offset);
return;
case BSL_ASN1_TAG_UTCTIME:
case BSL_ASN1_TAG_GENERALIZEDTIME:
EncodeTime((BSL_TIME *)asn->buff, asn->tag, encode, offset);
return;
case BSL_ASN1_TAG_BMPSTRING:
EncodeBMPString(asn->buff, asn->len, encode, offset);
return;
default:
(void)memcpy_s(encode + *offset, encodeLen, asn->buff, encodeLen);
*offset += encodeLen;
return;
}
}
static void EncodeItem(BSL_ASN1_EncodeItem *eItems, uint32_t itemNum, uint8_t *encode)
{
uint8_t *temp = encode;
uint32_t offset = 0;
uint32_t contentOctetNum;
for (uint32_t i = 0; i < itemNum; i++) {
if (eItems[i].asnOctetNum == 0) {
continue;
}
contentOctetNum = eItems[i].asnOctetNum - 1 - eItems[i].lenOctetNum;
/* tag */
*(temp + offset) = eItems[i].tag;
offset += 1;
/* length */
EncodeLength(eItems[i].lenOctetNum, contentOctetNum, encode, &offset);
/* content */
if (contentOctetNum != 0 && eItems[i].asn != NULL && eItems[i].asn->len != 0) {
EncodeContent(eItems[i].asn, contentOctetNum, encode, &offset);
}
}
}
static int32_t CheckBslTime(BSL_ASN1_Buffer *asn)
{
if (asn->len != sizeof(BSL_TIME)) {
return BSL_ASN1_ERR_CHECK_TIME;
}
BSL_TIME *time = (BSL_TIME *)asn->buff;
if (BSL_DateTimeCheck(time) == false) {
return BSL_ASN1_ERR_CHECK_TIME;
}
if (asn->tag == BSL_ASN1_TAG_UTCTIME && (time->year < 2000 || time->year > 2049)) { // Utc time range: [2000, 2049]
return BSL_ASN1_ERR_ENCODE_UTC_TIME;
}
if (asn->tag == BSL_ASN1_TAG_GENERALIZEDTIME &&
time->year > 9999) { // 9999: The number of digits for year must be 4.
return BSL_ASN1_ERR_ENCODE_GENERALIZED_TIME;
}
return BSL_SUCCESS;
}
static int32_t CheckBMPString(BSL_ASN1_Buffer *asn)
{
for (uint32_t i = 0; i < asn->len; i++) {
if (asn->buff[i] > 127) { // max ascii 127.
return BSL_INVALID_ARG;
}
}
return BSL_SUCCESS;
}
static int32_t CheckAsn(BSL_ASN1_Buffer *asn)
{
switch (asn->tag) {
case BSL_ASN1_TAG_BOOLEAN:
return asn->len != sizeof(bool) ? BSL_ASN1_ERR_ENCODE_BOOL : BSL_SUCCESS;
case BSL_ASN1_TAG_BITSTRING:
if (asn->len != sizeof(BSL_ASN1_BitString)) {
return BSL_ASN1_ERR_ENCODE_BIT_STRING;
}
BSL_ASN1_BitString *bs = (BSL_ASN1_BitString *)asn->buff;
return bs->unusedBits > BSL_ASN1_VAL_MAX_BIT_STRING_LEN ? BSL_ASN1_ERR_ENCODE_BIT_STRING : BSL_SUCCESS;
case BSL_ASN1_TAG_UTCTIME:
case BSL_ASN1_TAG_GENERALIZEDTIME:
return CheckBslTime(asn);
case BSL_ASN1_TAG_BMPSTRING:
return CheckBMPString(asn);
default:
return BSL_SUCCESS;
}
}
static int32_t CheckAsnArr(BSL_ASN1_Buffer *asnArr, uint32_t arrNum)
{
int32_t ret;
for (uint32_t i = 0; i < arrNum; i++) {
if (asnArr[i].buff != NULL) {
ret = CheckAsn(asnArr + i);
if (ret != BSL_SUCCESS) {
return ret;
}
}
}
return BSL_SUCCESS;
}
static int32_t EncodeItemInit(BSL_ASN1_EncodeItem *eItems, BSL_ASN1_TemplateItem *tItems, uint32_t itemNum,
BSL_ASN1_Buffer *asnArr, uint32_t *arrNum)
{
int32_t ret = EncodeInitItemFlag(eItems, tItems, itemNum);
if (ret != BSL_SUCCESS) {
return ret;
}
return EncodeInitItemContent(eItems, tItems, itemNum, asnArr, arrNum);
}
static int32_t EncodeInit(BSL_ASN1_EncodeItem *eItems, BSL_ASN1_Template *templ, BSL_ASN1_Buffer *asnArr,
uint32_t arrNum, uint32_t *encodeLen)
{
uint32_t tempArrNum = arrNum;
uint32_t stBegin;
uint32_t stEnd = templ->templNum - 1;
int32_t ret;
uint32_t i = templ->templNum;
while (i-- > 0) {
if (templ->templItems[i].depth > BSL_ASN1_MAX_TEMPLATE_DEPTH) {
return BSL_ASN1_ERR_MAX_DEPTH;
}
if (templ->templItems[i].depth != 0) {
continue;
}
stBegin = i;
ret = EncodeItemInit(eItems + stBegin, templ->templItems + stBegin, stEnd - stBegin + 1, asnArr, &tempArrNum);
if (ret != BSL_SUCCESS) {
return ret;
}
if ((eItems + stBegin)->asnOctetNum > UINT32_MAX - *encodeLen) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
*encodeLen += (eItems + stBegin)->asnOctetNum;
stEnd = i - 1;
}
if (tempArrNum != 0) { // Check whether all the asn-item has been used.
return BSL_ASN1_ERR_ENCODE_ASN_TOO_MUCH;
}
return BSL_SUCCESS;
}
int32_t BSL_ASN1_EncodeTemplate(BSL_ASN1_Template *templ, BSL_ASN1_Buffer *asnArr, uint32_t arrNum, uint8_t **encode,
uint32_t *encLen)
{
if (IsInvalidTempl(templ) || IsInvalidAsns(asnArr, arrNum) || encode == NULL || *encode != NULL || encLen == NULL) {
return BSL_INVALID_ARG;
}
int32_t ret = CheckAsnArr(asnArr, arrNum);
if (ret != BSL_SUCCESS) {
return ret;
}
BSL_ASN1_EncodeItem *eItems = (BSL_ASN1_EncodeItem *)BSL_SAL_Calloc(templ->templNum, sizeof(BSL_ASN1_EncodeItem));
if (eItems == NULL) {
return BSL_MALLOC_FAIL;
}
uint32_t encodeLen = 0;
ret = EncodeInit(eItems, templ, asnArr, arrNum, &encodeLen);
if (ret != BSL_SUCCESS) {
BSL_SAL_Free(eItems);
return ret;
}
*encode = (uint8_t *)BSL_SAL_Calloc(1, encodeLen);
if (*encode == NULL) {
BSL_SAL_Free(eItems);
return BSL_MALLOC_FAIL;
}
EncodeItem(eItems, templ->templNum, *encode);
*encLen = encodeLen;
BSL_SAL_Free(eItems);
return BSL_SUCCESS;
}
int32_t BSL_ASN1_EncodeListItem(uint8_t tag, uint32_t listSize, BSL_ASN1_Template *templ, BSL_ASN1_Buffer *asnArr,
uint32_t arrNum, BSL_ASN1_Buffer *out)
{
if ((tag != BSL_ASN1_TAG_SEQUENCE && tag != BSL_ASN1_TAG_SET) || IsInvalidTempl(templ) ||
IsInvalidAsns(asnArr, arrNum) || listSize == 0 || arrNum % listSize != 0 || out == NULL || out->buff != NULL) {
return BSL_INVALID_ARG;
}
int32_t ret = CheckAsnArr(asnArr, arrNum);
if (ret != BSL_SUCCESS) {
return ret;
}
if (listSize > UINT32_MAX / templ->templNum) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
BSL_ASN1_EncodeItem *eItems =
(BSL_ASN1_EncodeItem *)BSL_SAL_Calloc(templ->templNum * listSize, sizeof(BSL_ASN1_EncodeItem));
if (eItems == NULL) {
return BSL_MALLOC_FAIL;
}
uint32_t encodeLen = 0;
uint32_t itemAsnNum;
for (uint32_t i = 0; i < listSize; i++) {
itemAsnNum = arrNum / listSize;
ret = EncodeItemInit(
eItems + i * templ->templNum, templ->templItems, templ->templNum, asnArr + i * itemAsnNum, &itemAsnNum);
if (ret != BSL_SUCCESS) {
BSL_SAL_Free(eItems);
return ret;
}
if (itemAsnNum != 0) {
BSL_SAL_Free(eItems);
return BSL_ASN1_ERR_ENCODE_ASN_TOO_MUCH;
}
if (eItems[i * templ->templNum].asnOctetNum > UINT32_MAX - encodeLen) {
BSL_SAL_Free(eItems);
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
encodeLen += eItems[i * templ->templNum].asnOctetNum;
}
out->buff = (uint8_t *)BSL_SAL_Calloc(1, encodeLen);
if (out->buff == NULL) {
BSL_SAL_Free(eItems);
return BSL_MALLOC_FAIL;
}
uint8_t *encode = out->buff;
for (uint32_t i = 0; i < listSize; i++) {
EncodeItem(eItems + i * templ->templNum, templ->templNum, encode);
encode += (eItems + i * templ->templNum)->asnOctetNum;
}
out->tag = tag | BSL_ASN1_TAG_CONSTRUCTED;
out->len = encodeLen;
BSL_SAL_Free(eItems);
return BSL_SUCCESS;
}
int32_t BSL_ASN1_EncodeLimb(uint8_t tag, uint64_t limb, BSL_ASN1_Buffer *asn)
{
if ((tag != BSL_ASN1_TAG_INTEGER && tag != BSL_ASN1_TAG_ENUMERATED) || asn == NULL || asn->buff != NULL) {
return BSL_INVALID_ARG;
}
asn->tag = tag;
asn->len = limb == 0 ? 1 : GetOctetNumOfUint(limb);
asn->buff = (uint8_t *)BSL_SAL_Calloc(1, asn->len);
if (asn->buff == NULL) {
return BSL_MALLOC_FAIL;
}
if (limb == 0) {
return BSL_SUCCESS;
}
uint32_t offset = 0;
EncodeNumber(limb, asn->len, asn->buff, &offset);
return BSL_SUCCESS;
}
int32_t BSL_ASN1_GetEncodeLen(uint32_t contentLen, uint32_t *encodeLen)
{
if (encodeLen == NULL) {
return BSL_NULL_INPUT;
}
uint8_t lenOctetNum = GetLenOctetNum(contentLen);
if (contentLen > (UINT32_MAX - lenOctetNum - 1)) {
return BSL_ASN1_ERR_LEN_OVERFLOW;
}
*encodeLen = 1 + lenOctetNum + contentLen;
return BSL_SUCCESS;
}
| 2302_82127028/openHiTLS-examples_5062 | bsl/asn1/src/bsl_asn1.c | C | unknown | 43,813 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef BSL_ASN1_LOCAL_H
#define BSL_ASN1_LOCAL_H
#include <stdint.h>
#include <stdlib.h>
#include "bsl_asn1_internal.h"
#ifdef __cplusplus
extern "C" {
#endif
#define BSL_ASN1_VAL_MAX_BIT_STRING_LEN 7
#define BSL_ASN1_MAX_LIST_NEST_EPTH 2
#define BSL_ASN1_FLAG_OPTIONAL_DEFAUL (BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_DEFAULT)
/* Gets the mask of the class */
#define BSL_ASN1_CLASS_MASK 0xC0
typedef struct _ASN1_AnyOrChoiceParam {
uint32_t idx;
void *previousAsnOrTag;
BSL_ASN1_DecTemplCallBack tagCb;
} BSL_ASN1_AnyOrChoiceParam;
typedef struct _BSL_ASN1_EncodeItem {
uint32_t asnOctetNum; // tag + len + content
BSL_ASN1_Buffer *asn;
uint8_t tag;
uint8_t depth;
uint8_t skip; // Whether to skip processing template item
uint8_t optional;
uint8_t lenOctetNum; // The maximum number of the length octets is 126 + 1
} BSL_ASN1_EncodeItem;
#ifdef __cplusplus
}
#endif
#endif // BSL_ASN1_LOCAL_H
| 2302_82127028/openHiTLS-examples_5062 | bsl/asn1/src/bsl_asn1_local.h | C | unknown | 1,498 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef BSL_BASE64_INTERNAL_H
#define BSL_BASE64_INTERNAL_H
#include "hitls_build.h"
#ifdef HITLS_BSL_BASE64
#include "bsl_base64.h"
#ifdef __cplusplus
extern "C" {
#endif
struct BASE64_ControlBlock {
/* size of the unencoded block in the current buffer */
uint32_t num;
/*
* Size of the block for internal encoding and decoding.
* The size of the coding block is set to 48, and the size of the decoding block is set to 64.
*/
uint32_t length;
/* see BSL_BASE64_FLAGS*, for example: BSL_BASE64_FLAGS_NO_NEWLINE, means process without '\n' */
uint32_t flags;
uint32_t paddingCnt;
/* codec buffer */
uint8_t buf[HITLS_BASE64_CTX_BUF_LENGTH];
};
#define BASE64_ENCODE_BYTES 3 // encode 3 bytes at a time
#define BASE64_DECODE_BYTES 4 // decode 4 bytes at a time
#define BASE64_BLOCK_SIZE 1024
#define BASE64_PAD_MAX 2
#define BASE64_DECODE_BLOCKSIZE 64
#define BASE64_CTX_BUF_SIZE HITLS_BASE64_ENCODE_LENGTH(BASE64_BLOCK_SIZE) + 10
#define BSL_BASE64_ENC_ENOUGH_LEN(len) (((len) + 2) / 3 * 4 + 1)
#define BSL_BASE64_DEC_ENOUGH_LEN(len) (((len) + 3) / 4 * 3)
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* HITLS_BSL_BASE64 */
#endif /* conditional include */ | 2302_82127028/openHiTLS-examples_5062 | bsl/base64/include/bsl_base64_internal.h | C | unknown | 1,765 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_BSL_BASE64
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "securec.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "bsl_sal.h"
#include "bsl_base64_internal.h"
#include "bsl_base64.h"
/* BASE64 mapping table */
static const uint8_t BASE64_DECODE_MAP_TABLE[] = {
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 64U, 67U, 67U, 64U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 64U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 62U, 67U, 66U,
67U, 63U, 52U, 53U, 54U, 55U, 56U, 57U, 58U, 59U, 60U, 61U, 67U, 67U, 67U, 65U, 67U, 67U, 67U, 0U, 1U, 2U, 3U,
4U, 5U, 6U, 7U, 8U, 9U, 10U, 11U, 12U, 13U, 14U, 15U, 16U, 17U, 18U, 19U, 20U, 21U, 22U, 23U, 24U, 25U, 67U,
67U, 67U, 67U, 67U, 67U, 26U, 27U, 28U, 29U, 30U, 31U, 32U, 33U, 34U, 35U, 36U, 37U, 38U, 39U, 40U, 41U, 42U, 43U,
44U, 45U, 46U, 47U, 48U, 49U, 50U, 51U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U, 67U,
67U, 67U, 67U};
BSL_Base64Ctx *BSL_BASE64_CtxNew(void)
{
return BSL_SAL_Malloc(sizeof(BSL_Base64Ctx));
}
void BSL_BASE64_CtxFree(BSL_Base64Ctx *ctx)
{
BSL_SAL_FREE(ctx);
}
void BSL_BASE64_CtxClear(BSL_Base64Ctx *ctx)
{
BSL_SAL_CleanseData(ctx, (uint32_t)sizeof(BSL_Base64Ctx));
}
static int32_t BslBase64EncodeParamsValidate(const uint8_t *srcBuf, const uint32_t srcBufLen,
const char *dstBuf, uint32_t *dstBufLen)
{
if (srcBuf == NULL || srcBufLen == 0U || dstBuf == NULL || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
/* The length of dstBuf of the user must be at least (srcBufLen+2)/3*4+1 */
if (*dstBufLen < BSL_BASE64_ENC_ENOUGH_LEN(srcBufLen)) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
return BSL_SUCCESS;
}
static void BslBase64ArithEncodeProc(const uint8_t *srcBuf, const uint32_t srcBufLen,
char *dstBuf, uint32_t *dstBufLen)
{
/* base64-encoding mapping table */
static const char *base64Letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
uint32_t dstIdx = 0U;
const uint8_t *tmpBuf = srcBuf;
uint32_t tmpLen;
/* @alias Encode characters based on the BASE64 encoding rule. */
for (tmpLen = srcBufLen; tmpLen > 2U; tmpLen -= 3U) {
dstBuf[dstIdx] = base64Letter[(tmpBuf[0] >> 2U) & 0x3FU];
dstIdx++;
dstBuf[dstIdx] = base64Letter[((tmpBuf[0] & 0x3U) << 4U) | ((tmpBuf[1U] & 0xF0U) >> 4U)];
dstIdx++;
dstBuf[dstIdx] = base64Letter[((tmpBuf[1U] & 0x0FU) << 2U) | ((tmpBuf[2U] & 0xC0U) >> 6U)];
dstIdx++;
dstBuf[dstIdx] = base64Letter[tmpBuf[2U] & 0x3FU];
dstIdx++;
tmpBuf = &tmpBuf[3U];
}
/* Handle the case where the remaining length is not 0. */
if (tmpLen > 0U) {
/* Padded the first byte. */
dstBuf[dstIdx] = base64Letter[(tmpBuf[0] >> 2U) & 0x3FU];
dstIdx++;
if (tmpLen == 1U) {
/* Process the case where the remaining length is 1. */
dstBuf[dstIdx] = base64Letter[((tmpBuf[0U] & 0x3U) << 4U)];
dstIdx++;
dstBuf[dstIdx] = '=';
dstIdx++;
} else {
/* Process the case where the remaining length is 2. */
dstBuf[dstIdx] = base64Letter[((tmpBuf[0U] & 0x3U) << 4U) | ((tmpBuf[1U] & 0xF0U) >> 4U)];
dstIdx++;
dstBuf[dstIdx] = base64Letter[((tmpBuf[1U] & 0x0Fu) << 2U)];
dstIdx++;
}
/* Fill the last '='. */
dstBuf[dstIdx++] = '=';
}
/* Fill terminator. */
dstBuf[dstIdx] = '\0';
*dstBufLen = dstIdx;
}
/* Encode the entire ctx->buf, 48 characters in total, and return the number of decoded characters. */
static void BslBase64EncodeBlock(BSL_Base64Ctx *ctx, const uint8_t **srcBuf, uint32_t *srcBufLen,
char **dstBuf, uint32_t *dstBufLen, uint32_t remainLen)
{
uint32_t tmpOutLen = 0;
uint32_t offset = 0;
BslBase64ArithEncodeProc(*srcBuf, ctx->length, *dstBuf, &tmpOutLen);
ctx->num = 0;
offset = ((remainLen == 0) ? (ctx->length) : remainLen);
*srcBuf += offset;
*srcBufLen -= offset;
*dstBufLen += tmpOutLen;
*dstBuf += tmpOutLen;
if ((ctx->flags & BSL_BASE64_FLAGS_NO_NEWLINE) == 0) {
*(*dstBuf) = '\n';
(*dstBuf)++;
(*dstBufLen)++;
}
*(*dstBuf) = '\0';
}
static void BslBase64EncodeProcess(BSL_Base64Ctx *ctx, const uint8_t **srcBuf, uint32_t *srcBufLen,
char *dstBuf, uint32_t *dstBufLen)
{
uint32_t remainLen = 0;
const uint8_t *bufTmp = &(ctx->buf[0]);
char *dstBufTmp = dstBuf;
if (ctx->num != 0) {
remainLen = ctx->length - ctx->num;
(void)memcpy_s(&(ctx->buf[ctx->num]), remainLen, *srcBuf, remainLen);
BslBase64EncodeBlock(ctx, &bufTmp, srcBufLen, &dstBufTmp, dstBufLen, remainLen);
*srcBuf += remainLen;
remainLen = 0;
}
const uint8_t *srcBufTmp = *srcBuf;
/* Encoding every 48 characters. */
while (*srcBufLen >= ctx->length) {
BslBase64EncodeBlock(ctx, &srcBufTmp, srcBufLen, &dstBufTmp, dstBufLen, remainLen);
}
*srcBuf = srcBufTmp;
}
static int32_t BslBase64DecodeCheck(const char src, uint32_t *paddingCnt)
{
uint32_t padding = 0;
/* 66U is the header identifier '-' (invalid), and 66U or above are invalid characters beyond the range. */
if (BASE64_DECODE_MAP_TABLE[(uint8_t)src] == 66U) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_HEADER);
return BSL_BASE64_HEADER;
}
if (BASE64_DECODE_MAP_TABLE[(uint8_t)src] > 66U) {
BSL_ERR_PUSH_ERROR(BSL_INVALID_ARG);
return BSL_INVALID_ARG;
}
/* 65U is the padding character '=' and also EOF identifier. */
if (BASE64_DECODE_MAP_TABLE[(uint8_t)src] == 65U) {
if (*paddingCnt < BASE64_PAD_MAX) {
padding++;
} else { /* paddingCnt > 2 */
BSL_ERR_PUSH_ERROR(BSL_BASE64_INVALID);
return BSL_BASE64_INVALID;
}
}
/* illegal behavior: data after padding. */
if (*paddingCnt > 0 && BASE64_DECODE_MAP_TABLE[(uint8_t)src] < 64U) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_DATA_AFTER_PADDING);
return BSL_BASE64_DATA_AFTER_PADDING;
}
*paddingCnt += padding;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_Encode(const uint8_t *srcBuf, const uint32_t srcBufLen, char *dstBuf, uint32_t *dstBufLen)
{
int32_t ret = BslBase64EncodeParamsValidate(srcBuf, srcBufLen, (const char *)dstBuf, dstBufLen);
if (ret != BSL_SUCCESS) {
return ret;
}
BslBase64ArithEncodeProc(srcBuf, srcBufLen, dstBuf, dstBufLen); /* executes the encoding algorithm */
return BSL_SUCCESS;
}
static void BslBase64DecodeRemoveBlank(const uint8_t *buf, const uint32_t bufLen, uint8_t *destBuf, uint32_t *destLen)
{
uint32_t fast = 0;
uint32_t slow = 0;
for (; fast < bufLen; fast++) {
if (BASE64_DECODE_MAP_TABLE[buf[fast]] != 64U) { /* when the character is not ' ' or '\r', '\n' */
destBuf[slow++] = buf[fast];
}
}
*destLen = slow;
}
static int32_t BslBase64DecodeCheckAndRmvEqualSign(uint8_t *buf, uint32_t *bufLen)
{
int32_t ret = BSL_SUCCESS;
uint32_t i = 0;
bool hasEqualSign = false;
uint32_t len = *bufLen;
for (; i < len; i++) {
/* Check whether the characters are invalid characters in the Base64 mapping table. */
if (BASE64_DECODE_MAP_TABLE[buf[i]] > 65U) {
/* 66U is the status code of invalid characters. */
return BSL_BASE64_INVALID_CHARACTER;
}
/* Process the '=' */
if (BASE64_DECODE_MAP_TABLE[buf[i]] == 65U) {
hasEqualSign = true;
/* 65U is the status code with the '=' */
if (i == len - 1) {
break;
} else if (i == len - BASE64_PAD_MAX) {
ret = (buf[i + 1] == '=') ? BSL_SUCCESS : BSL_BASE64_INVALID_CHARACTER;
buf[i + 1] = '\0';
break;
} else {
return BSL_BASE64_INVALID_CHARACTER;
}
}
}
if (ret == BSL_SUCCESS) {
if (hasEqualSign == true) {
buf[i] = '\0';
}
*bufLen = i;
}
return ret;
}
static int32_t BslBase64Normalization(const char *srcBuf, const uint32_t srcBufLen, uint8_t *filterBuf,
uint32_t *filterBufLen)
{
(void)memset_s(filterBuf, *filterBufLen, 0, *filterBufLen);
BslBase64DecodeRemoveBlank((const uint8_t *)srcBuf, srcBufLen, filterBuf, filterBufLen);
if (*filterBufLen == 0 || ((*filterBufLen) % BASE64_DECODE_BYTES != 0)) {
return BSL_BASE64_INVALID_ENCODE;
}
return BslBase64DecodeCheckAndRmvEqualSign(filterBuf, filterBufLen);
}
/* can ensure that dstBuf and dstBufLen are sufficient and that srcBuf does not contain invalid characters */
static int32_t BslBase64DecodeBuffer(const uint8_t *srcBuf, const uint32_t srcBufLen, uint8_t *dstBuf,
uint32_t *dstBufLen)
{
uint32_t idx = 0U;
uint32_t tmpLen;
const uint8_t *tmp = srcBuf;
for (tmpLen = srcBufLen; tmpLen > 4U; tmpLen -= 4U) {
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[0U]] << 2U) | (BASE64_DECODE_MAP_TABLE[tmp[1U]] >> 4U);
idx++;
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[1U]] << 4U) | (BASE64_DECODE_MAP_TABLE[tmp[2U]] >> 2U);
idx++;
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[2U]] << 6U) | BASE64_DECODE_MAP_TABLE[tmp[3U]];
idx++;
tmp = &tmp[4U];
}
/* processing of less than four characters */
if (tmpLen > 1U) {
/* process the case of one character */
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[0U]] << 2U) | (BASE64_DECODE_MAP_TABLE[tmp[1U]] >> 4U);
idx++;
}
if (tmpLen > 2U) {
/* process the case of two characters */
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[1U]] << 4U) | (BASE64_DECODE_MAP_TABLE[tmp[2U]] >> 2U);
idx++;
}
if (tmpLen > 3U) {
/* process the case of three characters */
dstBuf[idx] = (BASE64_DECODE_MAP_TABLE[tmp[2U]] << 6U) | BASE64_DECODE_MAP_TABLE[tmp[3U]];
idx++;
}
*dstBufLen = idx;
return BSL_SUCCESS;
}
static int32_t BslBase64ArithDecodeProc(const char *srcBuf, const uint32_t srcBufLen, uint8_t *dstBuf,
uint32_t *dstBufLen)
{
uint8_t *buf = NULL;
uint32_t bufLen; /* length to be decoded after redundant characters are deleted */
int32_t ret;
buf = BSL_SAL_Malloc((uint32_t)srcBufLen);
if (buf == NULL) {
return BSL_MALLOC_FAIL;
}
bufLen = srcBufLen;
/* Delete the extra white space characters (\r\n, space, '=') */
ret = BslBase64Normalization(srcBuf, (const uint32_t)srcBufLen, buf, &bufLen);
if (ret != BSL_SUCCESS) {
BSL_SAL_FREE(buf);
return ret;
}
/* Decode the base64 character string. */
ret = BslBase64DecodeBuffer(buf, (const uint32_t)bufLen, dstBuf, dstBufLen);
if (ret != BSL_SUCCESS) {
BSL_SAL_FREE(buf);
return ret;
}
BSL_SAL_FREE(buf);
return BSL_SUCCESS;
}
/* Ensure that dstBuf and dstBufLen are correctly created. */
int32_t BSL_BASE64_Decode(const char *srcBuf, const uint32_t srcBufLen, uint8_t *dstBuf, uint32_t *dstBufLen)
{
int32_t ret;
/* An error is returned when a parameter is abnormal. */
if (srcBuf == NULL || dstBuf == NULL || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
/* The length of dstBuf of the user must be at least (srcBufLen+3)/4*3. */
if (*dstBufLen < BSL_BASE64_DEC_ENOUGH_LEN(srcBufLen)) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
ret = BslBase64ArithDecodeProc(srcBuf, srcBufLen, dstBuf, dstBufLen); /* start decoding */
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
return ret;
}
int32_t BSL_BASE64_EncodeInit(BSL_Base64Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
ctx->length = HITLS_BASE64_CTX_LENGTH;
ctx->num = 0;
ctx->flags = 0;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_EncodeUpdate(BSL_Base64Ctx *ctx, const uint8_t *srcBuf, uint32_t srcBufLen,
char *dstBuf, uint32_t *dstBufLen)
{
/* ensure the validity of dstBuf */
if (ctx == NULL || srcBuf == NULL || dstBuf == NULL || srcBufLen == 0 || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (ctx->length != HITLS_BASE64_CTX_LENGTH) {
BSL_ERR_PUSH_ERROR(BSL_INVALID_ARG);
return BSL_INVALID_ARG;
}
/* By default, the user selects the line feed, considers the terminator,
and checks whether the length meets the (srcBufLen + ctx->num)/48*65+1 requirement. */
if (*dstBufLen < ((srcBufLen + ctx->num) / HITLS_BASE64_CTX_LENGTH * (BASE64_DECODE_BLOCKSIZE + 1) + 1)) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
*dstBufLen = 0;
/* If srcBuf is too short for a buf, store it in the buf first. */
if (srcBufLen < ctx->length - ctx->num) {
(void)memcpy_s(&(ctx->buf[ctx->num]), srcBufLen, srcBuf, srcBufLen);
ctx->num += srcBufLen;
return BSL_SUCCESS;
}
BslBase64EncodeProcess(ctx, &srcBuf, &srcBufLen, dstBuf, dstBufLen);
/* If the remaining bytes are less than 48 bytes, store the bytes in the buf and wait for next processing. */
if (srcBufLen != 0) {
/* Ensure that srcBufLen < 48 */
(void)memcpy_s(&(ctx->buf[0]), srcBufLen, srcBuf, srcBufLen);
}
ctx->num = srcBufLen;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_EncodeFinal(BSL_Base64Ctx *ctx, char *dstBuf, uint32_t *dstBufLen)
{
uint32_t tmpDstLen = 0;
if (ctx == NULL || dstBuf == NULL || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (ctx->num == 0) {
*dstBufLen = 0;
return BSL_SUCCESS;
}
if (*dstBufLen < BSL_BASE64_ENC_ENOUGH_LEN((ctx->num))) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
BslBase64ArithEncodeProc((const uint8_t *)ctx->buf, ctx->num, dstBuf, &tmpDstLen);
if ((ctx->flags & BSL_BASE64_FLAGS_NO_NEWLINE) == 0) {
dstBuf[tmpDstLen++] = '\n';
}
dstBuf[tmpDstLen] = '\0';
*dstBufLen = tmpDstLen;
ctx->num = 0;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_DecodeInit(BSL_Base64Ctx *ctx)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
ctx->num = 0;
ctx->length = 0;
ctx->flags = 0;
ctx->paddingCnt = 0;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_DecodeUpdate(BSL_Base64Ctx *ctx, const char *srcBuf, const uint32_t srcBufLen,
uint8_t *dstBuf, uint32_t *dstBufLen)
{
if (ctx == NULL || srcBuf == NULL || dstBuf == NULL || srcBufLen == 0 || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
/* Estimated maximum value. By default, the input srcBuf is without line feed. Each line contains 64 characters.
Check whether the length meets the (srcBufLen + ctx->num)/64*48 requirement. */
if (*dstBufLen < ((srcBufLen + ctx->num) / BASE64_DECODE_BLOCKSIZE * HITLS_BASE64_CTX_LENGTH)) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
uint32_t num = ctx->num;
uint32_t totalLen = 0;
uint32_t decodeLen = 0;
uint8_t *tmpBuf = ctx->buf;
int32_t ret = BSL_SUCCESS;
uint8_t *dstTmp = dstBuf;
for (uint32_t i = 0U; i < srcBufLen; i++) {
ret = BslBase64DecodeCheck(srcBuf[i], &ctx->paddingCnt);
if (ret != BSL_SUCCESS) {
*dstBufLen = 0;
if (ret == BSL_BASE64_HEADER) {
*dstBufLen = totalLen;
}
return ret;
}
if (BASE64_DECODE_MAP_TABLE[(uint8_t)srcBuf[i]] < 64U) { /* 0U ~ 63U are valid characters */
/* If num >= 64, it indicates that someone has modified the ctx.
If this happens, refuse to write any more data. */
if (num >= BASE64_DECODE_BLOCKSIZE) {
*dstBufLen = 0;
ctx->num = num;
BSL_ERR_PUSH_ERROR(BSL_BASE64_ILLEGALLY_MODIFIED);
return BSL_BASE64_ILLEGALLY_MODIFIED;
}
tmpBuf[num++] = (uint8_t)srcBuf[i]; /* save valid base64 characters */
}
/* A round of block decoding is performed every time the num reaches 64, and then the buf is cleared. */
if (num == BASE64_DECODE_BLOCKSIZE) {
ret = BslBase64DecodeBuffer(tmpBuf, num, dstTmp, &decodeLen);
if (ret != BSL_SUCCESS) {
*dstBufLen = 0;
ctx->num = 0;
BSL_ERR_PUSH_ERROR(BSL_BASE64_DECODE_FAILED);
return BSL_BASE64_DECODE_FAILED;
}
num = 0;
totalLen += decodeLen;
dstTmp += decodeLen;
}
}
*dstBufLen = totalLen;
ctx->num = num;
return BSL_SUCCESS;
}
int32_t BSL_BASE64_DecodeFinal(BSL_Base64Ctx *ctx, uint8_t *dstBuf, uint32_t *dstBufLen)
{
int32_t ret = BSL_SUCCESS;
uint32_t totalLen = 0;
if (ctx == NULL || dstBuf == NULL || dstBufLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (ctx->num == 0) {
*dstBufLen = 0;
return ret;
}
if (*dstBufLen < BSL_BASE64_DEC_ENOUGH_LEN((ctx->num))) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_BUF_NOT_ENOUGH);
return BSL_BASE64_BUF_NOT_ENOUGH;
}
ret = BslBase64DecodeBuffer((const uint8_t *)ctx->buf, ctx->num, dstBuf, &totalLen);
ctx->num = 0;
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(BSL_BASE64_DECODE_FAILED);
return BSL_BASE64_DECODE_FAILED;
}
*dstBufLen = totalLen;
return ret;
}
int32_t BSL_BASE64_SetFlags(BSL_Base64Ctx *ctx, uint32_t flags)
{
if (ctx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
ctx->flags |= flags;
return BSL_SUCCESS;
}
#endif /* HITLS_BSL_BASE64 */
| 2302_82127028/openHiTLS-examples_5062 | bsl/base64/src/bsl_base64.c | C | unknown | 19,575 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef BSL_BUFFER_H
#define BSL_BUFFER_H
#include "hitls_build.h"
#ifdef HITLS_BSL_BUFFER
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
size_t length;
char *data;
size_t max;
} BSL_BufMem;
BSL_BufMem *BSL_BufMemNew(void);
void BSL_BufMemFree(BSL_BufMem *a);
size_t BSL_BufMemGrowClean(BSL_BufMem *str, size_t len);
#ifdef __cplusplus
}
#endif
#endif
#endif | 2302_82127028/openHiTLS-examples_5062 | bsl/buffer/include/bsl_buffer.h | C | unknown | 950 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_BSL_BUFFER
#include "securec.h"
#include "bsl_sal.h"
#include "bsl_buffer.h"
BSL_BufMem *BSL_BufMemNew(void)
{
BSL_BufMem *ret = NULL;
ret = (BSL_BufMem *)BSL_SAL_Malloc(sizeof(BSL_BufMem));
if (ret == NULL) {
return NULL;
}
ret->length = 0;
ret->max = 0;
ret->data = NULL;
return ret;
}
void BSL_BufMemFree(BSL_BufMem *a)
{
if (a == NULL) {
return;
}
if (a->data != NULL) {
BSL_SAL_FREE(a->data);
}
BSL_SAL_FREE(a);
}
size_t BSL_BufMemGrowClean(BSL_BufMem *str, size_t len)
{
char *ret = NULL;
if (str->length >= len) {
if (memset_s(&(str->data[len]), str->max - len, 0, str->length - len) != EOK) {
return 0;
}
str->length = len;
return len;
}
if (str->max >= len) {
if (memset_s(&(str->data[str->length]), str->max - str->length, 0, len - str->length) != EOK) {
return 0;
}
str->length = len;
return len;
}
const size_t n = ((len + 3) / 3) * 4; // actual growth size
if (n < len || n > UINT32_MAX) { // does not meet growth requirements or overflows
return 0;
}
ret = BSL_SAL_Malloc((uint32_t)n);
if (ret == NULL) {
return 0;
}
if (str->data != NULL && memcpy_s(ret, n, str->data, str->max) != EOK) {
BSL_SAL_FREE(ret);
return 0;
}
if (memset_s(&ret[str->length], n - str->length, 0, len - str->length) != EOK) {
BSL_SAL_FREE(ret);
return 0;
}
BSL_SAL_CleanseData(str->data, (uint32_t)str->max);
BSL_SAL_FREE(str->data);
str->data = ret;
str->max = n;
str->length = len;
return len;
}
#endif | 2302_82127028/openHiTLS-examples_5062 | bsl/buffer/src/bsl_buffer.c | C | unknown | 2,300 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef BSL_CONF_H
#define BSL_CONF_H
#include "hitls_build.h"
#ifdef HITLS_BSL_CONF
#include "bsl_conf_def.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct BSL_CONF_Struct {
const BSL_CONF_Method *meth;
void *data;
} BSL_CONF;
/**
* @ingroup bsl
*
* @brief Retrieves the default configuration management methods structure
*
* @return const BSL_CONF_Method* a pointer to the static structure containing the default methods
*
* @details
* The structure includes the following default methods:
* - `DefaultCreate`: Creates a new configuration object
* - `DefaultDestroy`: Destroys an existing configuration object
* - `DefaultLoad`: Loads configuration data from a file
* - `DefaultLoadUio`: Loads configuration data from a UIO interface
* - `DefaultDump`: Dumps configuration data to a file
* - `DefaultDumpUio`: Dumps configuration data to a UIO interface
* - `DefaultGetSectionNode`: Retrieves a specific section node from the configuration
* - `DefaultGetString`: Retrieves a string value from the configuration
* - `DefaultGetNumber`: Retrieves a numeric value from the configuration
* - `DefaultGetSectionNames`: Retrieves the names of all sections in the configuration
*
*/
const BSL_CONF_Method *BSL_CONF_DefaultMethod(void);
/**
* @ingroup bsl
*
* @brief Create a new configuration object.
*
* @param meth [IN] Method structure defining the behavior of the configuration object
*
* @retval The configuration object is created successfully.
* @retval NULL Failed to create the configuration.
*/
BSL_CONF *BSL_CONF_New(const BSL_CONF_Method *meth);
/**
* @ingroup bsl
*
* @brief Free a configuration object.
*
* @param conf [IN] Configuration object to be freed
*/
void BSL_CONF_Free(BSL_CONF *conf);
/**
* @ingroup bsl
*
* @brief Load configuration information from a UIO object into the configuration object.
*
* @param conf [IN] Configuration object
* @param uio [IN] UIO object
*
* @retval BSL_SUCCESS Configuration loaded successfully.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf or uio is NULL).
* @retval BSL_CONF_LOAD_FAIL Failed to load configuration (e.g., loadUio method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_LoadByUIO(BSL_CONF *conf, BSL_UIO *uio);
/**
* @ingroup bsl
*
* @brief Load configuration information from a file into the configuration object.
*
* @param conf [IN] Configuration object
* @param file [IN] Configuration file path
*
* @retval BSL_SUCCESS Configuration loaded successfully.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf or file is NULL).
* @retval BSL_CONF_LOAD_FAIL Failed to load configuration (e.g., load method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_Load(BSL_CONF *conf, const char *file);
/**
* @ingroup bsl
*
* @brief Get a specific section from the configuration object.
*
* @param conf [IN] Configuration object
* @param section [IN] Section name to retrieve
*
* @retval BSL_LIST* a pointer to Section retrieved successfully.
* @retval NULL Failed to Get Section.
*/
BslList *BSL_CONF_GetSection(const BSL_CONF *conf, const char *section);
/**
* @ingroup bsl
*
* @brief Get a string value from the configuration object based on the specified section and name.
*
* @param conf [IN] Configuration object
* @param section [IN] Section name in the configuration
* @param name [IN] Name of the configuration item
* @param str [OUT] Buffer to store the retrieved string
* @param strLen [IN|OUT] Length of the buffer
*
* @retval BSL_SUCCESS String retrieved successfully.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf, section, name, str, or strLen is NULL).
* @retval BSL_CONF_GET_FAIL Failed to retrieve the string (e.g., getString method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_GetString(const BSL_CONF *conf, const char *section, const char *name, char *str, uint32_t *strLen);
/**
* @ingroup bsl
*
* @brief Get a numeric value from the configuration object based on the specified section and name.
*
* @param conf [IN] Configuration object
* @param section [IN] Section name in the configuration
* @param name [IN] Name of the configuration item
* @param value [OUT] Pointer to store the retrieved numeric value
*
* @retval BSL_SUCCESS Numeric value retrieved successfully.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf, section, name, or value is NULL).
* @retval BSL_CONF_GET_FAIL Failed to retrieve the numeric value (e.g., getNumber method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_GetNumber(const BSL_CONF *conf, const char *section, const char *name, long *value);
/**
* @ingroup bsl
*
* @brief Save the configuration object's contents to a specified file.
*
* @param conf [IN] Configuration object
* @param file [IN] File path to save the configuration
*
* @retval BSL_SUCCESS Configuration successfully saved to the file.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf or file is NULL).
* @retval BSL_CONF_DUMP_FAIL Failed to save the configuration (e.g., dump method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_Dump(const BSL_CONF *conf, const char *file);
/**
* @ingroup bsl
*
* @brief Save the configuration object's contents to a specified UIO object.
*
* @param conf [IN] Configuration object
* @param uio [IN] UIO object to save the configuration
*
* @retval BSL_SUCCESS Configuration successfully saved to the UIO.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf or uio is NULL).
* @retval BSL_CONF_DUMP_FAIL Failed to save the configuration (e.g., dumpUio method is missing or fails).
* @retval Other error code.
*/
int32_t BSL_CONF_DumpUio(const BSL_CONF *conf, BSL_UIO *uio);
/**
* @ingroup bsl
*
* @brief Get the names of all sections from the configuration object.
*
* @param conf [IN] Configuration object
* @param namesSize [OUT] Pointer to store the size of the returned array
*
* @retval BSL_SUCCESS Successfully retrieved section names.
* @retval BSL_NULL_INPUT Invalid input parameter (if conf or namesSize is NULL).
* @retval BSL_CONF_GET_FAIL Failed to retrieve section names (e.g., getSectionNames method is missing or fails).
* @retval char ** a pointer to the section names array, which is retrieved successfully.
* @retval NULL failed to get section names.
*/
char **BSL_CONF_GetSectionNames(const BSL_CONF *conf, uint32_t *namesSize);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_CONF */
#endif /* BSL_CONF_H */
| 2302_82127028/openHiTLS-examples_5062 | bsl/conf/include/bsl_conf.h | C | unknown | 7,124 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef BSL_CONF_DEF_H
#define BSL_CONF_DEF_H
#include "hitls_build.h"
#ifdef HITLS_BSL_CONF
#include <stdint.h>
#include "bsl_uio.h"
#include "bsl_list.h"
#ifdef __cplusplus
extern "C" {
#endif
#define BSL_CONF_LINE_SIZE 513
#define BSL_CONF_SEC_SIZE 510
typedef struct BslConfDefaultKeyValue {
char *key;
char *value;
uint32_t keyLen;
uint32_t valueLen;
} BSL_CONF_KeyValue;
typedef struct BslConfDefaultSection {
BslList *keyValueList;
char *section;
uint32_t sectionLen;
} BSL_CONF_Section;
/* LIST(BslList)_____SECTION1(BSL_CONF_Section)_____LIST(BslList)_______KEY1, VALUE(BSL_CONF_KeyValue)
* | |__KEY2, VALUE(BSL_CONF_KeyValue)
* | |__KEY3, VALUE(BSL_CONF_KeyValue)
* |
* |__SECTION2(BSL_CONF_Section)_____LIST(BslList)_______KEY1, VALUE(BSL_CONF_KeyValue)
* | |__KEY2, VALUE(BSL_CONF_KeyValue)
* ...
*/
typedef BslList *(*BslConfCreate)(void);
typedef void (*BslConfDestroy)(BslList *sectionList);
typedef int32_t (*BslConfLoad)(BslList *sectionList, const char *file);
typedef int32_t (*BslConfLoadUio)(BslList *sectionList, BSL_UIO *uio);
typedef int32_t (*BslConfDump)(BslList *sectionList, const char *file);
typedef int32_t (*BslConfDumpUio)(BslList *sectionList, BSL_UIO *uio);
typedef BslList *(*BslConfGetSection)(BslList *sectionList, const char *section);
typedef int32_t (*BslConfGetString)(BslList *sectionList, const char *section, const char *key,
char *string, uint32_t *strLen);
typedef int32_t (*BslConfGetNumber)(BslList *sectionList, const char *section, const char *key, long int *num);
typedef char **(*BslConfGetSectionNames)(BslList *sectionList, uint32_t *namesSize);
typedef struct BSL_CONF_MethodStruct {
BslConfCreate create;
BslConfDestroy destroy;
BslConfLoad load;
BslConfLoadUio loadUio;
BslConfDump dump;
BslConfDumpUio dumpUio;
BslConfGetSection getSection;
BslConfGetString getString;
BslConfGetNumber getNumber;
BslConfGetSectionNames getSectionNames;
} BSL_CONF_Method;
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_CONF */
#endif /* BSL_CONF_DEF_H */ | 2302_82127028/openHiTLS-examples_5062 | bsl/conf/include/bsl_conf_def.h | C | unknown | 2,872 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_BSL_CONF
#include "bsl_uio.h"
#include "bsl_sal.h"
#include "bsl_list.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "bsl_conf.h"
// Create a conf object based on BSL_CONF_Method
BSL_CONF *BSL_CONF_New(const BSL_CONF_Method *meth)
{
BSL_CONF *conf = (BSL_CONF *)BSL_SAL_Calloc(1, sizeof(BSL_CONF));
if (conf == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
if (meth == NULL) {
conf->meth = BSL_CONF_DefaultMethod();
} else {
conf->meth = meth;
}
if (conf->meth->create == NULL || conf->meth->destroy == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_INIT_FAIL);
BSL_SAL_FREE(conf);
return NULL;
}
conf->data = conf->meth->create();
if (conf->data == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
BSL_SAL_FREE(conf);
return NULL;
}
return conf;
}
// release conf resources
void BSL_CONF_Free(BSL_CONF *conf)
{
if (conf == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return;
}
if (conf->meth != NULL && conf->meth->destroy != NULL) {
conf->meth->destroy(conf->data);
conf->data = NULL;
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_FREE_FAIL);
}
BSL_SAL_FREE(conf);
return;
}
// Read the conf information from the UIO.
int32_t BSL_CONF_LoadByUIO(BSL_CONF *conf, BSL_UIO *uio)
{
if (conf == NULL || uio == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->loadUio != NULL) {
return conf->meth->loadUio(conf->data, uio);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_LOAD_FAIL);
return BSL_CONF_LOAD_FAIL;
}
}
// Read the conf information from the file.
int32_t BSL_CONF_Load(BSL_CONF *conf, const char *file)
{
if (conf == NULL || file == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->load != NULL) {
return conf->meth->load(conf->data, file);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_LOAD_FAIL);
return BSL_CONF_LOAD_FAIL;
}
}
// Return the BslList that consists of all BslListNodes that store the BSL_CONF_KeyValue with the same section name.
BslList *BSL_CONF_GetSection(const BSL_CONF *conf, const char *section)
{
if (conf == NULL || section == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return NULL;
}
if (conf->meth != NULL && conf->meth->getSection != NULL) {
return conf->meth->getSection(conf->data, section);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return NULL;
}
}
// Obtain the value string corresponding to the name in the specified section.
int32_t BSL_CONF_GetString(const BSL_CONF *conf, const char *section, const char *name, char *str, uint32_t *strLen)
{
if (conf == NULL || section == NULL || name == NULL || str == NULL || strLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->getString != NULL) {
return conf->meth->getString(conf->data, section, name, str, strLen);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
}
// Obtain the integer value corresponding to the name in the specified section.
int32_t BSL_CONF_GetNumber(const BSL_CONF *conf, const char *section, const char *name, long *value)
{
if (conf == NULL || section == NULL || name == NULL || value == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->getNumber != NULL) {
return conf->meth->getNumber(conf->data, section, name, value);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
}
// Dump config contents to file.
int32_t BSL_CONF_Dump(const BSL_CONF *conf, const char *file)
{
if (conf == NULL || file == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->dump != NULL) {
return conf->meth->dump(conf->data, file);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_DUMP_FAIL);
return BSL_CONF_DUMP_FAIL;
}
}
// Dump config contents to uio.
int32_t BSL_CONF_DumpUio(const BSL_CONF *conf, BSL_UIO *uio)
{
if (conf == NULL || uio == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
if (conf->meth != NULL && conf->meth->dumpUio != NULL) {
return conf->meth->dumpUio(conf->data, uio);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_DUMP_FAIL);
return BSL_CONF_DUMP_FAIL;
}
}
// Get section name array.
char **BSL_CONF_GetSectionNames(const BSL_CONF *conf, uint32_t *namesSize)
{
if (conf == NULL || namesSize == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return NULL;
}
if (conf->meth != NULL && conf->meth->getSectionNames != NULL) {
return conf->meth->getSectionNames(conf->data, namesSize);
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return NULL;
}
}
#endif /* HITLS_BSL_CONF */
| 2302_82127028/openHiTLS-examples_5062 | bsl/conf/src/bsl_conf.c | C | unknown | 5,797 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_BSL_CONF
#include <ctype.h>
#include <limits.h>
#include "securec.h"
#include "bsl_uio.h"
#include "bsl_sal.h"
#include "bsl_list.h"
#include "bsl_errno.h"
#include "bsl_err_internal.h"
#include "bsl_conf_def.h"
#define BREAK_FLAG 1
#define CONTINUE_FLAG 2
static int32_t IsNameValid(const char *name)
{
const char table[128] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, // ',' '.'
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, // '0'-'9' ';'
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'A'-'Z'
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // '_'
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 'a'-'z'
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
};
uint32_t nameLen = (uint32_t)strlen(name);
char pos = 0;
for (uint32_t i = 0; i < nameLen; i++) {
pos = name[i];
if (pos < 0 || table[(uint32_t)pos] != 1) { // invalid name.
return 0;
}
}
return 1;
}
static int32_t IsEscapeValid(char c)
{
char table[] = {
'#', ';', '$', '\\', '\"', '\''
};
uint32_t tableSize = (uint32_t)(sizeof(table) / sizeof(table[0]));
for (uint32_t i = 0; i < tableSize; i++) {
if (c == table[i]) {
return 1;
}
}
return 0;
}
static int32_t RemoveSpace(char *str)
{
if (str == NULL) {
return 0;
}
int32_t strLen = (int32_t)strlen(str);
if (strLen == 0) {
return 0;
}
int32_t head = 0;
int32_t tail = strLen - 1;
while (head <= tail) {
if (isspace((unsigned char)str[head])) {
head++;
} else {
break;
}
}
while (head <= tail) {
if (isspace((unsigned char)str[tail])) {
tail--;
} else {
break;
}
}
int32_t realLen = tail - head + 1;
if (realLen > 0) {
(void)memmove_s(str, strLen, str + head, realLen);
}
str[realLen] = '\0';
return realLen;
}
// Parses a string enclosed within quotes, handling escape sequences appropriately.
static int32_t ParseQuote(char *str, char quote)
{
int32_t cnt = 0;
int32_t strLen = (int32_t)strlen(str);
int32_t i = 0;
while (i < strLen) {
if (str[i] == quote) {
break; // Exit the loop when the quote character is encountered.
}
if (str[i] == '\\') {
if (IsEscapeValid(str[i + 1]) == 0 && str[i + 1] != 'n') {
return BSL_CONF_CONTEXT_ERR; // Return error if the escape sequence is invalid.
}
i++; // Skip the escaped character.
if (i >= strLen) {
return BSL_CONF_CONTEXT_ERR; // Return error if the index exceeds the string length.
}
if (str[i] == 'n') { // '\n'
str[i] = '\n';
}
}
str[cnt] = str[i];
cnt++;
i++;
}
str[cnt] = '\0'; // Add a null terminator at the end of the parsed string.
return BSL_SUCCESS;
}
// Removes escape characters and comments from a string.
static int32_t RemoveEscapeAndComments(char *buff)
{
bool isValue = false;
int32_t flag = 0;
int32_t cnt = 0;
int32_t len = (int32_t)strlen(buff);
int32_t i = 0;
while (i < len) {
if (buff[i] == '=') {
isValue = true; // Enter the value part when '=' is encountered.
}
if (buff[i] == ';' || buff[i] == '#') {
if (isValue) { // Encounter a comment symbol in the value part, stop processing.
break;
}
}
if (buff[i] == '\\') {
// Escape characters are not allowed in the name part, or the escape character is invalid.
if (isValue == false) {
return -1;
}
if (IsEscapeValid(buff[i + 1]) == 0 && buff[i + 1] != 'n') {
return -1;
}
flag++;
i++; // Skip the escape character.
if (i >= len) { // If the index exceeds the string length, return an error.
return -1;
}
if (buff[i] == 'n') { // '\n'
buff[i] = '\n';
}
}
buff[cnt] = buff[i];
cnt++;
i++;
}
buff[cnt] = '\0'; // Add a null terminator at the end of the processed string.
return flag;
}
static void FreeSectionNames(char **names, int32_t namesSize)
{
if (names == NULL) {
return;
}
for (int32_t i = 0; i < namesSize; i++) {
BSL_SAL_FREE(names[i]);
}
BSL_SAL_FREE(names);
}
char **DefaultGetSectionNames(BslList *sectionList, uint32_t *namesSize)
{
if (sectionList == NULL || namesSize == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return NULL;
}
int32_t cnt = 0;
int32_t num = BSL_LIST_COUNT(sectionList);
char **names = (char **)BSL_SAL_Calloc(num, sizeof(char *));
if (names == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
BSL_CONF_Section *secData = NULL;
BslListNode *node = BSL_LIST_FirstNode(sectionList);
while (node != NULL && cnt < num) {
secData = BSL_LIST_GetData(node);
if (secData == NULL) {
FreeSectionNames(names, num);
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return NULL;
}
names[cnt] = BSL_SAL_Calloc(secData->sectionLen + 1, 1);
if (names[cnt] == NULL) {
FreeSectionNames(names, num);
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return NULL;
}
(void)memcpy_s(names[cnt], secData->sectionLen, secData->section, secData->sectionLen);
cnt++;
node = BSL_LIST_GetNextNode(sectionList, node);
}
if (cnt != num) {
FreeSectionNames(names, num);
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return NULL;
}
*namesSize = (uint32_t)num;
return names;
}
static int32_t CmpSectionFunc(const void *a, const void *b)
{
const BSL_CONF_Section *aData = (const BSL_CONF_Section *)a;
const char *bData = (const char *)b;
if (aData != NULL && aData->section != NULL && bData != NULL) {
if (strcmp(aData->section, bData) == 0) {
return 0;
}
}
return 1;
}
static int32_t CmpKeyFunc(const void *a, const void *b)
{
const BSL_CONF_KeyValue *aData = (const BSL_CONF_KeyValue *)a;
const char *bData = (const char *)b;
if (aData != NULL && aData->key != NULL && bData != NULL) {
if (strcmp(aData->key, bData) == 0) {
return 0;
}
}
return 1;
}
void DeleteKeyValueNodeFunc(void *data)
{
if (data == NULL) {
return;
}
BSL_CONF_KeyValue *keyValueNode = (BSL_CONF_KeyValue *)data;
BSL_SAL_FREE(keyValueNode->key);
BSL_SAL_FREE(keyValueNode->value);
BSL_SAL_FREE(keyValueNode);
}
void DeleteSectionNodeFunc(void *data)
{
if (data == NULL) {
return;
}
BSL_CONF_Section *sectionNode = (BSL_CONF_Section *)data;
BSL_LIST_FREE(sectionNode->keyValueList, DeleteKeyValueNodeFunc);
BSL_SAL_FREE(sectionNode->section);
BSL_SAL_FREE(sectionNode);
}
static int32_t UpdateKeyValue(BSL_CONF_KeyValue *keyValue, const char *value)
{
uint32_t newValueLen = (uint32_t)strlen(value);
char *newValue = (char *)BSL_SAL_Calloc(1, newValueLen + 1);
if (newValue == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
return BSL_CONF_MEM_ALLOC_FAIL;
}
(void)memcpy_s(newValue, newValueLen, value, newValueLen);
BSL_SAL_FREE(keyValue->value);
keyValue->value = newValue;
keyValue->valueLen = newValueLen;
return BSL_SUCCESS;
}
static int32_t AddKeyValue(BslList *keyValueList, const char * key, const char *value)
{
int32_t ret = BSL_SUCCESS;
if (IsNameValid(key) == 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_INVALID_NAME);
return BSL_CONF_INVALID_NAME;
}
BSL_CONF_KeyValue *keyValue = (BSL_CONF_KeyValue *)BSL_SAL_Calloc(1, sizeof(BSL_CONF_KeyValue));
if (keyValue == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
return BSL_CONF_MEM_ALLOC_FAIL;
}
keyValue->keyLen = (uint32_t)strlen(key);
keyValue->key = (char *)BSL_SAL_Calloc(1, keyValue->keyLen + 1);
if (keyValue->key == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
ret = BSL_CONF_MEM_ALLOC_FAIL;
goto EXIT;
}
keyValue->valueLen = (uint32_t)strlen(value);
keyValue->value = (char *)BSL_SAL_Calloc(1, keyValue->valueLen + 1);
if (keyValue->value == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
ret = BSL_CONF_MEM_ALLOC_FAIL;
goto EXIT;
}
(void)memcpy_s(keyValue->key, keyValue->keyLen, key, keyValue->keyLen);
(void)memcpy_s(keyValue->value, keyValue->valueLen, value, keyValue->valueLen);
ret = BSL_LIST_AddElement(keyValueList, keyValue, BSL_LIST_POS_END);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
return BSL_SUCCESS;
EXIT:
DeleteKeyValueNodeFunc(keyValue);
return ret;
}
static int32_t AddSection(BslList *sectionList, const char *section, const char *key, const char *value)
{
int32_t ret = BSL_SUCCESS;
if (IsNameValid(section) == 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_INVALID_NAME);
return BSL_CONF_INVALID_NAME;
}
BSL_CONF_Section *sectionNode = (BSL_CONF_Section *)BSL_SAL_Calloc(1, sizeof(BSL_CONF_Section));
if (sectionNode == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
return BSL_CONF_MEM_ALLOC_FAIL;
}
sectionNode->sectionLen = (uint32_t)strlen(section);
sectionNode->section = (char *)BSL_SAL_Calloc(1, sectionNode->sectionLen + 1);
if (sectionNode->section == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
ret = BSL_CONF_MEM_ALLOC_FAIL;
goto EXIT;
}
(void)memcpy_s(sectionNode->section, sectionNode->sectionLen, section, sectionNode->sectionLen);
sectionNode->keyValueList = BSL_LIST_New(sizeof(BslList));
if (sectionNode->keyValueList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
ret = BSL_CONF_MEM_ALLOC_FAIL;
goto EXIT;
}
if (strlen(key) != 0) {
ret = AddKeyValue(sectionNode->keyValueList, key, value);
if (ret != BSL_SUCCESS) {
goto EXIT;
}
}
ret = BSL_LIST_AddElement(sectionList, sectionNode, BSL_LIST_POS_END);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
goto EXIT;
}
return BSL_SUCCESS;
EXIT:
DeleteSectionNodeFunc(sectionNode);
return ret;
}
BslList *DefaultGetSectionNode(BslList *sectionList, const char *section)
{
if (sectionList == NULL || section == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return NULL;
}
BSL_CONF_Section *sectionNode = BSL_LIST_Search(sectionList, section, CmpSectionFunc, NULL);
if (sectionNode == NULL || sectionNode->keyValueList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return NULL;
}
return sectionNode->keyValueList;
}
int32_t DefaultGetString(BslList *sectionList, const char *section, const char *key, char *str, uint32_t *strLen)
{
if (sectionList == NULL || section == NULL || key == NULL || str == NULL || strLen == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
BSL_CONF_Section *secCtx = BSL_LIST_Search(sectionList, section, CmpSectionFunc, NULL);
if (secCtx == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
BSL_CONF_KeyValue *keyValue = BSL_LIST_Search(secCtx->keyValueList, key, CmpKeyFunc, NULL);
if (keyValue == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_VALUE_NOT_FOUND);
return BSL_CONF_VALUE_NOT_FOUND;
}
if (*strLen < keyValue->valueLen + 1) { // 1 byte for '\0'
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
(void)memcpy_s(str, *strLen, keyValue->value, keyValue->valueLen);
str[keyValue->valueLen] = '\0';
*strLen = keyValue->valueLen;
return BSL_SUCCESS;
}
int32_t DefaultGetNumber(BslList *sectionList, const char *section, const char *key, long int *num)
{
char str[BSL_CONF_LINE_SIZE + 1] = {0};
uint32_t strLen = BSL_CONF_LINE_SIZE + 1;
int32_t ret = DefaultGetString(sectionList, section, key, str, &strLen);
if (ret != BSL_SUCCESS) {
return ret;
}
char *endPtr = NULL;
errno = 0;
long int tmpNum = strtol(str, &endPtr, 0);
if (strlen(endPtr) > 0 || endPtr == str || (tmpNum == LONG_MAX || tmpNum == LONG_MIN) || errno == ERANGE ||
(tmpNum == 0 && errno != 0)) {
BSL_ERR_PUSH_ERROR(BSL_CONF_CONTEXT_ERR);
return BSL_CONF_CONTEXT_ERR;
}
*num = tmpNum;
return BSL_SUCCESS;
}
BslList *DefaultCreate(void)
{
BslList *sectionList = BSL_LIST_New(sizeof(BslList));
if (sectionList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_MEM_ALLOC_FAIL);
return NULL;
}
int32_t ret = AddSection(sectionList, "default", "", "");
if (ret != BSL_SUCCESS) {
BSL_LIST_FREE(sectionList, NULL);
return NULL;
}
return sectionList;
}
void DefaultDestroy(BslList *sectionList)
{
if (sectionList == NULL) {
return;
}
BSL_LIST_FREE(sectionList, DeleteSectionNodeFunc);
}
static int32_t SetSection(BslList *sectionList, const char *section, const char * key, const char *value)
{
if (sectionList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
BSL_CONF_Section *secCtx = NULL;
BSL_CONF_KeyValue *keyValue = NULL;
if (strlen(section) == 0) { // default section.
if (strlen(key) == 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_CONTEXT_ERR);
return BSL_CONF_CONTEXT_ERR;
}
secCtx = BSL_LIST_Search(sectionList, "default", CmpSectionFunc, NULL);
if (secCtx == NULL || secCtx->keyValueList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
keyValue = BSL_LIST_Search(secCtx->keyValueList, key, CmpKeyFunc, NULL);
if (keyValue == NULL) {
return AddKeyValue(secCtx->keyValueList, key, value);
} else {
return UpdateKeyValue(keyValue, value);
}
} else {
secCtx = BSL_LIST_Search(sectionList, section, CmpSectionFunc, NULL);
if (secCtx == NULL) {
return AddSection(sectionList, section, key, value);
}
if (strlen(key) == 0) {
return BSL_SUCCESS;
}
if (secCtx->keyValueList == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
keyValue = BSL_LIST_Search(secCtx->keyValueList, key, CmpKeyFunc, NULL);
if (keyValue == NULL) {
return AddKeyValue(secCtx->keyValueList, key, value);
} else {
return UpdateKeyValue(keyValue, value);
}
}
}
// Reads a line of data from a configuration file.
static int32_t ConfGetLine(BSL_UIO *uio, char *buff, int32_t buffSize, int32_t *offset, int32_t *flag)
{
int32_t tmpOffset = *offset;
int32_t buffLen = buffSize - tmpOffset; // Calculate the available buffer length
if (buffLen <= 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_BUFF_OVERFLOW);
return BSL_CONF_BUFF_OVERFLOW;
}
int32_t ret = BSL_UIO_Gets(uio, buff + tmpOffset, (uint32_t *)&buffLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
buffLen += tmpOffset; // Update the buffer length
if (buffLen == 0) {
*flag = BREAK_FLAG;
return BSL_SUCCESS;
}
bool isEof = false;
if (buff[buffLen - 1] != '\n') { // buffer might have been truncated.
ret = BSL_UIO_Ctrl(uio, BSL_UIO_FILE_GET_EOF, 1, &isEof);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
if (isEof != true) {
BSL_ERR_PUSH_ERROR(BSL_CONF_BUFF_OVERFLOW);
return BSL_CONF_BUFF_OVERFLOW;
}
(void)RemoveSpace(buff);
return BSL_SUCCESS;
}
buffLen = RemoveSpace(buff);
if (buffLen > 0) {
buffLen--;
}
if (buff[buffLen] == '\\') { // Handle multi-line cases
if (buffLen > 0 && buff[buffLen - 1] == '\\') { // Handle escape characters
tmpOffset = 0;
} else { // Normal case
tmpOffset = buffLen; // Set the temporary offset
*flag = CONTINUE_FLAG;
}
} else { // Single-line case
tmpOffset = 0;
}
*offset = tmpOffset;
return BSL_SUCCESS;
}
// Parses a line of configuration data.
static int32_t ConfParseLine(BslList *sectionList, char *buff, char *section, char *key, char *value)
{
int32_t ret = BSL_SUCCESS;
size_t len = strlen(buff);
int32_t n = 2; // sscanf_s is expected to return 2.
if (len < 1 || buff[0] == '#' || buff[0] == ';') { // empty or comments
return BSL_SUCCESS;
} else if (buff[0] == '[' && buff[len - 1] == ']') {
len -= 2; // remove '[' and ']' len - 2.
if (memcpy_s(section, BSL_CONF_SEC_SIZE, &buff[1], len) != 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_BUFF_OVERFLOW);
return BSL_CONF_BUFF_OVERFLOW;
}
section[len] = '\0';
} else if (sscanf_s(buff, "%[^=] = \"%[^\n]", key, BSL_CONF_LINE_SIZE, value, BSL_CONF_LINE_SIZE) == n) {
ret = ParseQuote(value, '\"');
} else if (sscanf_s(buff, "%[^=] = \'%[^\n]", key, BSL_CONF_LINE_SIZE, value, BSL_CONF_LINE_SIZE) == n) {
ret = ParseQuote(value, '\'');
} else if (RemoveEscapeAndComments(buff) < 0) {
BSL_ERR_PUSH_ERROR(BSL_CONF_CONTEXT_ERR);
return BSL_CONF_CONTEXT_ERR;
} else if (sscanf_s(buff, "%[^=]%[=]", key, BSL_CONF_LINE_SIZE, value, BSL_CONF_LINE_SIZE) == n) {
char *valPtr = strchr(buff, '=');
valPtr++;
len = strlen(valPtr);
(void)memcpy_s(value, len, valPtr, len);
value[len] = '\0';
} else {
BSL_ERR_PUSH_ERROR(BSL_CONF_CONTEXT_ERR);
return BSL_CONF_CONTEXT_ERR;
}
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
(void)RemoveSpace(section);
(void)RemoveSpace(key);
(void)RemoveSpace(value);
return SetSection(sectionList, section, key, value);
}
// Loads configuration data from a UIO into a section list.
int32_t DefaultLoadUio(BslList *sectionList, BSL_UIO *uio)
{
if (sectionList == NULL || uio == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
int32_t ret;
int32_t offset = 0;
int32_t flag;
char *buff = (char *)BSL_SAL_Calloc(4, (BSL_CONF_LINE_SIZE + 1)); // 4 blocks for buff, secion, key, value.
if (buff == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
char *section = (char *)(buff + BSL_CONF_LINE_SIZE + 1);
char *key = (char *)(section + BSL_CONF_LINE_SIZE + 1);
char *value = (char *)(key + BSL_CONF_LINE_SIZE + 1);
while (true) {
flag = 0; // Reset flag.
// Read one line into buff.
ret = ConfGetLine(uio, buff, BSL_CONF_LINE_SIZE + 1, &offset, &flag);
if (ret != BSL_SUCCESS || flag == BREAK_FLAG) {
break;
}
if (flag == CONTINUE_FLAG) {
continue;
}
// Parse section, key, value from buff.
ret = ConfParseLine(sectionList, buff, section, key, value);
if (ret != BSL_SUCCESS) {
break;
}
// Clear buff, key, value, do not clear section.
(void)memset_s(buff, BSL_CONF_LINE_SIZE + 1, 0, BSL_CONF_LINE_SIZE + 1);
(void)memset_s(key, BSL_CONF_LINE_SIZE + 1, 0, BSL_CONF_LINE_SIZE + 1);
(void)memset_s(value, BSL_CONF_LINE_SIZE + 1, 0, BSL_CONF_LINE_SIZE + 1);
offset = 0; // Reset offset.
}
BSL_SAL_FREE(buff);
return ret;
}
int32_t DefaultLoad(BslList *sectionList, const char *file)
{
if (sectionList == NULL || file == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
BSL_UIO *in = BSL_UIO_New(BSL_UIO_FileMethod());
if (in == NULL) {
BSL_ERR_PUSH_ERROR(BSL_UIO_FAIL);
return BSL_UIO_FAIL;
}
int32_t ret = BSL_UIO_Ctrl(in, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_READ, (void *)(uintptr_t)file);
if (ret != BSL_SUCCESS) {
BSL_UIO_Free(in);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = DefaultLoadUio(sectionList, in);
BSL_UIO_Free(in);
return ret;
}
static int32_t DumpSection(BSL_UIO *uio, const BSL_CONF_Section *secData)
{
uint32_t strLen = secData->sectionLen + 4; // "[]\n\0" == 4
char *str = (char *)BSL_SAL_Calloc(1, strLen + 1);
if (str == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
int32_t usedLen = sprintf_s(str, strLen, "[%s]\n", secData->section);
if (usedLen < 0) {
BSL_SAL_FREE(str);
BSL_ERR_PUSH_ERROR(BSL_CONF_DUMP_FAIL);
return BSL_CONF_DUMP_FAIL;
}
if (usedLen > BSL_CONF_LINE_SIZE) {
BSL_SAL_FREE(str);
BSL_ERR_PUSH_ERROR(BSL_CONF_BUFF_OVERFLOW);
return BSL_CONF_BUFF_OVERFLOW;
}
int32_t ret = BSL_UIO_Puts(uio, str, (uint32_t *)&usedLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
BSL_SAL_FREE(str);
return ret;
}
static int32_t DumpKeyValue(BSL_UIO *uio, const BSL_CONF_KeyValue *keyValue)
{
uint32_t strLen = keyValue->keyLen + keyValue->valueLen * 2 + 3; // "=\n\0" == 3, valueLen * 2 for '\\'.
char *str = (char *)BSL_SAL_Calloc(1, strLen + 1);
if (str == NULL) {
BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL);
return BSL_MALLOC_FAIL;
}
int32_t usedLen = sprintf_s(str, strLen, "%s=", keyValue->key);
if (usedLen < 0) {
BSL_SAL_FREE(str);
BSL_ERR_PUSH_ERROR(BSL_CONF_DUMP_FAIL);
return BSL_CONF_DUMP_FAIL;
}
for (uint32_t i = 0; i < keyValue->valueLen; i++) {
if (IsEscapeValid(keyValue->value[i]) == 1) { // add '\\'.
str[usedLen] = '\\';
usedLen++;
}
if (keyValue->value[i] == '\n') {
str[usedLen] = '\\';
usedLen++;
str[usedLen] = 'n';
usedLen++;
continue;
}
str[usedLen] = keyValue->value[i];
usedLen++;
}
str[usedLen] = '\n';
usedLen++;
if (usedLen > BSL_CONF_LINE_SIZE) {
BSL_SAL_FREE(str);
BSL_ERR_PUSH_ERROR(BSL_CONF_BUFF_OVERFLOW);
return BSL_CONF_BUFF_OVERFLOW;
}
int32_t ret = BSL_UIO_Puts(uio, str, (uint32_t *)&usedLen);
if (ret != BSL_SUCCESS) {
BSL_ERR_PUSH_ERROR(ret);
}
BSL_SAL_FREE(str);
return ret;
}
int32_t DefaultDumpUio(BslList *sectionList, BSL_UIO *uio)
{
if (sectionList == NULL || uio == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
int32_t ret = BSL_SUCCESS;
BSL_CONF_Section *secData = NULL;
BSL_CONF_KeyValue *keyValue = NULL;
BslListNode *keyValueNode = NULL;
BslListNode *node = BSL_LIST_FirstNode(sectionList);
while (node != NULL) {
secData = BSL_LIST_GetData(node);
if (secData == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
ret = DumpSection(uio, secData);
if (ret != BSL_SUCCESS) {
return ret;
}
keyValueNode = BSL_LIST_FirstNode(secData->keyValueList);
while (keyValueNode != NULL) {
keyValue = BSL_LIST_GetData(keyValueNode);
if (keyValue == NULL) {
BSL_ERR_PUSH_ERROR(BSL_CONF_GET_FAIL);
return BSL_CONF_GET_FAIL;
}
ret = DumpKeyValue(uio, keyValue);
if (ret != BSL_SUCCESS) {
return ret;
}
keyValueNode = BSL_LIST_GetNextNode(secData->keyValueList, keyValueNode);
}
node = BSL_LIST_GetNextNode(sectionList, node);
}
return BSL_SUCCESS;
}
int32_t DefaultDump(BslList *sectionList, const char *file)
{
if (sectionList == NULL || file == NULL) {
BSL_ERR_PUSH_ERROR(BSL_NULL_INPUT);
return BSL_NULL_INPUT;
}
BSL_UIO *out = BSL_UIO_New(BSL_UIO_FileMethod());
if (out == NULL) {
BSL_ERR_PUSH_ERROR(BSL_UIO_FAIL);
return BSL_UIO_FAIL;
}
int32_t ret = BSL_UIO_Ctrl(out, BSL_UIO_FILE_OPEN, BSL_UIO_FILE_WRITE, (void *)(uintptr_t)file);
if (ret != BSL_SUCCESS) {
BSL_UIO_Free(out);
BSL_ERR_PUSH_ERROR(ret);
return ret;
}
ret = DefaultDumpUio(sectionList, out);
BSL_UIO_SetIsUnderlyingClosedByUio(out, true);
BSL_UIO_Free(out);
return ret;
}
const BSL_CONF_Method *BSL_CONF_DefaultMethod(void)
{
static const BSL_CONF_Method DEFAULT_METHOD = {
DefaultCreate,
DefaultDestroy,
DefaultLoad,
DefaultLoadUio,
DefaultDump,
DefaultDumpUio,
DefaultGetSectionNode,
DefaultGetString,
DefaultGetNumber,
DefaultGetSectionNames,
};
return &DEFAULT_METHOD;
}
#endif /* HITLS_BSL_CONF */
| 2302_82127028/openHiTLS-examples_5062 | bsl/conf/src/bsl_conf_def.c | C | unknown | 26,113 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef BSL_ERR_INTERNAL_H
#define BSL_ERR_INTERNAL_H
#include <stdint.h>
#include "hitls_build.h"
#include "bsl_err.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef HITLS_BSL_ERR
/**
* @ingroup bsl_err
* @brief Save the error information to the error information stack.
*
* @par Description:
* Save the error information to the error information stack.
*
* @attention err cannot be 0.
* @param err [IN] Error code. The most significant 16 bits indicate the submodule ID,
* and the least significant 16 bits indicate the error ID.
* @param file [IN] File name, excluding the directory path
* @param lineNo [IN] Number of the line where the error occurs.
*/
void BSL_ERR_PushError(int32_t err, const char *file, uint32_t lineNo);
/**
* @ingroup bsl_err
* @brief Save the error information to the error information stack.
*
* @par Description:
* Save the error information to the error information stack.
*
* @attention e cannot be 0.
*/
#define BSL_ERR_PUSH_ERROR(e) BSL_ERR_PushError((e), __FILENAME__, __LINE__)
#else
#define BSL_ERR_PUSH_ERROR(e)
#endif /* HITLS_BSL_ERR */
#ifdef __cplusplus
}
#endif
#endif // BSL_ERR_INTERNAL_H
| 2302_82127028/openHiTLS-examples_5062 | bsl/err/include/bsl_err_internal.h | C | unknown | 1,723 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_BSL_ERR
#include "bsl_sal.h"
#include "bsl_log_internal.h"
#include "bsl_log.h"
#include "bsl_binlog_id.h"
#include "avl.h"
// Maximum height of the AVL tree.
#define AVL_MAX_HEIGHT 64
static uint32_t GetMaxHeight(uint32_t a, uint32_t b)
{
if (a >= b) {
return a;
} else {
return b;
}
}
static uint32_t GetAvlTreeHeight(const BSL_AvlTree *node)
{
if (node == NULL) {
return 0;
} else {
return node->height;
}
}
static void UpdateAvlTreeHeight(BSL_AvlTree *node)
{
if (node != NULL) {
uint32_t leftHeight = GetAvlTreeHeight(node->leftNode);
uint32_t rightHeight = GetAvlTreeHeight(node->rightNode);
if (node->height >= AVL_MAX_HEIGHT) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05001, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"avl tree height exceed max limit", 0, 0, 0, 0);
return;
}
node->height = GetMaxHeight(leftHeight, rightHeight) + 1u;
}
}
BSL_AvlTree *BSL_AVL_MakeLeafNode(BSL_ElementData data)
{
BSL_AvlTree *curNode = (BSL_AvlTree *)BSL_SAL_Malloc(sizeof(BSL_AvlTree));
if (curNode == NULL) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05002, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"MALLOC for avl tree node failed", 0, 0, 0, 0);
return NULL;
}
curNode->height = 1;
curNode->rightNode = NULL;
curNode->leftNode = NULL;
curNode->data = data;
return curNode;
}
/**
* @brief AVL rotate left
* @param root [IN] Root node to be rotated
* @return rNode Root node after rotation
*/
static BSL_AvlTree *AVL_RotateLeft(BSL_AvlTree *root)
{
/* Rotate Left
10 20
5 20 --Rotate Left---> 10 30
30 5 40
40
In this case, the input root node is 10, and the output node is 20. */
BSL_AvlTree *rNode = root->rightNode;
BSL_AvlTree *lNode = rNode->leftNode;
root->rightNode = lNode;
rNode->leftNode = root;
UpdateAvlTreeHeight(root);
UpdateAvlTreeHeight(rNode);
return rNode;
}
/**
* @brief AVL rotate right
* @param root [IN] Root node to be rotated
* @return lNode Root node after rotation
*/
static BSL_AvlTree *AVL_RotateRight(BSL_AvlTree *root)
{
/* Rotate Right
40 30
/ \ / \
30 50 --Rotate Right---> 20 40
20 35 10 35 50
10
In this case, the input root node is 40, and the output node is 30. */
BSL_AvlTree *lNode = root->leftNode;
BSL_AvlTree *rNode = lNode->rightNode;
root->leftNode = rNode;
lNode->rightNode = root;
UpdateAvlTreeHeight(root);
UpdateAvlTreeHeight(lNode);
return lNode;
}
/**
* @brief AVL Right Balance
* @param root [IN] Root node to be balanced
* @return root: root node after balancing
*/
static BSL_AvlTree *AVL_RebalanceRight(BSL_AvlTree *root)
{
// The height difference between the left and right subtrees is only 1.
if ((GetAvlTreeHeight(root->leftNode) + 1u) >= GetAvlTreeHeight(root->rightNode)) {
UpdateAvlTreeHeight(root);
return root;
}
/* The height of the left subtree is greater than that of the right subtree. Rotate right and then left. */
BSL_AvlTree *curNode = root->rightNode;
if (GetAvlTreeHeight(curNode->leftNode) > GetAvlTreeHeight(curNode->rightNode)) {
root->rightNode = AVL_RotateRight(curNode);
}
return AVL_RotateLeft(root);
}
/**
* @brief AVL Left Balance
* @param root [IN] Root node to be balanced
* @return root: root node after balancing
*/
static BSL_AvlTree *AVL_RebalanceLeft(BSL_AvlTree *root)
{
// The height difference between the left and right subtrees is only 1.
if ((GetAvlTreeHeight(root->rightNode) + 1u) >= GetAvlTreeHeight(root->leftNode)) {
UpdateAvlTreeHeight(root);
return root;
}
/* The height of the right subtree is greater than that of the left subtree. Rotate left and then right. */
BSL_AvlTree *curNode = root->leftNode;
if (GetAvlTreeHeight(curNode->rightNode) > GetAvlTreeHeight(curNode->leftNode)) {
root->leftNode = AVL_RotateLeft(curNode);
}
return AVL_RotateRight(root);
}
static void AVL_FreeData(BSL_ElementData data, BSL_AVL_DATA_FREE_FUNC freeFunc)
{
if (freeFunc != NULL) {
freeFunc(data);
}
}
BSL_AvlTree *BSL_AVL_InsertNode(BSL_AvlTree *root, uint64_t nodeId, BSL_AvlTree *node)
{
if (root == NULL) {
node->nodeId = nodeId;
return node;
}
if (root->nodeId > nodeId) {
// If the nodeId is smaller than the root nodeId, insert the left subtree.
root->leftNode = BSL_AVL_InsertNode(root->leftNode, nodeId, node);
return AVL_RebalanceLeft(root);
} else if (root->nodeId < nodeId) {
// If the nodeId is greater than the root nodeId, insert the right subtree.
root->rightNode = BSL_AVL_InsertNode(root->rightNode, nodeId, node);
return AVL_RebalanceRight(root);
}
/* if the keys are the same and cannot be inserted */
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05003, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"AVL tree insert key nodeId(%llu) already exist", nodeId, 0, 0, 0);
return NULL;
}
BSL_AvlTree *BSL_AVL_SearchNode(BSL_AvlTree *root, uint64_t nodeId)
{
BSL_AvlTree *curNode = root;
while (curNode != NULL) {
// match the node
if (curNode->nodeId == nodeId) {
break;
} else if (curNode->nodeId > nodeId) {
// If the nodeId is smaller than the root nodeId, search the left subtree.
curNode = curNode->leftNode;
} else {
// If the nodeId is greater than the root nodeId, search the right subtree.
curNode = curNode->rightNode;
}
}
// If the specified node cannot be found, NULL is returned.
return curNode;
}
/**
* @brief Delete the specified AVL node that has both the left and right subnodes.
* @param rmNodeChild [IN] Child node of the AVL node to be deleted
* removeNode [IN] Avl node to be deleted.
* @return root Return the deleted root node of the AVL tree.
*/
static BSL_AvlTree *AVL_DeleteNodeWithTwoChilds(BSL_AvlTree *rmNodeChild, BSL_AvlTree *removeNode)
{
if (rmNodeChild == NULL || removeNode == NULL) {
return NULL;
}
if (rmNodeChild->rightNode == NULL) {
// Connect the left node and the grandfather node regardless of whether rmNodeChild has a left node.
BSL_AvlTree *curNode = rmNodeChild->leftNode;
removeNode->nodeId = rmNodeChild->nodeId;
removeNode->data = rmNodeChild->data;
BSL_SAL_FREE(rmNodeChild);
return curNode;
}
rmNodeChild->rightNode = AVL_DeleteNodeWithTwoChilds(rmNodeChild->rightNode, removeNode);
return AVL_RebalanceLeft(rmNodeChild);
}
BSL_AvlTree *BSL_AVL_DeleteNode(BSL_AvlTree *root, uint64_t nodeId, BSL_AVL_DATA_FREE_FUNC func)
{
if (root == NULL) {
return root;
}
if (root->nodeId == nodeId) {
if (root->leftNode == NULL) {
if (root->rightNode == NULL) {
// Both the left and right nodes are NULL.
AVL_FreeData(root->data, func);
BSL_SAL_FREE(root);
return NULL;
} else {
// Only have the right node.
BSL_AvlTree *curNode = root->rightNode;
AVL_FreeData(root->data, func);
BSL_SAL_FREE(root);
return (curNode);
}
} else if (root->rightNode == NULL) {
// Only have the right node.
BSL_AvlTree *curNode = root->leftNode;
AVL_FreeData(root->data, func);
BSL_SAL_FREE(root);
return (curNode);
} else {
// There are left and right nodes.
AVL_FreeData(root->data, func);
root->leftNode = AVL_DeleteNodeWithTwoChilds(root->leftNode, root);
return AVL_RebalanceRight(root);
}
}
if (root->nodeId > nodeId) {
root->leftNode = BSL_AVL_DeleteNode(root->leftNode, nodeId, func);
return AVL_RebalanceRight(root);
} else {
root->rightNode = BSL_AVL_DeleteNode(root->rightNode, nodeId, func);
return AVL_RebalanceLeft(root);
}
}
void BSL_AVL_DeleteTree(BSL_AvlTree *root, BSL_AVL_DATA_FREE_FUNC func)
{
if (root == NULL) {
return;
}
BSL_AVL_DeleteTree(root->leftNode, func);
BSL_AVL_DeleteTree(root->rightNode, func);
AVL_FreeData(root->data, func);
BSL_SAL_FREE(root);
}
#endif /* HITLS_BSL_ERR */
| 2302_82127028/openHiTLS-examples_5062 | bsl/err/src/avl.c | C | unknown | 9,427 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#ifndef AVL_H
#define AVL_H
#include "hitls_build.h"
#ifdef HITLS_BSL_ERR
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef void *BSL_ElementData;
typedef void (*BSL_AVL_DATA_FREE_FUNC)(BSL_ElementData data);
/* AVL tree node structure */
typedef struct AvlTree {
uint32_t height;
uint64_t nodeId;
struct AvlTree *rightNode;
struct AvlTree *leftNode;
BSL_ElementData data;
} BSL_AvlTree;
/**
* @ingroup bsl_err
* @brief Create a tree node.
*
* @par Description:
* Create a tree node and set node data.
*
* @attention None
* @param data [IN] Data pointer of the tree node
* @retval BSL_AvlTree *curNode node returned after the application is successful.
* NULL application failed
*/
BSL_AvlTree *BSL_AVL_MakeLeafNode(BSL_ElementData data);
/**
* @ingroup bsl_err
* @brief Search for a node.
*
* @par Description:
* Query the node in the AVL tree by nodeId.
*
* @attention None
* @param root [IN] Pointer to the root node of the tree
* @param nodeId [IN] node ID of the tree, as the key
* @retval NULL No corresponding node is found.
* @retval not NULL Pointer to the corresponding node.
*/
BSL_AvlTree *BSL_AVL_SearchNode(BSL_AvlTree *root, uint64_t nodeId);
/**
* @ingroup bsl_err
* @brief Create a node in the tree.
*
* @par Description:
* Create a node in the tree.
*
* @attention If the nodeId already exists, the insertion fails.
* @param root [IN] Pointer to the root node of the tree.
* @param nodeId [IN] as the key of the created node
* @param node [IN] Tree node
* @retval The root node of a non-null tree or subtree
*/
BSL_AvlTree *BSL_AVL_InsertNode(BSL_AvlTree *root, uint64_t nodeId, BSL_AvlTree *node);
/**
* @ingroup bsl_err
* @brief Delete a specific tree node.
*
* @par Description:
* Delete the nodeId corresponding tree node.
*
* @attention None
* @param root [IN] Pointer to the root node of the tree.
* @param nodeId [IN] Key of the node to be deleted
* @param func [IN] Pointer to the function that releases the data of the deleted node.
* @retval NULL All nodes in the tree have been deleted.
* @retval not NULL Pointer to the root node of a tree or subtree.
*/
BSL_AvlTree *BSL_AVL_DeleteNode(BSL_AvlTree *root, uint64_t nodeId, BSL_AVL_DATA_FREE_FUNC func);
/**
* @ingroup bsl_err
* @brief Delete all nodes from the tree.
*
* @par Description:
* Delete all nodes in the tree.
*
* @attention None
* @param root [IN] Pointer to the root node of the tree
* @param func [IN] Pointer to the function that releases the data of the deleted node.
*/
void BSL_AVL_DeleteTree(BSL_AvlTree *root, BSL_AVL_DATA_FREE_FUNC func);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_ERR */
#endif // AVL_H | 2302_82127028/openHiTLS-examples_5062 | bsl/err/src/avl.h | C | unknown | 3,271 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "hitls_build.h"
#ifdef HITLS_BSL_ERR
#include <stdbool.h>
#include "securec.h"
#include "bsl_log_internal.h"
#include "bsl_log.h"
#include "bsl_sal.h"
#include "avl.h"
#include "bsl_err.h"
#include "bsl_errno.h"
#include "bsl_binlog_id.h"
#include "bsl_err_internal.h"
#define ERR_FLAG_POP_MARK 0x01
/* Error information stack size */
#define SAL_MAX_ERROR_STACK 20
/* Error information stack */
typedef struct {
/* Current point location to the stack. When the value is -1, the stack is empty. */
uint16_t bottom; /* Stack bottom */
uint16_t top; /* Stack top */
/* Prevent error stacks from being cleared. Currently, this parameter is used in asynchronous cases. */
uint32_t flag;
/* Store the error code information of a specific thread */
int32_t errorStack[SAL_MAX_ERROR_STACK];
/* Error code flag, which is used to partially clear and prevent side channel attack. */
uint32_t errorFlags[SAL_MAX_ERROR_STACK];
/* store the error file name. */
const char *filename[SAL_MAX_ERROR_STACK];
/* store the line number of the file where the error occurs */
uint32_t line[SAL_MAX_ERROR_STACK];
} ErrorCodeStack;
/* Avl tree root node of the error stack. */
static BSL_AvlTree *g_avlRoot = NULL;
/* Error description root node */
static BSL_AvlTree *g_descRoot = NULL;
/* Current number of AVL nodes */
static uint32_t g_avlNodeCount = 0;
/* Maximum number of nodes allowed by the AVL tree */
static uint32_t g_maxAvlNodes = 0x0000FFFF;
/* Check the initialization status. 0 means false, if the value is not 0, it means true. Run once. */
static uint32_t g_isErrInit = 0;
/* Handle of the thread lock */
static BSL_SAL_ThreadLockHandle g_errLock = NULL;
static void ErrAutoInit(void)
{
/* Attempting self-initialization in abnormal conditions */
(void)BSL_ERR_Init();
}
int32_t BSL_ERR_Init(void)
{
if (g_errLock != NULL) {
return BSL_SUCCESS;
}
return BSL_SAL_ThreadLockNew(&g_errLock);
}
void BSL_ERR_DeInit(void)
{
g_isErrInit = 0;
if (g_errLock == NULL) {
return;
}
BSL_SAL_ThreadLockFree(g_errLock);
g_errLock = NULL;
return;
}
static void StackReset(ErrorCodeStack *stack)
{
if (stack != NULL) {
(void)memset_s(stack, sizeof(*stack), 0, sizeof(*stack));
}
}
static void StackResetIndex(ErrorCodeStack *stack, uint32_t i)
{
bool invalid = stack == NULL || i >= SAL_MAX_ERROR_STACK;
if (!invalid) {
stack->errorStack[i] = 0;
stack->line[i] = 0;
stack->filename[i] = NULL;
stack->errorFlags[i] = 0;
}
}
static void StackDataFree(BSL_ElementData data)
{
BSL_SAL_FREE(data);
}
static ErrorCodeStack *GetStack(void)
{
const uint64_t threadId = BSL_SAL_ThreadGetId();
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_avlRoot, threadId);
if (curNode != NULL) {
/* If an error stack exists, directly returned. */
return curNode->data;
}
/* need to create an error stack */
if (g_avlNodeCount >= g_maxAvlNodes) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05004, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"New Avl Node failed.", 0, 0, 0, 0);
return NULL;
}
ErrorCodeStack *stack = (ErrorCodeStack *)BSL_SAL_Calloc(1, sizeof(ErrorCodeStack));
if (stack == NULL) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05005, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"CALLOC error code stack failed", 0, 0, 0, 0);
return NULL;
}
BSL_AvlTree *node = BSL_AVL_MakeLeafNode(stack);
if (node == NULL) {
StackDataFree(stack);
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05006, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"avl insert node failed, threadId %lu", threadId, 0, 0, 0);
return NULL;
}
g_avlNodeCount++;
/* upper layer has ensured that the threadId node does not exist. */
g_avlRoot = BSL_AVL_InsertNode(g_avlRoot, threadId, node);
return stack;
}
void BSL_ERR_PushError(int32_t err, const char *file, uint32_t lineNo)
{
if (err == BSL_SUCCESS) {
/* push success is not allowed. */
return;
}
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05007, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"acquire lock failed when pushing error, threadId %llu, error code %d", BSL_SAL_ThreadGetId(), ret, 0, 0);
return;
}
ErrorCodeStack *stack = GetStack();
if (stack != NULL) {
if (stack->top == stack->bottom && stack->errorStack[stack->top] != 0) {
stack->bottom = (stack->bottom + 1) % SAL_MAX_ERROR_STACK;
}
stack->errorFlags[stack->top] = 0;
stack->errorStack[stack->top] = err;
stack->filename[stack->top] = file;
stack->line[stack->top] = lineNo;
stack->top = (stack->top + 1) % SAL_MAX_ERROR_STACK;
}
BSL_SAL_ThreadUnlock(g_errLock);
}
void BSL_ERR_ClearError(void)
{
(void)BSL_SAL_ThreadRunOnce(&g_isErrInit, ErrAutoInit);
uint64_t threadId = BSL_SAL_ThreadGetId();
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05008, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"acquire lock failed when clearing error, threadId %llu", threadId, 0, 0, 0);
return;
}
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_avlRoot, threadId);
if (curNode != NULL) {
/* Will not be NULL. */
ErrorCodeStack *errStack = curNode->data;
if (errStack->flag == 0) {
StackReset(errStack);
}
}
BSL_SAL_ThreadUnlock(g_errLock);
}
void BSL_ERR_RemoveErrorStack(bool isRemoveAll)
{
(void)BSL_SAL_ThreadRunOnce(&g_isErrInit, ErrAutoInit);
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05009, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"acquire lock failed when removing error stack, threadId %llu", BSL_SAL_ThreadGetId(), 0, 0, 0);
return;
}
if (g_avlRoot != NULL) {
if (isRemoveAll) {
BSL_AVL_DeleteTree(g_avlRoot, StackDataFree);
g_avlNodeCount = 0;
g_avlRoot = NULL;
} else {
uint64_t threadId = BSL_SAL_ThreadGetId();
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_avlRoot, threadId);
if (curNode != NULL) {
g_avlNodeCount--;
g_avlRoot = BSL_AVL_DeleteNode(g_avlRoot, threadId, StackDataFree);
}
}
}
BSL_SAL_ThreadUnlock(g_errLock);
}
/* Obtain the index. 'last' indicates that the last or first error code is obtained. */
static uint16_t GetIndex(ErrorCodeStack *errStack, bool last)
{
uint16_t idx;
if (last) {
idx = errStack->top - 1;
if (idx >= SAL_MAX_ERROR_STACK) {
idx = SAL_MAX_ERROR_STACK - 1;
}
} else {
idx = errStack->bottom;
}
return idx;
}
/* If clr is true, the external operation is get. If clr is false, the external operation is peek.
The get operation cleans up after the error information is obtained, while the peek operation does not.
If last is true, the last error code at the top of the stack is obtained.
If last is false, the first error code at the bottom of the stack is obtained. */
static int32_t GetErrorInfo(const char **file, uint32_t *lineNo, bool clr, bool last)
{
uint16_t idx;
int32_t ret = BSL_SAL_ThreadReadLock(g_errLock);
if (ret != BSL_SUCCESS) {
return BSL_ERR_ERR_ACQUIRE_READ_LOCK_FAIL;
}
if (g_avlRoot == NULL) {
/* If avlRoot is empty, no thread push error. Therefore, error should be success. */
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
const uint64_t threadId = BSL_SAL_ThreadGetId();
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_avlRoot, threadId);
if (curNode == NULL) {
/* If curNode is empty, the current thread does not have push error. Therefore, error should be success. */
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
ErrorCodeStack *errStack = curNode->data; /* will not be null */
idx = GetIndex(errStack, last);
if (errStack->errorStack[idx] == 0) { /* error stack is empty */
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
int32_t errorCode = errStack->errorStack[idx]; /* Obtain the specified error ID. */
uint32_t fileLine = errStack->line[idx]; /* Obtain the specified line number. */
const char *f = errStack->filename[idx]; /* Obtain the specified file name. */
if (clr) {
StackResetIndex(errStack, idx);
if (last) {
errStack->top = idx;
} else {
errStack->bottom = (idx + 1) % SAL_MAX_ERROR_STACK;
}
}
BSL_SAL_ThreadUnlock(g_errLock);
if (file != NULL && lineNo != NULL) { /* both together, there's no point in getting only one of them. */
if (f == NULL) {
*file = "NA";
*lineNo = 0;
} else {
*file = f;
*lineNo = fileLine;
}
}
return errorCode;
}
static int32_t GetLastErrorInfo(const char **file, uint32_t *lineNo, bool clr)
{
return GetErrorInfo(file, lineNo, clr, true);
}
static int32_t GetFirstErrorInfo(const char **file, uint32_t *lineNo, bool clr)
{
return GetErrorInfo(file, lineNo, clr, false);
}
int32_t BSL_ERR_GetLastErrorFileLine(const char **file, uint32_t *lineNo)
{
return GetLastErrorInfo(file, lineNo, true);
}
int32_t BSL_ERR_PeekLastErrorFileLine(const char **file, uint32_t *lineNo)
{
return GetLastErrorInfo(file, lineNo, false);
}
int32_t BSL_ERR_GetLastError(void)
{
return GetLastErrorInfo(NULL, NULL, true);
}
int32_t BSL_ERR_GetErrorFileLine(const char **file, uint32_t *lineNo)
{
return GetFirstErrorInfo(file, lineNo, true);
}
int32_t BSL_ERR_PeekErrorFileLine(const char **file, uint32_t *lineNo)
{
return GetFirstErrorInfo(file, lineNo, false);
}
int32_t BSL_ERR_GetError(void)
{
return GetFirstErrorInfo(NULL, NULL, true);
}
static int32_t AddErrDesc(const BSL_ERR_Desc *desc)
{
if (desc->error < 0) {
return BSL_INTERNAL_EXCEPTION;
}
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_descRoot, (uint64_t)desc->error);
if (curNode != NULL) {
curNode->data = (BSL_ElementData)(uintptr_t)(desc->string);
return BSL_SUCCESS;
}
BSL_AvlTree *node = BSL_AVL_MakeLeafNode((BSL_ElementData)(uintptr_t)(desc->string));
if (node == NULL) {
return BSL_INTERNAL_EXCEPTION;
}
g_descRoot = BSL_AVL_InsertNode(g_descRoot, (uint64_t)desc->error, node);
return BSL_SUCCESS;
}
int32_t BSL_ERR_AddErrStringBatch(const BSL_ERR_Desc *descList, uint32_t num)
{
if (descList == NULL || num == 0) {
return BSL_NULL_INPUT;
}
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
return ret;
}
for (uint32_t i = 0; i < num; i++) {
ret = AddErrDesc(&descList[i]);
if (ret != BSL_SUCCESS) {
break;
}
}
BSL_SAL_ThreadUnlock(g_errLock);
return ret;
}
void BSL_ERR_RemoveErrStringBatch(void)
{
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
BSL_LOG_BINLOG_FIXLEN(BINLOG_ID05010, BSL_LOG_LEVEL_ERR, BSL_LOG_BINLOG_TYPE_RUN,
"acquire lock failed when removing error string, threadId %llu", BSL_SAL_ThreadGetId(), 0, 0, 0);
return;
}
if (g_descRoot != NULL) {
BSL_AVL_DeleteTree(g_descRoot, NULL);
g_descRoot = NULL;
}
BSL_SAL_ThreadUnlock(g_errLock);
}
const char *BSL_ERR_GetString(int32_t error)
{
if (error < 0) {
return NULL;
}
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
return NULL;
}
if (g_descRoot == NULL) {
BSL_SAL_ThreadUnlock(g_errLock);
return NULL;
}
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_descRoot, (uint64_t)error);
if (curNode == NULL) {
BSL_SAL_ThreadUnlock(g_errLock);
return NULL;
}
const char *str = curNode->data;
BSL_SAL_ThreadUnlock(g_errLock);
return str;
}
static int32_t BSL_LIST_WriteLockCreate(ErrorCodeStack **errStack, uint32_t *top)
{
int32_t ret = BSL_SAL_ThreadWriteLock(g_errLock);
if (ret != BSL_SUCCESS) {
return BSL_ERR_ERR_ACQUIRE_WRITE_LOCK_FAIL;
}
if (g_avlRoot == NULL) {
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_ERR_ERR_NO_STACK;
}
const uint64_t threadId = BSL_SAL_ThreadGetId();
BSL_AvlTree *curNode = BSL_AVL_SearchNode(g_avlRoot, threadId);
if (curNode == NULL) {
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_ERR_ERR_NO_STACK;
}
*errStack = curNode->data; /* will not be null */
if (top == NULL) {
return ret;
}
*top = (*errStack)->top - 1;
if (*top >= SAL_MAX_ERROR_STACK) {
*top = SAL_MAX_ERROR_STACK - 1;
}
return ret;
}
int32_t BSL_ERR_SetMark(void)
{
ErrorCodeStack *errStack = NULL;
uint32_t top = 0;
int32_t ret = BSL_LIST_WriteLockCreate(&errStack, &top);
if (ret != BSL_SUCCESS) {
return ret;
}
if (errStack->errorStack[top] == 0) { /* error stack is empty */
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_ERR_ERR_NO_ERROR;
}
errStack->errorFlags[top] |= ERR_FLAG_POP_MARK;
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
int32_t BSL_ERR_PopToMark(void)
{
ErrorCodeStack *errStack = NULL;
uint32_t top = 0;
int32_t ret = BSL_LIST_WriteLockCreate(&errStack, &top);
if (ret != BSL_SUCCESS) {
return ret;
}
while (errStack->errorStack[top] != 0 && ((errStack->errorFlags[top] & ERR_FLAG_POP_MARK) == 0)) {
StackResetIndex(errStack, top);
top--;
if (top >= SAL_MAX_ERROR_STACK) {
top = SAL_MAX_ERROR_STACK - 1;
}
}
errStack->top = (top + 1) % SAL_MAX_ERROR_STACK;
if (errStack->errorStack[top] == 0) {
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_ERR_ERR_NO_MARK;
}
errStack->errorFlags[top] &= ~ERR_FLAG_POP_MARK;
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
int32_t BSL_ERR_ClearLastMark(void)
{
ErrorCodeStack *errStack = NULL;
uint32_t top = 0;
int32_t ret = BSL_LIST_WriteLockCreate(&errStack, &top);
if (ret != BSL_SUCCESS) {
return ret;
}
while (errStack->errorStack[top] != 0 && ((errStack->errorFlags[top] & ERR_FLAG_POP_MARK) == 0)) {
top--;
if (top >= SAL_MAX_ERROR_STACK) {
top = SAL_MAX_ERROR_STACK - 1;
}
}
errStack->errorFlags[top] &= ~ERR_FLAG_POP_MARK;
BSL_SAL_ThreadUnlock(g_errLock);
return BSL_SUCCESS;
}
#endif /* HITLS_BSL_ERR */
| 2302_82127028/openHiTLS-examples_5062 | bsl/err/src/err.c | C | unknown | 15,532 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @defgroup bsl_hash hash table
* @ingroup bsl
*/
#ifndef BSL_HASH_H
#define BSL_HASH_H
#include "hitls_build.h"
#ifdef HITLS_BSL_HASH
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include "bsl_hash_list.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @ingroup bsl_hash
* @brief Handle of the hash table, which indicates the elements contained in the hash table.
*/
typedef struct BSL_HASH_Info BSL_HASH_Hash;
/**
* @ingroup bsl_hash
* @brief Definition of the iterator of the hash table, pointing to the hash node.
*/
typedef struct BSL_HASH_TagNode *BSL_HASH_Iterator;
/**
* @ingroup bsl_hash
* @brief Generates a hash table index based on the entered key.
* @param key [IN] hash key
* @param bktSize [IN] hash bucket size
*/
typedef uint32_t (*BSL_HASH_CodeCalcFunc)(uintptr_t key, uint32_t bktSize);
/**
* @ingroup bsl_hash
* @brief This function is used to match the input data with the key.
* Key1 stored in the hash table, and the key2 to be matched. If no, false is returned.
* @param key1 [IN] Key stored in the hash table
* @param key2 [IN] Key to be matched
* @retval #true key1 matches key2.
* @retval #false key1 and key2 do not match.
*/
typedef bool (*BSL_HASH_MatchFunc)(uintptr_t key1, uintptr_t key2);
/**
* @ingroup bsl_hash
* @brief Function for updating a node in the hash table.
* @par Description: This function is used to update the value of an existing node in the hash table.
* @attention
* 1. This function is called when a key already exists in the hash table and needs to be updated.
* 2. The user can provide a custom implementation of this function to handle specific update logic.
* @param hash [IN] Handle of the hash table.
* @param node [IN] Pointer to the node to be updated.
* @param value [IN] New value or address for storing the new value.
* @param valueSize [IN] Size of the new value. If the user has not registered a dupFunc, this parameter is not used.
* @retval #BSL_SUCCESS The node was successfully updated.
* @retval #BSL_INTERNAL_EXCEPTION Failed to update the node.
* @par Dependency: None
* @li bsl_hash.h: Header file where this function type is declared.
*/
typedef int32_t (*BSL_HASH_UpdateNodeFunc)(BSL_HASH_Hash *hash, BSL_HASH_Iterator node,
uintptr_t value, uint32_t valueSize);
/**
* @ingroup bsl_hash
* @brief Hash function.
* @par Description: Calculate the hash value based on the key value.
* The hash value does not modulate the size of the hash table and cannot be directly used for hash indexing.
* @attention
* 1. The key is the input parameter when the user invokes other interfaces.
* 2. If the key is an integer, you can use this function as the hashFunc parameter when creating a hash.
* @param key [IN] Key to be calculated.
* @param keySize [IN] Size of the key value.
* @retval #Hash value calculated based on the user key. The hash value is not modulated by the hash table size
* and cannot be directly used for hash indexing.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uint32_t BSL_HASH_CodeCalc(void *key, uint32_t keySize);
/**
* @ingroup bsl_hash
* @brief Default integer hash function.
* @par Default integer hash function.
* @attention
* 1. The key parameter is the input parameter when the user invokes other interfaces.
* 2. If the key is an integer, you can use this function as the hashFunc parameter when creating a hash.
* @param key [IN] Key to be calculated.
* @param bktSize [IN] Hash bucket size.
* @retval #Hash value calculated based on the user key.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uint32_t BSL_HASH_CodeCalcInt(uintptr_t key, uint32_t bktSize);
/**
* @ingroup bsl_hash
* @brief Default string hash function.
* @par Default string hash function.
* @attention
* 1. The key is an input parameter when the user invokes other interfaces.
* Ensure that the input key is a valid string start address.
* 2. If the key is a string, you can use this function as the hashFunc parameter when creating a hash.
* @param key [IN] Key to be calculated.
* @param bktSize [IN] Hash bucket size.
* @retval #Hash valueThe hash value calculated based on the user key.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uint32_t BSL_HASH_CodeCalcStr(uintptr_t key, uint32_t bktSize);
/**
* @ingroup bsl_hash
* @brief Default integer matching function.
* @par Default integer matching function.
* @attention
* 1. The key is the input parameter when the user invokes other interfaces.
* 2. If the key is an integer, you can use this function as the matchFunc parameter when creating a hash.
* @param key1 [IN] Key to be matched.
* @param key2 [IN] Key to be matched.
* @retval #true key1 matches key2.
* @retval #false key1 and key2 do not match.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
bool BSL_HASH_MatchInt(uintptr_t key1, uintptr_t key2);
/**
* @ingroup bsl_hash
* @brief Default string matching function.
* @par Default string matching function.
* @attention
* 1. Key1 is the input parameter when the user invokes other interfaces.
* Ensure that the input key1 is a valid string start address.
* 2. If the key is a string, you can use this function as the matchFunc parameter when creating the hash.
* @param key1 [IN] Key to be matched.
* @param key2 [IN] Key to be matched.
* @retval #true key1 matches key2.
* @retval #false key1 and key2 do not match.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
bool BSL_HASH_MatchStr(uintptr_t key1, uintptr_t key2);
/**
* @ingroup bsl_hash
* @brief Create a hash table and return the handle of the hash table.
* @attention
* 1. Copy functions for keys and data:
* You do not need to register the copy function in the following case:
* a) Data is the int type and the length <= sizeof(uintptr_t).
* The copy function must be registered in the following cases:
* a) Data is the int type, but the length is greater than sizeof(uintptr_t);
* b) string;
* c) User-defined data structure.
* 2. About the free function: Simply put, if the duplicate function is registered,
* the corresponding free function must be registered.
* 3. Provide the default integer and string hash functions: #BSL_HASH_CodeCalcInt and #BSL_HASH_CodeCalcStr.
* 4. Provide default integer and string matching functions: #BSL_HASH_MatchInt and #BSL_HASH_MatchStr.
* @param bktSize [IN] Number of hash buckets.
* @param hashCalcFunc [IN] Hash value calculation function.
* If the value is NULL, the default key is an integer. Use #BSL_HASH_CodeCalcInt.
* @param matchFunc [IN] hash key matching function.
* If the value is NULL, the default key is an integer. Use #BSL_HASH_MatchInt.
* @param keyFunc [IN] hash key copy and release function pair.
* If the keyFunc->dupFunc is not registered, the key is an integer by default.
* @param valueFunc [IN] hash data copy and release function pair.
* If the user has not registered valueFunc->dupFunc, the data type is an integer by default.
* @retval hash table handle. NULL indicates that the creation fails.
* @par Dependency: None
* @see #BSL_HASH_CodeCalcInt, #BSL_HASH_CodeCalcStr, #BSL_HASH_MatchInt, #BSL_HASH_MatchStr.
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Hash *BSL_HASH_Create(uint32_t bktSize, BSL_HASH_CodeCalcFunc hashFunc, BSL_HASH_MatchFunc matchFunc,
ListDupFreeFuncPair *keyFunc, ListDupFreeFuncPair *valueFunc);
/**
* @ingroup bsl_hash
* @brief Insert the hash data.
* @par Description: Create a node and insert data (key and value) into the hash table.
* @attention
* 1. Duplicate keys are not supported.
* 2. The key and value are integer values or addresses pointing to the user key or value.
* 3. If the life cycle of the extended data is shorter than the life cycle of the node,
* you need to register the copy function and release function when creating the hash table.
* @param hash [IN] handle of the hash table
* @param key [IN] key or address for storing the key
* @param keySize [IN] Copy length of key. If the user has not registered the dupFunc, this parameter is not used.
* @param value [IN] value or the address for storing the value.
* @param valueSize [IN] Copy length of value. If user has not registered the dupFunc, this parameter is not used.
* @retval #BSL_SUCCESS Succeeded in inserting the node.
* @retval #BSL_INTERNAL_EXCEPTION Insertion fails.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
int32_t BSL_HASH_Insert(BSL_HASH_Hash *hash, uintptr_t key, uint32_t keySize, uintptr_t value, uint32_t valueSize);
/**
* @ingroup bsl_hash
* @brief Insert or update the hash data.
* @par Description: This function is used to insert a nonexistent key into the hash table
* or update the value corresponding to an existing key.
* @attention
* 1. Duplicate keys are supported.
* 2. When the key does not exist, the usage of this function is the same as that of #BSL_HASH_Insert.
* 3. When the key exists, this function updates the value.
* @param hash [IN] Handle of the hash table.
* @param key [IN] key or address for storing the key.
* @param keySize [IN] Copy length of key. If the user has not registered the dupFunc, this parameter is not used.
* @param value [IN] value or the address for storing the value.
* @param valueSize [IN] Copy length of value. If user has not registered the dupFunc, this parameter is not used.
* @param updateNodeFunc [IN] Callback function for updating a node. If NULL, the default update function will be used.
* This function allows custom logic for updating existing nodes.
* @retval #BSL_SUCCESS Succeeded in inserting or updating the node.
* @retval #BSL_INTERNAL_EXCEPTION Failed to insert or update the node.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
int32_t BSL_HASH_Put(BSL_HASH_Hash *hash, uintptr_t key, uint32_t keySize, uintptr_t value, uint32_t valueSize,
BSL_HASH_UpdateNodeFunc updateNodeFunc);
/**
* @ingroup bsl_hash
* @brief Search for a node and return the node data.
* @par Description: Searches for and returns node data based on the key.
* @param hash [IN] Handle of the hash table.
* @param key [IN] key or address for storing the key.
* @param value [OUT] Data found.
* @retval #BSL_SUCCESS found successfully.
* @retval #BSL_INTERNAL_EXCEPTION query failed.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
int32_t BSL_HASH_At(const BSL_HASH_Hash *hash, uintptr_t key, uintptr_t *value);
/**
* @ingroup bsl_hash
* @brief Search for the iterator where the key is located.
* @par Description: Searches for and returns the iterator where the key is located based on the key.
* @param hash [IN] Handle of the hash table.
* @param key [IN] key or address for storing the key.
* @retval If the key exists, the iterator (pointing to the address of the node) where the key is located is returned.
* In other cases, #BSL_HASH_IterEnd() is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Iterator BSL_HASH_Find(const BSL_HASH_Hash *hash, uintptr_t key);
/**
* @ingroup bsl_hash
* @brief Check whether the current hash table is empty.
* @par Description: Check whether the current hash table is empty.
* If the hash table is empty, true is returned. Otherwise, false is returned.
* @param hash [IN] Handle of the hash table. The value range is valid pointer.
* @retval #true, indicating that the hash table is empty.
* @retval #false, indicating that the hash table is not empty.
* @see #BSL_HASH_Size
* @par Dependency: None
* @li bsl_hash.h: header file where the interface declaration is stored.
*/
bool BSL_HASH_Empty(const BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Obtain the number of nodes in the hash table.
* @par Description: Obtains the number of nodes in the hash table and returns the number of nodes.
* @param hash [IN] Handle of the hash table. The value range is valid pointer.
* @retval Number of hash nodes.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uint32_t BSL_HASH_Size(const BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Remove a specified node from the hash table.
* @par Description: Find the node based on the key, delete the node (release it),
* and release the memory of the corresponding node.
* @param hash [IN] Handle of the hash table. The value range is a valid pointer.
* @param key [IN] Remove a node key.
* @retval If the key exists,
* the next iterator (pointing to the address of the node) of the iterator where the key is located is returned.
* Otherwise, #BSL_HASH_IterEnd() is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Iterator BSL_HASH_Erase(BSL_HASH_Hash *hash, uintptr_t key);
/**
* @ingroup bsl_hash
* @brief Delete all nodes in the hash table.
* @par Description: Delete all nodes and reclaim the node memory. The hash table still exists, but there are no members
* @attention Note: If the user data contains private resources, need to register the free hook function during creation
* @param hash [IN] Handle of the hash table.
* @retval none.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
void BSL_HASH_Clear(BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Delete the hash table.
* @par Description: Delete the hash table. If a node exists in the table, delete the node first and reclaim the memory.
* @attention Note: If the user data contains private resources, need to register the free hook function during creation
* @param hash [IN] Handle of the hash table.
* @retval none.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
void BSL_HASH_Destory(BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Obtain the iterator of the first node in the hash table.
* @par Description: Obtains the iterator where the first node in the hash table is located.
* @param hash [IN] Handle of the hash table.
* @retval Iterator of the first node. If the hash is empty, #BSL_HASH_IterEnd() is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Iterator BSL_HASH_IterBegin(const BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Obtain the iterator reserved after the last node in the hash table.
* @par Description: Obtain the iterator reserved after the last node in the hash table.
* This node points to the last reserved hash bucket, which has no members.
* @param hash [IN] Handle of the hash table.
* @retval Iterator reserved after the last node.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Iterator BSL_HASH_IterEnd(const BSL_HASH_Hash *hash);
/**
* @ingroup bsl_hash
* @brief Obtain the iterator of the next node in the hash table.
* @par Description: Obtains the iterator of the next node in the hash table.
* @param hash [IN] Handle of the hash table.
* @param it [IN] Current iterator.
* @retval Next node iterator. If the current node is the last iterator, #BSL_HASH_IterEnd() is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
BSL_HASH_Iterator BSL_HASH_IterNext(const BSL_HASH_Hash *hash, BSL_HASH_Iterator it);
/**
* @ingroup bsl_hash
* @brief Obtain the key of the iterator.
* @par Description: Obtains the current key of the iterator in the hash table.
* @attention
* 1. When the hash pointer is null or iterator it is equal to #BSL_HASH_IterEnd(), this function returns 0.
* This function cannot distinguish whether the error code or user data,
* 2. Before calling this function, ensure that hash is a valid pointer
* and iterator it is not equal to #BSL_HASH_IterEnd().
* @param hash [IN] Handle of the hash table.
* @param it [IN] Current iterator.
* @retval Key corresponding to the iterator. If iterator it equals #BSL_HASH_IterEnd(), 0 is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uintptr_t BSL_HASH_HashIterKey(const BSL_HASH_Hash *hash, BSL_HASH_Iterator it);
/**
* @ingroup bsl_hash
* @brief Obtain the value of the iterator.
* @par Description: Obtains the current value of the iterator in the hash table.
* @attention
* 1. When the hash pointer is null or it is equal to #BSL_HASH_IterEnd(), the interface returns 0.
* This function cannot distinguish whether the error code or user data,
* 2. Before calling this function, ensure that hash is a valid pointer
* and iterator it is not equal to #BSL_HASH_IterEnd().
* @param hash [IN] Handle of the hash table.
* @param it [IN] Current iterator.
* @retval Value corresponding to the iterator. If iterator it equals #BSL_HASH_IterEnd(), 0 is returned.
* @par Dependency: None
* @li bsl_hash.h: header file where this function's declaration is located.
*/
uintptr_t BSL_HASH_IterValue(const BSL_HASH_Hash *hash, BSL_HASH_Iterator it);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_HASH */
#endif // BSL_HASH_H
| 2302_82127028/openHiTLS-examples_5062 | bsl/hash/include/bsl_hash.h | C | unknown | 18,600 |
/*
* This file is part of the openHiTLS project.
*
* openHiTLS is licensed under the Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @defgroup bsl_list bidirectional linked list
* @ingroup bsl
*/
#ifndef BSL_HASH_LIST_H
#define BSL_HASH_LIST_H
#include "hitls_build.h"
#ifdef HITLS_BSL_HASH
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @ingroup bsl_list
* @brief User data copy function prototype
* @attention Note: The source buffer length needs to be obtained by the caller.
* Because the data type and length are unknown, the hook function needs to be implemented by the service side.
* @param ptr [IN] Pointer to user data
* @param size [IN] User data copy length
* @retval Destination buffer. NULL indicates failure.
*/
typedef void *(*ListDupFunc)(void *ptr, size_t size);
/**
* @ingroup bsl_list
* @brief User memory release function prototype
* @par Description: resource release function prototype, which is generally used to release memory in batches.
* The memory may contain private resources, which need to be released by users.
* @param ptr [IN] Pointer to user data
* @retval None
*/
typedef void (*ListFreeFunc)(void *ptr);
/**
* @ingroup bsl_list
* @brief Match the function prototype.
* @par Description: used to match the query.
* @attention Note: Only the function prototype is defined here. Because the user query matching mechanism is unknown,
* the hook function needs to be implemented by the service side.
* @param node [IN] Algorithm structure node
* @param data [IN] Key information
* @retval true: Matching succeeded.
* @retval false Matching failure
*/
typedef bool (*ListMatchFunc)(const void *node, uintptr_t data);
/**
* @ingroup bsl_list
* @brief Compare function prototype
* @par Description: Compare function prototype, which is used in sorting.
* @attention Note: Only the comparison function prototype is defined here. The data type and length are unknown.
* Therefore, the hook function needs to be implemented by the service side.
* The current source code has a default comparison function. This function is not provided externally.
* If the default comparison method is not specified, it will be invoked.
* The comparison method is to convert the current data into a signed number for comparison,
* that is, to process the case with negative numbers in ascending order.
* If the data to be stored is of the unsigned integer type, The sorting result may not be expected at this time.
* To compare data in this case, we need to customize the comparison function.
* For example, for a BIGNUM A = uintptr_t(-1) and a BIGNUM B = 1ULL << 50, the current function considers A < B.
* Actually, A is greater than B.
* To sum up, the user should write the comparison function based on the data type
* (including descending order or other comparison rules).
*/
typedef int32_t (*ListKeyCmpFunc)(uintptr_t key1, uintptr_t key2);
/**
* @ingroup bsl_list
* @brief Hook for saving memory application and release.
*/
typedef struct {
ListDupFunc dupFunc;
ListFreeFunc freeFunc;
} ListDupFreeFuncPair;
/**
* @ingroup bsl_list
* list header
*/
typedef struct BslListSt BSL_List;
/**
* @ingroup bsl_list
* Linked list iterator (node) definition
*/
typedef struct BslListNodeSt *BSL_ListIterator;
/**
* @ingroup bsl_list
* @brief Initialize the linked list.
* @par Description: Initialize the linked list and
* register the user data dup function and user data resource free function as required.
* @attention
* 1. If the data to be stored is of the integer type and the length <= sizeof(uintptr_t),
* do not need to register dataFunc&dupFunc and assign it empty.
* 2. If the user data is string or other customized complex data type
* and the data life cycle is shorter than the node life cycle, user must register dataFunc->dupFunc for data copy.
* @param list [IN] Linked list
* @param dataFunc [IN] User data copy and release function pair. If dataFunc and dupFunc are not registered,
* the default data type is integer.
* @retval #BSL_SUCCESS 0 indicates that the linked list is successfully initialized.
*/
int32_t BSL_ListInit(BSL_List *list, const ListDupFreeFuncPair *dataFunc);
/**
* @ingroup bsl_list
* @brief Clear the node in the linked list and delete all nodes.
* @par Description: Clear the linked list node, delete all nodes, invoke the free function registered by the user
* to release user resources, and return to the status after initialization of the linked list.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The linked list is cleared successfully.
*/
int32_t BSL_ListClear(BSL_List *list);
/**
* @ingroup bsl_list
* @brief Deinitialize the linked list.
* @par Description: Deinitialize the linked list: Delete all nodes,
* invoke the free function registered by the user to release user resources, and deregister the hook function.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The linked list is successfully de-initialized.
*/
int32_t BSL_ListDeinit(BSL_List *list);
/**
* @ingroup bsl_list
* @brief Check whether the linked list is empty.
* @param list [IN] Linked list to be checked
* @retval #true 1: The linked list is null or no data exists.
* @retval #false 0: The linked list is not empty.
* @li bsl_list.h: header file where the API declaration is located.
*/
bool BSL_ListIsEmpty(const BSL_List *list);
/**
* @ingroup bsl_list
* @brief Obtain the number of nodes in the linked list.
* @param list [IN] Linked list
* @retval Number of linked list nodes
* @li bsl_list.h: header file where the API declaration is located.
*/
size_t BSL_ListSize(const BSL_List *list);
/**
* @ingroup bsl_list
* @brief Insert user data into the header of the linked list.
* @param list [IN] Linked list
* @param userData [IN] Data to be inserted or pointer to user private data
* @param userDataSize [IN] Data copy length. If the user has not registered the dupFunc, this parameter is not used.
* @retval #BSL_SUCCESS Data is successfully inserted.
* @li bsl_list.h: header file where this function declaration is located.
*/
int32_t BSL_ListPushFront(BSL_List *list, uintptr_t userData, size_t userDataSize);
/**
* @ingroup bsl_list
* @brief Insert user data to the end of the linked list.
* @param list [IN] Linked list
* @param userData [IN] Data to be inserted or pointer to user private data
* @param userDataSize [IN] Data copy length. If the user has not registered the dupFunc, this parameter is not used.
* @retval #BSL_SUCCESS Data is successfully inserted.
* @li bsl_list.h: header file where this function declaration is located.
*/
int32_t BSL_ListPushBack(BSL_List *list, uintptr_t userData, size_t userDataSize);
/**
* @ingroup bsl_list
* @brief POP a node from the header of the linked list.
* @par Description: Remove the head node from the linked list and release the node memory.
* If the free function is registered during initialization, the hook function is called to release private resources.
* If the linked list is empty, nothing will be done.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The header is removed successfully.
* @li bsl_list.h: header file where the API declaration is located.
*/
int32_t BSL_ListPopFront(BSL_List *list);
/**
* @ingroup bsl_list
* @brief POP a node from the end of the linked list.
* @par Description: Remove the tail node from the linked list and release the node memory.
* If the free function is registered during initialization, the hook function is called to release private resources.
* If the linked list is empty, nothing will be done.
* @param list [IN] Linked list
* @retval #BSL_SUCCESS 0. The tail is removed successfully.
* @li bsl_list.h: header file where the API declaration is located.
*/
int32_t BSL_ListPopBack(BSL_List *list);
/**
* @ingroup bsl_list
* @brief Access the header node of the linked list and return the user data of the header node.
* @par Description: Access the header node of the linked list and return the user data of the header node.
* @attention Note: If the linked list is empty,
* it cannot be distinguished whether the linked list is empty and the returned data is 0.
* Therefore, before calling this function, we must check whether the linked list is empty.
* @param list [IN] Linked list
* @retval User data/pointer of the head node. If the linked list is empty, 0 is returned.
* @li bsl_list.h: header file where this function declaration is located.
*/
uintptr_t BSL_ListFront(const BSL_List *list);
/**
* @ingroup bsl_list
* @brief Access the tail node of the linked list and return the user data of the tail node.
* @attention Note: If the linked list is empty,
* it cannot be distinguished whether the linked list is empty and the returned data is 0.
* Therefore, we must check whether the linked list is empty before calling this function.
* @param list [IN] Linked list
* @retval User data/pointer of the tail node. If the linked list is empty, 0 is returned.
* @li bsl_list.h: header file where the API declaration is located.
*/
uintptr_t BSL_ListBack(const BSL_List *list);
/**
* @ingroup bsl_list
* @brief Obtain the iterator of the header node of the linked list.
* @param list [IN] Linked list
* @retval Head node iterator of the linked list. If the linked list is empty, it points to the header.
* @li bsl_list.h: header file where this function declaration is located.
*/
BSL_ListIterator BSL_ListIterBegin(const BSL_List *list);
/**
* @ingroup bsl_list
* @brief Obtain the iterator of the next node of the tail.
* @param list [IN] Linked list
* @attention If the input list is NULL, NULL will be returned. Therefore, user need to use correct parameters.
* @retval Next node iterator of the tail (pointing to the head of the linked list).
* @li bsl_list.h: header file where the API declaration is located.
*/
BSL_ListIterator BSL_ListIterEnd(BSL_List *list);
/**
* @ingroup bsl_list
* @brief Obtain the iterator of the previous node.
* @param list [IN] Linked list
* @param it [IN] Iterator
* @attention If the input list is NULL or iterator it is not a valid part of the list, NULL is returned.
* Therefore, user need to use the correct parameter.
* @retval list is not empty, return the previous node iterator.
* @retval list is NULL, and NULL is returned.
* @li bsl_list.h: header file where the API declaration is located.
*/
BSL_ListIterator BSL_ListIterPrev(const BSL_List *list, const BSL_ListIterator it);
/**
* @ingroup bsl_list
* @brief Obtain the iterator of the next node.
* @param list [IN] Linked list
* @param it [IN] Iterator
* @attention If the input list is NULL or iterator it is not a valid part of the list, NULL is returned.
* Therefore, user need to use the correct parameter.
* @retval Returns the iterator of the next node if the value is not null.
* @retval list is NULL, and NULL is returned.
* @li bsl_list.h: header file where the API declaration is located.
*/
BSL_ListIterator BSL_ListIterNext(const BSL_List *list, const BSL_ListIterator it);
/**
* @ingroup bsl_list
* @brief Insert data before the node pointed to by the specified iterator.
* @param list [IN] Linked list
* @param it [IN] Current iterator position
* @param userData [IN] Data to be inserted or pointer to user private data
* @param userDataSize [IN] Data copy length. If the user has not registered the dupFunc, this parameter is not used.
* @retval #BSL_SUCCESS Data is successfully inserted.
* @li bsl_list.h: header file where this function declaration is located.
*/
int32_t BSL_ListInsert(BSL_List *list, const BSL_ListIterator it, uintptr_t userData, size_t userDataSize);
/**
* @ingroup bsl_list
* @brief Delete a specified node from the linked list and release the node memory.
* @par Description: Delete the specified node from the linked list and release the node memory.
* If the free function is registered during initialization,
* the hook function is invoked to release private resources such as handles and pointers in user data
* @attention If the input list is NULL or iterator it is not a valid part of the list, NULL is returned.
* Therefore, user need to use the correct parameter.
* @param list [IN] Linked list
* @param it [IN] Iterator of the node to be deleted.
* @retval Next node iterator of the deleted node. If the deleted node is the tail node,
* the returned iterator points to the header of the linked list.
* @li bsl_list.h: header file where this function declaration is located.
*/
BSL_ListIterator BSL_ListIterErase(BSL_List *list, BSL_ListIterator it);
/**
* @ingroup bsl_list
* @brief Obtain user data.
* @attention The caller must ensure the validity of the parameter. If the input parameter is invalid, 0 is returned.
* The caller cannot distinguish whether the returned value 0 is normal data
* or whether the returned value is 0 due to invalid parameters.
* @param it [IN] Linked list iterator
* @retval User data
* @li bsl_list.h: header file where this function declaration is located.
*/
uintptr_t BSL_ListIterData(const BSL_ListIterator it);
/**
* @ingroup bsl_list
* @brief Searches for the desired iterator, that is, the node pointer,
* based on the user-defined iterator matching function.
* @par Description: Searches for the desired iterator, that is, the node pointer,
* based on the user-defined iterator matching function.
* @attention
* 1. Traversefrom the header and call the matching function for each node in turn
* until the first matching node is found or the traversal ends at the tail of the linked list.
* 2. The first input parameter address of the matching function hook entered by the user
* is the userdata of each node to be searched. The input parameter type is uintptr_t.
* 3. If the input list is NULL or the comparison function is NULL, NULL is returned.
* Therefore, user need to use correct parameters.
* @param list [IN] Linked list
* @param iterCmpFunc [IN] Hook of match function.
* @param data [IN] Data information
* @retval not NULL Query succeeded, the matching node iterator is returned.
* @retval NULL Query failed.
* @li bsl_list.h: header file where this function declaration is located.
*/
BSL_ListIterator BSL_ListIterFind(BSL_List *list, ListKeyCmpFunc iterCmpFunc, uintptr_t data);
#ifdef __cplusplus
}
#endif
#endif /* HITLS_BSL_HASH */
#endif // BSL_HASH_LIST_H
| 2302_82127028/openHiTLS-examples_5062 | bsl/hash/include/bsl_hash_list.h | C | unknown | 15,245 |