第一步,编译iOS平台的openssl库,如何编译可自行搜索,网上一搜一大堆,git传送门:https://github.com/x2on/OpenSSL-for-iPhone,编译完之后导入项目,配置Header Search Paths就行
第二步,导出开发者证书为Sign.p12,终端运行以下命令
openssl pkcs12 -in Sign.p12 -out Sign.pem -nodes
此时得到Sign.pem
导出Apple WorldWide证书为Apple.pem,这个直接导成pem就行
然后把Sign.pem和Apple.pem放入项目
第三步,上代码搞定
//
// YMOpenSSL.m
// Yuumi
//
// Created by 1 on 2021/2/4.
//
#import "YMOpenSSL.h"
#import <openssl/pkcs7.h>
#import <openssl/pem.h>
@implementation YMOpenSSL
+ (BOOL)signMobileConfigWithInPath:(NSString *)inPath outPath:(NSString *)outPath
{
//X509证书对象,sign为签名者证书sign.pem,root为签名附加证书(一般是sign的颁发机构提供)
X509 *sign = NULL, *root = NULL;
//证书私钥
EVP_PKEY *skey = NULL;
//文件操作
BIO *signBio = NULL, *rootBio = NULL;
//读取包内证书路径
NSString * signPem = [[NSBundle mainBundle] pathForResource:@"Sign" ofType:@"pem"];
NSString * applePem = [[NSBundle mainBundle] pathForResource:@"Apple" ofType:@"pem"];
if (!signPem || !applePem) {
return NO;
}
//获取sign.pem文件
signBio = BIO_new_file(signPem.UTF8String, "r");
if (!signBio) {
return NO;
}
//将sign.pem文件以X509格式读取
sign = PEM_read_bio_X509(signBio, NULL, 0, NULL);
//读取sign的私钥
skey = PEM_read_bio_PrivateKey(signBio, NULL, 0, NULL);
if (!skey) {
return NO;
}
//获取root.pem文件
rootBio = BIO_new_file(applePem.UTF8String, "r");
if (!rootBio) {
return NO;
}
//将root.pem文件以X509格式读取
root = PEM_read_bio_X509(rootBio, NULL, 0, NULL);
//创建PKCS7签名对象
PKCS7* p7 = PKCS7_new();
//设置类型为NID_pkcs7_signed
PKCS7_set_type(p7, NID_pkcs7_signed);
//内容设置为NID_pkcs7_data
PKCS7_content_new(p7, NID_pkcs7_data);
//设置为no-detached签名方式
PKCS7_set_detached(p7, 0);
//向签名信息中增加证书,秘钥,对应的加密算法
PKCS7_add_signature(p7, sign, skey, EVP_sha1());
//增加证书链,sign和root证书
PKCS7_add_certificate(p7, sign);
PKCS7_add_certificate(p7, root);
//创建PKCS7签名操作
BIO *p7bio = PKCS7_dataInit(p7, NULL);
//读取需要签名的文件
NSData * data = [NSData dataWithContentsOfFile:inPath];
if (!data) {
return NO;
}
const char *inData = [data bytes];
//像签名操作中写入文件的内容
BIO_write(p7bio, inData, (int)strlen(inData));
//处理签名
PKCS7_dataFinal(p7, p7bio);
//转换为der编码输出
int len;
unsigned char *der, *p;
len = i2d_PKCS7(p7, NULL);
der = (unsigned char *)malloc(len);
p = der;
len = i2d_PKCS7(p7, &p);
//写入文件
FILE *fp;
fp = fopen(outPath.UTF8String, "wb");
fwrite(der, 1, len, fp);
//释放操作
fclose(fp);
free(der);
X509_free(sign);
X509_free(root);
EVP_PKEY_free(skey);
BIO_free(signBio);
BIO_free(rootBio);
PKCS7_free(p7);
BIO_free(p7bio);
return YES;
}
@end
网友评论