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 |
|---|---|---|---|---|---|
package com.hmdp.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_blog_comments")
public class BlogComments implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 用户id
*/
private Long userId;
/**
* 探店id
*/
private Long blogId;
/**
* 关联的1级评论id,如果是一级评论,则值为0
*/
private Long parentId;
/**
* 回复的评论id
*/
private Long answerId;
/**
* 回复的内容
*/
private String content;
/**
* 点赞数
*/
private Integer liked;
/**
* 状态,0:正常,1:被举报,2:禁止查看
*/
private Boolean status;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/entity/BlogComments.java | Java | unknown | 1,327 |
package com.hmdp.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_follow")
public class Follow implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 用户id
*/
private Long userId;
/**
* 关联的用户id
*/
private Long followUserId;
/**
* 创建时间
*/
private LocalDateTime createTime;
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/entity/Follow.java | Java | unknown | 839 |
package com.hmdp.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_seckill_voucher")
public class SeckillVoucher implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 关联的优惠券的id
*/
@TableId(value = "voucher_id", type = IdType.INPUT)
private Long voucherId;
/**
* 库存
*/
private Integer stock;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 生效时间
*/
private LocalDateTime beginTime;
/**
* 失效时间
*/
private LocalDateTime endTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/entity/SeckillVoucher.java | Java | unknown | 1,038 |
package com.hmdp.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_shop")
public class Shop implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 商铺名称
*/
private String name;
/**
* 商铺类型的id
*/
private Long typeId;
/**
* 商铺图片,多个图片以','隔开
*/
private String images;
/**
* 商圈,例如陆家嘴
*/
private String area;
/**
* 地址
*/
private String address;
/**
* 经度
*/
private Double x;
/**
* 维度
*/
private Double y;
/**
* 均价,取整数
*/
private Long avgPrice;
/**
* 销量
*/
private Integer sold;
/**
* 评论数量
*/
private Integer comments;
/**
* 评分,1~5分,乘10保存,避免小数
*/
private Integer score;
/**
* 营业时间,例如 10:00-22:00
*/
private String openHours;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
@TableField(exist = false)
private Double distance;
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/entity/Shop.java | Java | unknown | 1,731 |
package com.hmdp.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false) //不包含父类的属性
@Accessors(chain = true)
@TableName("tb_shop_type")
public class ShopType implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 类型名称
*/
private String name;
/**
* 图标
*/
private String icon;
/**
* 顺序
*/
private Integer sort;
/**
* 创建时间
*/
@JsonIgnore
private LocalDateTime createTime;
/**
* 更新时间
*/
@JsonIgnore
private LocalDateTime updateTime;
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/entity/ShopType.java | Java | unknown | 1,082 |
package com.hmdp.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 手机号码
*/
private String phone;
/**
* 密码,加密存储
*/
private String password;
/**
* 昵称,默认是随机字符
*/
private String nickName;
/**
* 用户头像
*/
private String icon = "";
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/entity/User.java | Java | unknown | 1,068 |
package com.hmdp.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_user_info")
public class UserInfo implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键,用户id
*/
@TableId(value = "user_id", type = IdType.AUTO)
private Long userId;
/**
* 城市名称
*/
private String city;
/**
* 个人介绍,不要超过128个字符
*/
private String introduce;
/**
* 粉丝数量
*/
private Integer fans;
/**
* 关注的人的数量
*/
private Integer followee;
/**
* 性别,0:男,1:女
*/
private Boolean gender;
/**
* 生日
*/
private LocalDate birthday;
/**
* 积分
*/
private Integer credits;
/**
* 会员级别,0~9级,0代表未开通会员
*/
private Boolean level;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/entity/UserInfo.java | Java | unknown | 1,429 |
package com.hmdp.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_voucher")
public class Voucher implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 商铺id
*/
private Long shopId;
/**
* 代金券标题
*/
private String title;
/**
* 副标题
*/
private String subTitle;
/**
* 使用规则
*/
private String rules;
/**
* 支付金额
*/
private Long payValue;
/**
* 抵扣金额
*/
private Long actualValue;
/**
* 优惠券类型
*/
private Integer type;
/**
* 优惠券类型
*/
private Integer status;
/**
* 库存
*/
@TableField(exist = false)
private Integer stock;
/**
* 生效时间
*/
@TableField(exist = false)
private LocalDateTime beginTime;
/**
* 失效时间
*/
@TableField(exist = false)
private LocalDateTime endTime;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/entity/Voucher.java | Java | unknown | 1,652 |
package com.hmdp.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_voucher_order")
public class VoucherOrder implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.INPUT)
private Long id;
/**
* 下单的用户id
*/
private Long userId;
/**
* 购买的代金券id
*/
private Long voucherId;
/**
* 支付方式 1:余额支付;2:支付宝;3:微信
*/
private Integer payType;
/**
* 订单状态,1:未支付;2:已支付;3:已核销;4:已取消;5:退款中;6:已退款
*/
private Integer status;
/**
* 下单时间
*/
private LocalDateTime createTime;
/**
* 支付时间
*/
private LocalDateTime payTime;
/**
* 核销时间
*/
private LocalDateTime useTime;
/**
* 退款时间
*/
private LocalDateTime refundTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/entity/VoucherOrder.java | Java | unknown | 1,429 |
package com.hmdp.mapper;
import com.hmdp.entity.BlogComments;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface BlogCommentsMapper extends BaseMapper<BlogComments> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/mapper/BlogCommentsMapper.java | Java | unknown | 194 |
package com.hmdp.mapper;
import com.hmdp.entity.Blog;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface BlogMapper extends BaseMapper<Blog> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/mapper/BlogMapper.java | Java | unknown | 170 |
package com.hmdp.mapper;
import com.hmdp.entity.Follow;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface FollowMapper extends BaseMapper<Follow> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/mapper/FollowMapper.java | Java | unknown | 176 |
package com.hmdp.mapper;
import com.hmdp.entity.SeckillVoucher;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface SeckillVoucherMapper extends BaseMapper<SeckillVoucher> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/mapper/SeckillVoucherMapper.java | Java | unknown | 200 |
package com.hmdp.mapper;
import com.hmdp.entity.Shop;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface ShopMapper extends BaseMapper<Shop> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/mapper/ShopMapper.java | Java | unknown | 171 |
package com.hmdp.mapper;
import com.hmdp.entity.ShopType;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface ShopTypeMapper extends BaseMapper<ShopType> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/mapper/ShopTypeMapper.java | Java | unknown | 183 |
package com.hmdp.mapper;
import com.hmdp.entity.UserInfo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/mapper/UserInfoMapper.java | Java | unknown | 183 |
package com.hmdp.mapper;
import com.hmdp.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface UserMapper extends BaseMapper<User> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/mapper/UserMapper.java | Java | unknown | 171 |
package com.hmdp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hmdp.entity.Voucher;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface VoucherMapper extends BaseMapper<Voucher> {
List<Voucher> queryVoucherOfShop(@Param("shopId") Long shopId);
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/mapper/VoucherMapper.java | Java | unknown | 316 |
package com.hmdp.mapper;
import com.hmdp.entity.VoucherOrder;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface VoucherOrderMapper extends BaseMapper<VoucherOrder> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/mapper/VoucherOrderMapper.java | Java | unknown | 194 |
package com.hmdp.service;
import com.hmdp.entity.BlogComments;
import com.baomidou.mybatisplus.extension.service.IService;
public interface IBlogCommentsService extends IService<BlogComments> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/IBlogCommentsService.java | Java | unknown | 199 |
package com.hmdp.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hmdp.dto.Result;
import com.hmdp.entity.Blog;
public interface IBlogService extends IService<Blog> {
/**
* 查询热门博客
*
* @param current 当前
* @return {@link Result}
*/
Result queryHotBlog(Integer current);
/**
* 通过id查询博客
*
* @param id id
* @return {@link Result}
*/
Result queryBlogById(Long id);
/**
* 点赞博客
*
* @param id id
* @return {@link Result}
*/
Result likeBlog(Long id);
/**
* 查询博客点赞排行榜
*
* @param id id
* @return {@link Result}
*/
Result queryBlogLikesById(Long id);
/**
* 保存博客
*
* @param blog 博客
* @return {@link Result}
*/
Result saveBlog(Blog blog);
/**
* 查询博客遵循
*
* @param max 马克斯
* @param offset 抵消
* @return {@link Result}
*/
Result queryBlogOfFollow(Long max, Integer offset);
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/IBlogService.java | Java | unknown | 1,091 |
package com.hmdp.service;
import com.hmdp.dto.Result;
import com.hmdp.entity.Follow;
import com.baomidou.mybatisplus.extension.service.IService;
public interface IFollowService extends IService<Follow> {
Result follow(Long followUserId, Boolean isFollow);
Result isFollow(Long followUserId);
Result followCommons(Long id);
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/IFollowService.java | Java | unknown | 342 |
package com.hmdp.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hmdp.entity.SeckillVoucher;
public interface ISeckillVoucherService extends IService<SeckillVoucher> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/ISeckillVoucherService.java | Java | unknown | 205 |
package com.hmdp.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
public interface IShopService extends IService<Shop> {
/**
* 根据id查询商户信息
*
* @param id id
* @return {@link Result}
*/
Result queryById(Long id);
/**
* 更新店铺信息
*
* @param shop 商店
* @return {@link Result}
*/
Result update(Shop shop);
Result queryShopByType(Integer typeId, Integer current, Double x, Double y);
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/IShopService.java | Java | unknown | 559 |
package com.hmdp.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
public interface IShopTypeService extends IService<ShopType> {
/**
* 获取商品类型列表
*
* @return {@link Result}
*/
Result getTypeList();
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/IShopTypeService.java | Java | unknown | 326 |
package com.hmdp.service;
import com.hmdp.entity.UserInfo;
import com.baomidou.mybatisplus.extension.service.IService;
public interface IUserInfoService extends IService<UserInfo> {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/IUserInfoService.java | Java | unknown | 188 |
package com.hmdp.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;
import javax.servlet.http.HttpSession;
public interface IUserService extends IService<User> {
Result sendCode(String phone, HttpSession session);
Result login(LoginFormDTO loginForm, HttpSession session);
Result sign();
Result signCount();
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/IUserService.java | Java | unknown | 443 |
package com.hmdp.service;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.baomidou.mybatisplus.extension.service.IService;
public interface IVoucherOrderService extends IService<VoucherOrder> {
Result seckillVoucher(Long voucherId);
void createVoucherOrder(VoucherOrder voucherOrder);
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/IVoucherOrderService.java | Java | unknown | 328 |
package com.hmdp.service;
import com.hmdp.dto.Result;
import com.hmdp.entity.Voucher;
import com.baomidou.mybatisplus.extension.service.IService;
public interface IVoucherService extends IService<Voucher> {
Result queryVoucherOfShop(Long shopId);
void addSeckillVoucher(Voucher voucher);
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/IVoucherService.java | Java | unknown | 303 |
package com.hmdp.service.impl;
import com.hmdp.entity.BlogComments;
import com.hmdp.mapper.BlogCommentsMapper;
import com.hmdp.service.IBlogCommentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
@Service
public class BlogCommentsServiceImpl extends ServiceImpl<BlogCommentsMapper, BlogComments> implements IBlogCommentsService {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/impl/BlogCommentsServiceImpl.java | Java | unknown | 412 |
package com.hmdp.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
@Resource
private IUserService userService;
@Resource
private IFollowService followService;
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryHotBlog(Integer current) {
// 根据用户查询
Page<Blog> page = query()
.orderByDesc("liked")
.page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
// 获取当前页数据
List<Blog> records = page.getRecords();
// 查询用户
records.forEach(blog -> {
queryBlogUser(blog);
isBlogLiked(blog);
});
return Result.ok(records);
}
@Override
public Result queryBlogById(Long id) {
//查询blog
Blog blog = getById(id);
if (blog == null) {
return Result.fail("博客不存在");
}
queryBlogUser(blog);
isBlogLiked(blog);
return Result.ok(blog);
}
@Override
public Result likeBlog(Long id) {
//获取当前登陆用户
Long userId = UserHolder.getUser().getId();
//一个用户只能点一次赞
String key = RedisConstants.BLOG_LIKED_KEY + id;
Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
if (score==null) {
//如果未点赞 可以点赞
//写数据库
boolean isSuccess = update().setSql("liked=liked+1").eq("id", id).update();
//保存点赞的 用户id到 redis 的 set集合
if (isSuccess){
stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
}
log.debug("点赞成功");
} else {
//如果已经点赞 取消点赞
boolean isSuccess = update().setSql("liked=liked-1").eq("id", id).update();
log.debug("取消点赞");
//数据库-1
if (isSuccess){
stringRedisTemplate.opsForZSet().remove(key,userId.toString());
}
//redis删除数据
}
return Result.ok();
}
@Override
public Result queryBlogLikesById(Long id) {
String key = RedisConstants.BLOG_LIKED_KEY + id;
//查询top5的点赞用户
Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 6);
if (top5==null||top5.isEmpty()){
return Result.ok(Collections.emptyList());
}
//解析出用户id
List<Long> userIds = top5.stream().map(Long::valueOf).collect(Collectors.toList());
//根据id查询用户 where id in (5,1) order by field (id,5,1) 用 in 查出的用户跟给的 id 顺序不一致
String idStr = StrUtil.join(",", userIds);
List<UserDTO> userDTOS = userService.query()
.in("id",userIds)
.last("ORDER BY FIELD(id,"+idStr+")").list()
.stream()
.map(user -> BeanUtil.copyProperties(user, UserDTO.class)
).collect(Collectors.toList());
//返回
return Result.ok(userDTOS);
}
@Override
public Result saveBlog(Blog blog) {
// 获取登录用户
UserDTO user = UserHolder.getUser();
blog.setUserId(user.getId());
// 保存探店博文
boolean isSuccess = save(blog);
if (!isSuccess){
return Result.fail("新增笔记失败");
}
log.debug("新增笔记成功");
//新增笔记时 将笔记推送给所有粉丝
List<Follow> follows = followService.lambdaQuery()
.eq(Follow::getFollowUserId, user.getId())
.list();
for (Follow follow : follows) {
Long userId = follow.getUserId();
String key="feed:"+userId;
stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
}
// 返回id
return Result.ok(blog.getId());
}
@Override
public Result queryBlogOfFollow(Long max, Integer offset) {
UserDTO user = UserHolder.getUser();
//查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count
String key="feed:"+user.getId();
Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
.reverseRangeByScoreWithScores(key, 0, max, offset, 2);
if (typedTuples==null||typedTuples.isEmpty()){
return Result.ok();
}
//解析数据 blogId minTime offset
List<Long> ids=new ArrayList<>(typedTuples.size());
long minTime =0;
int os=1;
for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
//获取id
String blogId = typedTuple.getValue();
ids.add(Long.valueOf(blogId));
// 获取时间戳
long time = typedTuple.getScore().longValue();
// 判断值是否是最小值
if (time==minTime){
os++;
}else {
minTime = time;
os=1;
}
}
//根据 id 查询blog (查出的结果必须是有序的,不能用自带的 listByIds())
List<Blog> blogs=new ArrayList<>(ids.size());
for (Long id : ids) {
Blog blog = getById(id);
blogs.add(blog);
}
blogs.forEach(blog -> {
queryBlogUser(blog);
isBlogLiked(blog);
});
//封装 返回
ScrollResult scrollResult = new ScrollResult();
scrollResult.setList(blogs);
scrollResult.setOffset(os);
scrollResult.setMinTime(minTime);
return Result.ok(scrollResult);
}
private void queryBlogUser(Blog blog) {
Long userId = blog.getUserId();
User user = userService.getById(userId);
blog.setName(user.getNickName());
blog.setIcon(user.getIcon());
}
private void isBlogLiked(Blog blog) {
//获取当前登陆用户
UserDTO user = UserHolder.getUser();
if (user==null){
return;
}
Long userId = user.getId();
//判断当前用户时候点赞
String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
blog.setIsLike(score!=null);
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/impl/BlogServiceImpl.java | Java | unknown | 7,467 |
package com.hmdp.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private IUserService userService;
@Override
public Result follow(Long followUserId, Boolean isFollow) {
Long userId = UserHolder.getUser().getId();
String key="follow:"+userId;
// 判断 关注 还是 取关 (新增用户或删除)
if(isFollow){
Follow follow = new Follow();
follow.setFollowUserId(followUserId);
follow.setUserId(userId);
boolean isSuccess = save(follow);
if(isSuccess){
stringRedisTemplate.opsForSet().add(key,followUserId.toString());
}
}else {
// 取关
remove(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", followUserId));
stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
}
return Result.ok();
}
// 查询是否关注
@Override
public Result isFollow(Long followUserId) {
Long userId = UserHolder.getUser().getId();
Long count = query().eq("follow_user_id", followUserId).eq("follow_user_id", userId).count();
return Result.ok(count>0);
}
@Override
public Result followCommons(Long id) {
Long userId = UserHolder.getUser().getId();
String key1="follow:"+userId;
String key2="follow:"+id;
//求 关注的用户 的 交集
Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
if(intersect==null||intersect.isEmpty()){
return Result.ok(Collections.emptyList());
}
// 解析 id 集合
List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
Stream<UserDTO> users = userService.listByIds(ids).stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class));
return Result.ok(users);
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/impl/FollowServiceImpl.java | Java | unknown | 2,784 |
package com.hmdp.service.impl;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
@Service
public class SeckillVoucherServiceImpl extends ServiceImpl<SeckillVoucherMapper, SeckillVoucher> implements ISeckillVoucherService {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/impl/SeckillVoucherServiceImpl.java | Java | unknown | 426 |
package com.hmdp.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static com.hmdp.utils.RedisConstants.*;
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private CacheClient cacheClient;
@Override
public Result queryById(Long id) {
// Shop shop = queryWithMutex(id); 互斥锁解决缓存击穿
// Shop shop = queryWithLogicalExpire(id); 逻辑过期解决缓存击穿
// Shop shop = cacheClient // Redis 工具类
// .queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById,
// CACHE_SHOP_TTL, TimeUnit.MINUTES);
Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class,
this::getById, 20L, TimeUnit.SECONDS);
if (shop == null) {
return Result.fail("店铺不存在!");
}
return Result.ok(shop);
}
// //解决缓存穿透
// public Shop queryWithPassThrough(Long id){
// String key=CACHE_SHOP_KEY+id;
// // 1.从 redis 查商铺缓存
// String shopJson = stringRedisTemplate.opsForValue().get(key);
// if(StrUtil.isNotBlank(shopJson)){
// Shop shop = JSONUtil.toBean(shopJson, Shop.class);
// return shop;
// }
// // 判断命中的是否是存入的空数据(解决缓存穿透)
// if(shopJson!=null){
// return null;
// }
// // 2.不存在,查数据库,并写入 redis
// Shop shop = getById(id);
// if(shop == null){
// // 将空值写入 redis,并设置过期时间(解决缓存穿透)
// stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
// return null;
// }
// stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
// return shop;
// }
// // 解决缓存穿透和击穿
// public Shop queryWithMutex(Long id){
// String key=CACHE_SHOP_KEY+id;
// // 1.从 redis 查商铺缓存
// String shopJson = stringRedisTemplate.opsForValue().get(key);
// if(StrUtil.isNotBlank(shopJson)){
// Shop shop = JSONUtil.toBean(shopJson, Shop.class);
// return shop;
// }
// // 判断命中的是否是存入的空数据(解决缓存穿透)
// if(shopJson!=null){
// return null;
// }
// // 2.缓存重建
// // 2.1 获取互斥锁
// String lockKey=LOCK_SHOP_KEY+id;
// Shop shop = null;
// try {
// boolean isLock = tryLock(lockKey);
// // 2.2 判断是否获取成功
// if(!isLock){
// // 2.3 失败则休眠并重试
// Thread.sleep(50);
// return queryWithMutex(id); //递归循环
// }
// // 2.4 成功则查数据库,并写入 redis
// shop = getById(id);
// Thread.sleep(200); // 模拟重建的延时
// if(shop == null){
// // 将空值写入 redis,并设置过期时间(解决缓存穿透)
// stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
// return null;
// }
// stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// } finally {
// // 2.5 释放锁
// unLock(lockKey);
// }
// return shop;
// }
// // 线程池
// private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
// // 逻辑过期(解决击穿)
// public Shop queryWithLogicalExpire(Long id){
// String key=CACHE_SHOP_KEY+id;
// // 1.从 redis 查商铺缓存
// String shopJson = stringRedisTemplate.opsForValue().get(key);
// if(StrUtil.isBlank(shopJson)){
// return null;
// }
// // 2.存在,反序列化,判断逻辑是否过期
// RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
// JSONObject data = (JSONObject)redisData.getData();
// Shop shop = JSONUtil.toBean(data, Shop.class);
// LocalDateTime expireTime = redisData.getExpireTime();
// // 2.1 未过期,直接返回店铺信息
// if(expireTime.isAfter(LocalDateTime.now())){
// return shop;
// }
// // 2.2 过期,需要重建缓存(利用互斥锁)
// String lockKey=LOCK_SHOP_KEY+id;
// boolean isLock = tryLock(lockKey);
// if(isLock){
// // 开启独立线程
// CACHE_REBUILD_EXECUTOR.submit(()->{
// try {
// this.saveShop2Redis(id,20L);
// } catch (Exception e) {
// throw new RuntimeException(e);
// } finally {
// unLock(lockKey);
// }
// });
// }
// return shop;
// }
//
// // 创建锁和释放锁
// private boolean tryLock(String key){
// Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
// return BooleanUtil.isTrue(flag);
// }
// private void unLock(String key){
// stringRedisTemplate.delete(key);
// }
// // 设置逻辑过期时间(从库中查店铺,逻辑过期时间字段只在缓存中有)
// public void saveShop2Redis(Long id,Long expireSeconds) throws InterruptedException {
// Shop shop = getById(id);
// Thread.sleep(200);
// RedisData redisData = new RedisData();
// redisData.setData(shop);
// redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
// stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
// }
@Override
@Transactional // 如果异常,事务回滚
public Result update(Shop shop) {
Long id = shop.getId();
if (id==null){
return Result.fail("店铺 id 不能为空");
}
// 1.更新数据库
updateById(shop);
// 2.删除缓存
stringRedisTemplate.delete(CACHE_SHOP_KEY+id);
return Result.ok();
}
@Override
public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
// 判断是否需要根据坐标查询
if(x==null || y==null){
// 不需要,直接查数据库
Page<Shop> page = query().eq("type_id", typeId)
.page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
return Result.ok(page.getRecords());
}
// 计算分页参数
int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
// 查询 redis,按照距离排序、分页。结果:shopId、distance
String key = SHOP_GEO_KEY+typeId;
// GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
.search(key,
GeoReference.fromCoordinate(x, y),
new Distance(5000), // 搜 5000米范围内的
RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
);
// 解析出 id
if(results==null){
return Result.ok(Collections.emptyList());
}
List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
if(list.size()<=from){
// 没有下一页
return Result.ok(Collections.emptyList());
}
// 截取 from 到 end
List<Long> ids=new ArrayList<>();
Map<String,Distance> distanceMap=new HashMap<>(list.size());
list.stream().skip(from).forEach(result->{
String shopIdStr = result.getContent().getName();
ids.add(Long.valueOf(shopIdStr));
Distance distance = result.getDistance();
distanceMap.put(shopIdStr,distance);
});
// 根据 店铺id 查取店铺,并将 distance 给店铺
String idStr = StrUtil.join(",", ids);
List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
for (Shop shop : shops) {
shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
}
return Result.ok(shops);
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/impl/ShopServiceImpl.java | Java | unknown | 9,703 |
package com.hmdp.service.impl;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result getTypeList() {
String typeKey = RedisConstants.CACHE_TYPE_KEY;
try {
// 从Redis查询
List<String> typeJsonList = stringRedisTemplate.opsForList().range(typeKey, 0, -1);
if (typeJsonList != null && !typeJsonList.isEmpty()) {
// 转换并返回
List<ShopType> typeList = new ArrayList<>();
for (String json : typeJsonList) {
typeList.add(JSONUtil.toBean(json, ShopType.class));
}
return Result.ok(typeList);
}
} catch (Exception e) {
// 记录日志,Redis异常时不影响后续流程
log.error("Redis操作异常", e);
}
// Redis无数据或异常,查询数据库
List<ShopType> typeList = query().orderByAsc("sort").list();
// 写入Redis(同样可以加try-catch,避免缓存失败影响主流程)
try {
List<String> jsonList = typeList.stream()
.map(JSONUtil::toJsonStr)
.collect(Collectors.toList());
stringRedisTemplate.opsForList().rightPushAll(typeKey, jsonList);
stringRedisTemplate.expire(typeKey, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
} catch (Exception e) {
log.error("Redis写入异常", e);
}
return Result.ok(typeList);
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/impl/ShopTypeServiceImpl.java | Java | unknown | 2,219 |
package com.hmdp.service.impl;
import com.hmdp.entity.UserInfo;
import com.hmdp.mapper.UserInfoMapper;
import com.hmdp.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/impl/UserInfoServiceImpl.java | Java | unknown | 383 |
package com.hmdp.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result sendCode(String phone, HttpSession session) {
// 1.校验手机号格式
if(RegexUtils.isPhoneInvalid(phone)){
return Result.fail("手机号格式错误!");
}
//2.符合,生成验证码
String code = RandomUtil.randomNumbers(6);
//3.保存验证码到 redis (key:phone,value:code)
stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
//4.发送验证码
log.debug("发送短信验证码成功");
log.debug(code);
//5.返回 ok
return Result.ok();
}
@Override
public Result login(LoginFormDTO loginForm, HttpSession session) {
// 1. 校验手机号格式
String phone = loginForm.getPhone();
if (RegexUtils.isPhoneInvalid(phone)) {
return Result.fail("手机号格式错误!");
}
// 2. 校验验证码(从 Redis 获取)
String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
String inputCode = loginForm.getCode();
if (cacheCode == null || !cacheCode.equals(inputCode)) {
return Result.fail("验证码错误或已过期");
}
// 3. 根据手机号查询用户(不存在则创建)
User user = query().eq("phone", phone).one();
if (user == null) {
user = createUserWithPhone(phone);
}
// 4. 生成登录 token,转换用户信息为 Redis Hash 格式
String token = UUID.randomUUID().toString();
UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
Map<String, Object> userMap = BeanUtil.beanToMap(
userDTO,
new HashMap<>(),
CopyOptions.create()
.setIgnoreNullValue(true)
.setFieldValueEditor((fieldName, fieldValue) ->
fieldValue != null ? fieldValue.toString() : "")
);
try {
stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, userMap);
stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);
} catch (Exception e) {
stringRedisTemplate.delete(LOGIN_USER_KEY + token);
log.error("用户登录:Redis 存储失败", e);
return Result.fail("登录失败,请重试");
}
// 7. 返回登录成功的 token
log.debug("用户登录成功");
return Result.ok(token);
}
@Override
public Result sign() {
Long userId = UserHolder.getUser().getId();
LocalDateTime now = LocalDateTime.now();
String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
String key=USER_SIGN_KEY+userId+keySuffix;
int dayOfMonth = now.getDayOfMonth();
// 写入 redis setbit key offset 1
stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
return Result.ok();
}
//统计从今天往前的连续签到次数
@Override
public Result signCount() {
Long userId = UserHolder.getUser().getId();
LocalDateTime now = LocalDateTime.now();
String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
String key=USER_SIGN_KEY+userId+keySuffix;
int dayOfMonth = now.getDayOfMonth();
// 获取本月截止今天为止的所有签到记录,返回的是一个十进制数字 (共dayOfMonth位)
// bitfield sign:1:202509 get u14 0
List<Long> result = stringRedisTemplate.opsForValue().bitField(
key, BitFieldSubCommands.create()
.get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
.valueAt(0)
);
if(result==null || result.isEmpty()){
return Result.ok(0);
}
Long num = result.get(0);
if(num==null || num==0){
return Result.ok(0);
}
// 循环遍历,与 1 做与运算,得到数字的最后一个 bit 位置
int count=0;
while (true){
if((num & 1)==0){
// 该 bit 位为0,未签到,结束
break;
}else {
// 不为0,已签到,计数器+1
count++;
}
// 数字右移 1 位,用前一个 bit位 与1运算
num >>>=1;
}
return Result.ok(count);
}
private User createUserWithPhone(String phone) {
User user = new User();
user.setPhone(phone);
user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
save(user); // mybatisplus 自带的
return user;
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/impl/UserServiceImpl.java | Java | unknown | 6,037 |
package com.hmdp.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import io.reactivex.Single;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
@Resource
private ISeckillVoucherService seckillVoucherService;
@Resource
private RedisIdWorker redisWorker;
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private RedissonClient redissonClient;
private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
static {
SECKILL_SCRIPT=new DefaultRedisScript<>();
SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua")); // resources 下路径
SECKILL_SCRIPT.setResultType(Long.class);
}
// 创建线程池
private static final ExecutorService SECKILL_ORDER_EXECUTOR= Executors.newSingleThreadExecutor();
@PostConstruct
private void init() {
// 一旦初始化完毕就要执行这个线程任务(从阻塞队列中取出任务并创建订单)
SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
}
// 子线程任务
private class VoucherOrderHandler implements Runnable{
String queueName="stream.orders";
@Override
public void run() {
while (true) {
try {
// 1、获取消息队列中的订单信息
List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
Consumer.from("g1", "c1"),
StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
StreamOffset.create(queueName, ReadOffset.lastConsumed())
);
// 2、判断消息是否获取成功
if(list==null||list.isEmpty()){
// 2.1、获取失败,继续下一次循环
continue;
}
// 2.2、获取成功,可以创建订单
// 解析信息
MapRecord<String, Object, Object> record = list.get(0);
Map<Object, Object> values = record.getValue();
VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
handleVoucherOrder(voucherOrder);
// 3、ACK 确认
stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
} catch (Exception e) {
log.error("处理订单异常",e);
handlePendingList(); // 处理消息队列中异常的消息
}
}
}
private void handlePendingList() {
while (true) {
try {
// 1、获取 pending-list 中的订单信息
List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
Consumer.from("g1", "c1"),
StreamReadOptions.empty().count(1),
StreamOffset.create(queueName, ReadOffset.from("0"))
);
// 2、判断消息是否获取成功
if(list==null||list.isEmpty()){
// 2.1、获取失败,说明 pending-list 中没有异常消息,结束循环
break;
}
// 2.2、获取成功,可以创建订单
// 解析信息
MapRecord<String, Object, Object> record = list.get(0);
Map<Object, Object> values = record.getValue();
VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
handleVoucherOrder(voucherOrder);
// 3、ACK 确认
stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
} catch (Exception e) {
log.error("处理 pending-list 异常",e);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}
}
}
// // 创建阻塞队列
// private BlockingQueue<VoucherOrder> orderTasks=new ArrayBlockingQueue<>(1024*1024);
// // 线程任务
// private class VoucherOrderHandler implements Runnable{
// @Override
// public void run() {
// while (true) {
// try {
// // 1、获取队列中的订单信息
// VoucherOrder voucherOrder = orderTasks.take();
// // 2、创建订单
// handleVoucherOrder(voucherOrder);
// } catch (InterruptedException e) {
// log.error("处理订单异常",e);
// }
//
// }
// }
// }
// 处理子线程
private void handleVoucherOrder(VoucherOrder voucherOrder) {
Long userId = voucherOrder.getUserId();
//创建锁对象
RLock lock = redissonClient.getLock("lock:order:" + userId);
//获取锁
boolean isLock = lock.tryLock();
//判断是否获取锁成功
if (!isLock) {
//获取失败
log.error("不允许重复下单");
return;
}
try {
proxy.createVoucherOrder(voucherOrder);
} finally {
//释放
lock.unlock();
}
}
private IVoucherOrderService proxy;
// 改用stream消息队列,已在 lua 脚本中改造
@Override
public Result seckillVoucher(Long voucherId) {
Long userId = UserHolder.getUser().getId();
long orderId = redisWorker.nextId("order");
// 1、执行 lua 脚本
Long result = stringRedisTemplate.execute(
SECKILL_SCRIPT,
Collections.emptyList(), // 因为 lua 脚本 中 KEY 为 0
voucherId.toString(),
userId.toString(),
String.valueOf(orderId)
);
// 2、判断结果
int r = result.intValue();
if(r!=0){
// 2.1 不为0,没有购买资格
return Result.fail(r==1 ? "库存不足" : "不能重复下单");
}
// 获取代理对象(事务)
proxy = (IVoucherOrderService) AopContext.currentProxy();
// 3、返回订单id
return Result.ok(orderId);
}
// @Override
// public Result seckillVoucher(Long voucherId) {
// Long userId = UserHolder.getUser().getId();
// // 1、执行 lua 脚本
// Long result = stringRedisTemplate.execute(
// SECKILL_SCRIPT,
// Collections.emptyList(), // 因为 lua 脚本 中 KEY 为 0
// voucherId.toString(),
// userId.toString()
// );
// // 2、判断结果
// int r = result.intValue();
// if(r!=0){
// // 2.1 不为0,没有购买资格
// return Result.fail(r==1 ? "库存不足" : "不能重复下单");
// }
// // 获取代理对象(事务)
// proxy = (IVoucherOrderService) AopContext.currentProxy();
// // 2.2 为0,有购买资格,将下单信息保存到阻塞队列
// VoucherOrder voucherOrder = new VoucherOrder();
// long orderId = redisWorker.nextId("order");
// // 保存到阻塞队列中
// voucherOrder.setId(orderId);
// voucherOrder.setUserId(userId);
// voucherOrder.setVoucherId(voucherId);//代金券id
// orderTasks.add(voucherOrder);
// // 3、返回订单id
// return Result.ok(0);
// }
/**
* 实现秒杀券下单
*/
// @Override
// public Result seckillVoucher(Long voucherId) {
// //查询优惠券
// SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//
// //判断秒杀是否开始
// if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
// //还没开始
// return Result.fail("秒杀活动尚未开始");
// }
//
// //判断秒杀是否已经结束
// if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
// //已经结束
// return Result.fail("秒杀活动已经结束");
// }
//
// //判断库存是否充足
// if (voucher.getStock() < 1) {
// return Result.fail("库存不足");
// }
// UserDTO user = UserHolder.getUser();
// if (user == null) {
// // 用户未登录,返回错误结果
// return Result.fail("用户未登录,请先登录");
// }
// Long userId = user.getId();
// //获取锁对象
// //SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
// RLock lock = redissonClient.getLock("lock:order:" + userId);
// //获取锁
// boolean isLock = lock.tryLock();
// //判断是否获取锁成功
// if (!isLock) {
// //获取失败
// //一个重试一个返回错误
// return Result.fail("一人下一单");
// }
//
// //获取成功
// try {
// IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
// return proxy.createVoucherOrder(voucherId);
// } finally {
// //释放
// lock.unlock();
// }
// }
@Transactional
public void createVoucherOrder(VoucherOrder voucherOrder) {
//6.一人一单
// UserHolder 基于 ThreadLocal 实现,子线程无法继承主线程的 ThreadLocal 数据,导致 userId = null
Long userId = voucherOrder.getUserId(); // 注意 userId 不能从 UserHolder 中获取
//6.1查询订单
Long count =query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
//6.2判断是否存在
if(count>0){
//用户已经购买过了
log.error("用户已经购买过一次!");
return;
}
//3.2库存充足扣减库存
boolean success = seckillVoucherService.update()
.setSql("stock = stock - 1") //相当于set条件 set stock = stock - 1
.eq("voucher_id", voucherOrder.getVoucherId()) //相当于where条件 where id = ? and stock = ?
.gt("stock",0).update();
if(!success){
log.error("库存不足!");
return;
}
save(voucherOrder);
}
} | 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/impl/VoucherOrderServiceImpl.java | Java | unknown | 11,957 |
package com.hmdp.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Voucher;
import com.hmdp.mapper.VoucherMapper;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import static com.hmdp.utils.RedisConstants.SECKILL_STOCK_KEY;
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements IVoucherService {
@Resource
private ISeckillVoucherService seckillVoucherService;
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public Result queryVoucherOfShop(Long shopId) {
// 查询优惠券信息
List<Voucher> vouchers = getBaseMapper().queryVoucherOfShop(shopId);
// 返回结果
return Result.ok(vouchers);
}
@Override
@Transactional
public void addSeckillVoucher(Voucher voucher) {
// 保存优惠券
save(voucher);
// 保存秒杀信息到数据库
SeckillVoucher seckillVoucher = new SeckillVoucher();
seckillVoucher.setVoucherId(voucher.getId());
seckillVoucher.setStock(voucher.getStock());
seckillVoucher.setBeginTime(voucher.getBeginTime());
seckillVoucher.setEndTime(voucher.getEndTime());
seckillVoucherService.save(seckillVoucher);
// 保存秒杀信息到 redis 中
stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY+voucher.getId(),voucher.getStock().toString());
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/service/impl/VoucherServiceImpl.java | Java | unknown | 1,804 |
package com.hmdp.util;
import com.hmdp.utils.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// 登录校验拦截器
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 获取 ThreadLocal 中的用户,不存在则拦截
if(UserHolder.getUser()==null){
response.setStatus(401);
return false;
}
return true;
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/util/LoginInterceptor.java | Java | unknown | 641 |
package com.hmdp.util;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_TTL;
// 登录校验拦截器
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {
private final StringRedisTemplate stringRedisTemplate;
public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("authorization");
log.debug("请求路径:{},获取到的 token:{}", request.getRequestURI(), token);
if (StrUtil.isEmpty(token)) {
log.debug("token 为空,不加载用户信息");
return true;
}
Map<Object, Object> userMap =
stringRedisTemplate.opsForHash()
.entries(RedisConstants.LOGIN_USER_KEY + token);
log.debug("读取到的用户数据:{}", userMap);
if (userMap.isEmpty()) {
log.debug("Redis 中无用户信息,不加载");
return true;
}
// 转换为 UserDTO
//hash转UserDTO存入ThreadLocal
UserHolder.saveUser(BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false));
// 刷新 token 有效期
stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
UserHolder.removeUser();
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/util/RefreshTokenInterceptor.java | Java | unknown | 2,181 |
package com.hmdp.utils;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static com.hmdp.utils.RedisConstants.*;
/**
* 封装一个缓存工具类,满足下列需求:
* ✔方法1:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置TTL过期时间
* ✔方法2:将任意Java对象序列化为json并存储在string类型的key中,并且可以设置逻辑过期时间,用于处理缓存击穿问题
* ✔方法3:根据指定的key查询缓存,并反序列化为指定类型,利用缓存空值的方式解决缓存穿透问题
* ✔方法4:根据指定的key查询缓存,并反序列化为指定类型,需要利用逻辑过期解决缓存击穿问题
*/
@Slf4j
@Component
public class CacheClient {
private final StringRedisTemplate stringRedisTemplate;
public CacheClient(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
public void set(String key, Object value, Long time, TimeUnit unit) {
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
}
// 逻辑过期(本质是在缓存中永久有效)
public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
RedisData redisData = new RedisData();
redisData.setData(value);
redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
}
// 工具用泛型
public <R,ID> R queryWithPassThrough(String keyPrefix,
ID id, Class<R> type,
Function<ID, R> dbFallback,
Long time, TimeUnit unit){
String key=keyPrefix+id;
// 1.从 redis 查商铺缓存
String json = stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isNotBlank(json)){
return JSONUtil.toBean(json, type);
}
// 判断命中的是否是存入的空数据(解决缓存穿透)
if(json!=null){
return null;
}
// 2.不存在,查数据库,并写入 redis
R r = dbFallback.apply(id);
if(r == null){
// 将空值写入 redis,并设置过期时间(解决缓存穿透)
stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
return null;
}
this.set(key,r,time,unit);
return r;
}
// 创建锁和释放锁
private boolean tryLock(String key){
Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
return BooleanUtil.isTrue(flag);
}
private void unLock(String key){
stringRedisTemplate.delete(key);
}
//线程池
private static final ExecutorService CACHE_REBUILD_EXECUTOR= Executors.newFixedThreadPool(10);
public <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id,
Class<R> type,Function<ID, R> dbFallback,
Long time, TimeUnit unit){
String key=keyPrefix+id;
// 1.从 redis 查商铺缓存
String shopJson = stringRedisTemplate.opsForValue().get(key);
if(StrUtil.isBlank(shopJson)){
return null;
}
// 2.存在,反序列化,判断逻辑是否过期
RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
R r = JSONUtil.toBean((JSONObject)redisData.getData(), type);
LocalDateTime expireTime = redisData.getExpireTime();
// 2.1 未过期,直接返回店铺信息
if(expireTime.isAfter(LocalDateTime.now())){
return r;
}
// 2.2 过期,需要重建缓存(利用互斥锁)
String lockKey=LOCK_SHOP_KEY+id;
boolean isLock = tryLock(lockKey);
if(isLock){
// 开启独立线程
CACHE_REBUILD_EXECUTOR.submit(()->{
try {
R r1 = dbFallback.apply(id);
this.setWithLogicalExpire(key,r1,time,unit);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
unLock(lockKey);
}
});
}
return r;
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/utils/CacheClient.java | Java | unknown | 4,892 |
package com.hmdp.utils;
/**
* redis分布式锁
**/
public interface ILock {
/**
* 尝试获取锁
* @param timeoutSec 锁持有的超时时间,过期后自动释放
* @return true代表获取锁成功; false代表获取锁失败
*/
boolean tryLock(long timeoutSec);
/**
* 释放锁
*/
void unlock();
} | 2401_83448718/hm-dianping | src/main/java/com/hmdp/utils/ILock.java | Java | unknown | 356 |
package com.hmdp.utils;
import cn.hutool.core.util.RandomUtil;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;
public class PasswordEncoder {
public static String encode(String password) {
// 生成盐
String salt = RandomUtil.randomString(20);
// 加密
return encode(password,salt);
}
private static String encode(String password, String salt) {
// 加密
return salt + "@" + DigestUtils.md5DigestAsHex((password + salt).getBytes(StandardCharsets.UTF_8));
}
public static Boolean matches(String encodedPassword, String rawPassword) {
if (encodedPassword == null || rawPassword == null) {
return false;
}
if(!encodedPassword.contains("@")){
throw new RuntimeException("密码格式不正确!");
}
String[] arr = encodedPassword.split("@");
// 获取盐
String salt = arr[0];
// 比较
return encodedPassword.equals(encode(rawPassword, salt));
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/utils/PasswordEncoder.java | Java | unknown | 1,062 |
package com.hmdp.utils;
public class RedisConstants {
public static final String LOGIN_CODE_KEY = "login:code:";
public static final Long LOGIN_CODE_TTL = 2L;
public static final String LOGIN_USER_KEY = "login:token:";
public static final Long LOGIN_USER_TTL = 30L;
public static final Long CACHE_NULL_TTL = 2L;
public static final Long CACHE_SHOP_TTL = 30L;
public static final String CACHE_SHOP_KEY = "cache:shop:";
public static final String LOCK_SHOP_KEY = "lock:shop:";
public static final Long LOCK_SHOP_TTL = 10L;
public static final String CACHE_TYPE_KEY = "cache:type";
public static final String SECKILL_STOCK_KEY = "seckill:stock:";
public static final String BLOG_LIKED_KEY = "blog:liked:";
public static final String FEED_KEY = "feed:";
public static final String SHOP_GEO_KEY = "shop:geo:";
public static final String USER_SIGN_KEY = "sign:";
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/utils/RedisConstants.java | Java | unknown | 925 |
package com.hmdp.utils;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class RedisData {
private LocalDateTime expireTime;
private Object data;
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/utils/RedisData.java | Java | unknown | 175 |
package com.hmdp.utils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
/**
* Redis 自增ID,每天一个 key,方便统计订单量
*/
@Component
public class RedisIdWorker {
private static final long BEGIN_TIMESTAMP = 1752451200; // 2025.7.14 0点0分的秒数
private static final int COUNT_BITS = 32; // 序列号的位数
private final StringRedisTemplate stringRedisTemplate;
public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
public long nextId(String keyPrefix) {
// 时间戳+序列号
//1.生成时间戳
LocalDateTime now = LocalDateTime.now();
long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
long timestamp = nowSecond- BEGIN_TIMESTAMP;
//2.生成序列号
String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
return timestamp << COUNT_BITS | count; //先向左移空出位置,再进行或运算
}
public static void main(String[] args) {
LocalDateTime time=LocalDateTime.of(2025,7,14,0,0,0);
long second = time.toEpochSecond(ZoneOffset.UTC);
System.out.println("second = "+second);
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/utils/RedisIdWorker.java | Java | unknown | 1,496 |
package com.hmdp.utils;
public abstract class RegexPatterns {
/**
* 手机号正则
*/
public static final String PHONE_REGEX = "^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\\d{8}$";
/**
* 邮箱正则
*/
public static final String EMAIL_REGEX = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
/**
* 密码正则。4~32位的字母、数字、下划线
*/
public static final String PASSWORD_REGEX = "^\\w{4,32}$";
/**
* 验证码正则, 6位数字或字母
*/
public static final String VERIFY_CODE_REGEX = "^[a-zA-Z\\d]{6}$";
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/utils/RegexPatterns.java | Java | unknown | 621 |
package com.hmdp.utils;
import cn.hutool.core.util.StrUtil;
public class RegexUtils {
/**
* 是否是无效手机格式
* @param phone 要校验的手机号
* @return true:符合,false:不符合
*/
public static boolean isPhoneInvalid(String phone){
return mismatch(phone, RegexPatterns.PHONE_REGEX);
}
/**
* 是否是无效邮箱格式
* @param email 要校验的邮箱
* @return true:符合,false:不符合
*/
public static boolean isEmailInvalid(String email){
return mismatch(email, RegexPatterns.EMAIL_REGEX);
}
/**
* 是否是无效验证码格式
* @param code 要校验的验证码
* @return true:符合,false:不符合
*/
public static boolean isCodeInvalid(String code){
return mismatch(code, RegexPatterns.VERIFY_CODE_REGEX);
}
// 校验是否不符合正则格式
private static boolean mismatch(String str, String regex){
if (StrUtil.isBlank(str)) {
return true;
}
return !str.matches(regex);
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/utils/RegexUtils.java | Java | unknown | 1,095 |
package com.hmdp.utils;
import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
/**
* 简单的redis分布式锁实现
* 实现了自定义的ILock接口,提供获取锁和释放锁的功能
*/
public class SimpleRedisLock implements ILock {
private String name;
private StringRedisTemplate stringRedisTemplate;
public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
this.name = name;
this.stringRedisTemplate = stringRedisTemplate;
}
private static final String KEY_PREFIX = "lock:";
private static final String ID_PREFIX = UUID.randomUUID().toString(true)+'-';
private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
static {
UNLOCK_SCRIPT=new DefaultRedisScript<>();
UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua")); // resources 下路径
UNLOCK_SCRIPT.setResultType(Long.class);
}
@Override
public boolean tryLock(long timeoutSec) {
//获取线程标识
String threadId = ID_PREFIX+Thread.currentThread().getId();
Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId + "", timeoutSec, TimeUnit.SECONDS);
return Boolean.TRUE.equals(success);
}
@Override
public void unlock() {
// 改用 lua 脚本(保证原子性,将 判断锁 和 释放锁 放在一个脚本中,防止两个动作之间被阻塞)
stringRedisTemplate.execute(
UNLOCK_SCRIPT,
Collections.singletonList(KEY_PREFIX+name),
ID_PREFIX+Thread.currentThread().getId());
// //获取线程标识,判断是不是这把锁,不能误删别的线程的锁
// String threadId = ID_PREFIX + Thread.currentThread().getId();
// String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
// // 线程id 是否与 锁中的id 一致
// if(threadId.equals(id)) {
// //释放锁
// stringRedisTemplate.delete(KEY_PREFIX + name);
// }
//
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/utils/SimpleRedisLock.java | Java | unknown | 2,315 |
package com.hmdp.utils;
public class SystemConstants {
public static final String IMAGE_UPLOAD_DIR = "D:\\nginx-1.18.0\\nginx-1.18.0\\html\\hmdp\\imgs";
public static final String USER_NICK_NAME_PREFIX = "user_";
public static final int DEFAULT_PAGE_SIZE = 5;
public static final int MAX_PAGE_SIZE = 10;
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/utils/SystemConstants.java | Java | unknown | 323 |
package com.hmdp.utils;
import com.hmdp.dto.UserDTO;
public class UserHolder {
private static final ThreadLocal<UserDTO> tl = new ThreadLocal<>();
public static void saveUser(UserDTO user){
tl.set(user);
}
public static UserDTO getUser(){
return tl.get();
}
public static void removeUser(){
tl.remove();
}
}
| 2401_83448718/hm-dianping | src/main/java/com/hmdp/utils/UserHolder.java | Java | unknown | 365 |
-- 将对数据库的一些操作 放到 lua脚本 中,即 对redis操作, 提高性能
local voucherId=ARGV[1]
local userId=ARGV[2]
local orderId=ARGV[3]
local stockKey='seckill:stock:' .. voucherId
local orderKey='seckill:order:' .. voucherId
-- 判断库存是否充足
if(tonumber(redis.call('get',stockKey))<=0) then
return 1
end
-- 判断用户是否下单
if(redis.call('sismember',orderKey,userId)==1) then
return 2
end
-- 扣库存
redis.call('incrby',stockKey,-1)
-- 下单(保存 userId 到 orderKey 中)
redis.call('sadd',orderKey,userId)
-- 发送消息到队列当中
redis.call('xadd','stream.orders','*','userId',userId,'voucherId',voucherId,'id',orderId)
return 0 | 2401_83448718/hm-dianping | src/main/resources/seckill.lua | Lua | unknown | 693 |
-- 比较线程标识 与 锁中标识 是否一致
if(redis.call('get',KEYS[1])==ARGV[1]) then
-- 释放锁 del key
return redis.call('del',KEYS[1])
end
return 0 | 2401_83448718/hm-dianping | src/main/resources/unlock.lua | Lua | unknown | 170 |
# 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | 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_1556 | apps/src/app_utils.c | C | unknown | 31,126 |