RSA作为最主流的加解密与验签算法,iOS当然少不了
签名
unsigned char *rsaPKCS1SignData(const unsigned char *src,int src_len,unsigned char*pri_key,int pri_key_len, int *dst_len)
{
unsigned char *pri_pem = formatPem(pri_key, PEM_FORMAT_PRIVATEKEY);
BIO *bio_private = NULL;
RSA *rsa_private = NULL;
bio_private = BIO_new(BIO_s_mem());
BIO_write(bio_private, pri_pem, strlen((const char *)pri_pem));
unsigned char pwd[] = "";
rsa_private = PEM_read_bio_RSAPrivateKey(bio_private, NULL, (pem_password_cb *)pwd,NULL);
EVP_PKEY *key = EVP_PKEY_new();
int err = EVP_PKEY_assign_RSA(key,rsa_private);
int size=0;
if (err) {
size = EVP_PKEY_size(key);
}
EVP_MD_CTX *ctx = EVP_MD_CTX_create();
EVP_MD_CTX_init(ctx);
EVP_SignInit_ex(ctx,EVP_sha1() , NULL);
EVP_SignUpdate(ctx, src,src_len);
unsigned char *md=(unsigned char *)malloc(size);
unsigned int len = 0;
EVP_SignFinal(ctx, md, &len, key);
*dst_len = len;
EVP_PKEY_free(key);
EVP_MD_CTX_cleanup(ctx);
return md;
}
验签
bool rsaVerify(const unsigned char *src,int src_len,unsigned char *sig,unsigned int sigl_len,unsigned char *pub_key,int pub_key_len) { unsigned char *pub_pem = formatPem(pub_key, PEM_FORMAT_PUBKEY); BIO *bio_public = NULL; bio_public = BIO_new(BIO_s_mem()); BIO_write(bio_public, pub_pem, strlen((const char *)pub_pem)); EVP_PKEY *key=NULL; PEM_read_bio_PUBKEY(bio_public, &key, NULL, NULL); int size=0; if (key) { size = EVP_PKEY_size(key); } EVP_MD_CTX *ctx = EVP_MD_CTX_create(); EVP_MD_CTX_init(ctx); EVP_VerifyInit_ex(ctx, EVP_sha1(), NULL); EVP_VerifyUpdate(ctx, src,src_len); int suc = EVP_VerifyFinal(ctx, sig, sigl_len, key); EVP_PKEY_free(key); EVP_MD_CTX_cleanup(ctx); if (suc == 1) { return true; } else return false; }
转载于:https://blog.51cto.com/techforlcl/1323136