1.需要后台提供.pem格式的Openssl公钥文件,也可以自己制作。具体请参考:http://www.qmailer.net/archives/216.html(OpenSSL密钥相关命令)
char *my_encrypt(const char *str,const char *path_key){
char *p_en;
RSA *p_rsa;
FILE *file;
int flen,rsa_len;
if((file=fopen(path_key,"r"))==NULL){
perror("open key file error");
return NULL;
}
if((p_rsa=PEM_read_RSA_PUBKEY(file,NULL,NULL,NULL))==NULL){
//if((p_rsa=PEM_read_RSAPublicKey(file,NULL,NULL,NULL))==NULL){
ERR_print_errors_fp(stdout);
return NULL;
}
NSString * plainString = @"plainString";
int len = (int) [plainString length];//待加密字母串长度
unsigned char *plainBuffer = (unsigned char *) [plainString UTF8String];
int clen = RSA_size(p_rsa);
unsigned char *cipherBuffer = calloc(clen, sizeof(unsigned char));
RSA_public_encrypt(len, plainBuffer, cipherBuffer, p_rsa, RSA_PKCS1_PADDING);
return cipherBuffer;
}
2.也可以尝试:
- (NSString *)encryptWithString:(NSString *)content
{
NSData *publicKey = [NSData dataFromBase64String:RSA_KEY_BASE64];
NSData *usernamm = [content dataUsingEncoding: NSUTF8StringEncoding];
NSData *newKey= [SecKeyWrapper encrypt:usernamm publicKey:publicKey];
NSString *result = [newKey base64EncodedString];
return result;
}
参考链接:http://www.cnblogs.com/aLittleBitCool/archive/2011/09/22/2185418.html
http://www.qmailer.net/archives/216.html
版权声明:本文为博主原创文章,未经博主允许不得转载。