RSA加密解密需要用到一对公私钥。在ios端是使用公钥加密,用私钥解密。而在java服务端是可以通用的。这次讲解一下从文件读取的公私钥,用来加密的问题。
至于openssl的安装和用途就不介绍了,网上很多方法。这里介绍的是如何使用openssl和openssl生成公私钥后如何使用到ios端。
网上有很多终端运行语句,这里简单标注下
安装完毕openssl后
//第一步直接输入openssl进入openssl
openssl
//第二步生成私钥pem文件
genrsa -out private_key.pem 1024
//第三步将pem文件转换成csr文件
openssl req -new -key private_key.pem -out rsaCertReq.csr
//第四步生成带时效的crt文件
x509 -req -days 3650 -in rsaCertReq.csr -signkey private_key.pem -out rsaCert.crt
//第五步导出ios端需要使用的公钥der文件
x509 -outform der -in rsaCert.crt -out public_key.der
//第六步生成crt文件
pkcs12 -export -out private_key.p12 -inkey private_key.pem -in rsaCert.crt
//第七步从私钥pem中导出JAVA端需要的公钥pem文件
rsa -in private_key.pem -out rsa_public_key.pem -pubout
//第八步私钥用于JAVA端的pem文件
pkcs8 -topk8 -in private_key.pem -out pkcs8_private_key.pem -nocrypt
以上是生成公私钥的文件,下面讲解ios端需要的操作
1.将private_key.p12和public_key.der导入到工程中。
2.新建一个继承NSObjcect的类RSADeal
3.RSADeal.h中声明方法如下
-(void) loadPublicKeyFromFile: (NSString*) derFilePath;
-(void) loadPublicKeyFromData: (NSData*) derData;
-(void) loadPrivateKeyFromFile: (NSString*) p12FilePath password:(NSString*)p12Password;
-(void) loadPrivateKeyFromData: (NSData*) p12Data password:(NSString*)p12Password;
-(NSString*) rsaEncryptString:(NSString*)string;
-(NSData*) rsaEncryptData:(NSData*)data ;
-(NSString*) rsaDecryptString:(NSString*)string;
-(NSData*) rsaDecryptData:(NSData*)data;
-(BOOL) rsaSHA1VerifyData:(NSData *) plainData
withSignature:(NSData *) signature;
#pragma mark - Class Methods
+(void) setSharedInstance: (RSADeal*)instance;
+(RSADeal*) sharedInstance;
在.m方法中实现方法
static RSADeal* sharedInstance = nil;
+(void) setSharedInstance: (RSADeal*)instance
{
sharedInstance = instance;
}
+(RSADeal*) sharedInstance
{
return sharedInstance;
}
-(void)dealloc
{
if (nil != publicKey) {
CFRelease(publicKey);
}
if (nil != privateKey) {
CFRelease(privateKey);
}
}
#pragma mark-从本地文件中获取公私钥
-(SecKeyRef) getPublicKey {
return publicKey;
}
-(SecKeyRef) getPrivateKey {
return privateKey;
}
-(void) loadPublicKeyFromFile: (NSString*) derFilePath
{
NSData *derData = [[NSData alloc] initWithContentsOfFile:derFilePath];
[self loadPublicKeyFromData: derData];
}
-(void) loadPublicKeyFromData: (NSData*) derData
{
publicKey = [self getPublicKeyRefrenceFromeData: derData];
}
-(void) loadPrivateKeyFromFile: (NSString*) p12FilePath password:(NSString*)p12Password
{
NSData *p12Data = [NSData dataWithContentsOfFile:p12FilePath];
[self loadPrivateKeyFromData: p12Data password:p12Password];
}
-(void) loadPrivateKeyFromData: (NSData*) p12Data password:(NSString*)p12Password
{
privateKey = [self getPrivateKeyRefrenceFromData: p12Data password: p12Password];
}
#pragma mark - 私有调用方法
-(SecKeyRef) getPublicKeyRefrenceFromeData: (NSData*)derData
{
SecCertificateRef myCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)derData);
SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
SecTrustRef myTrust;
OSStatus status = SecTrustCreateWithCertificates(myCertificate,myPolicy,&myTrust);
SecTrustResultType trustResult;
if (status == noErr) {
status = SecTrustEvaluate(myTrust, &trustResult);
}
SecKeyRef securityKey = SecTrustCopyPublicKey(myTrust);
CFRelease(myCertificate);
CFRelease(myPolicy);
CFRelease(myTrust);
return securityKey;
}
-(SecKeyRef) getPrivateKeyRefrenceFromData: (NSData*)p12Data password:(NSString*)password
{
SecKeyRef privateKeyRef = NULL;
NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
[options setObject: password forKey:(__bridge id)kSecImportExportPassphrase];
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) p12Data, (__bridge CFDictionaryRef)options, &items);
if (securityError == noErr && CFArrayGetCount(items) > 0) {
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
if (securityError != noErr) {
privateKeyRef = NULL;
}
}
CFRelease(items);
return privateKeyRef;
}
#pragma mark - 加密
-(NSString*) rsaEncryptString:(NSString*)string {
NSData* data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSData* encryptedData = [self rsaEncryptData: data];
NSString* base64EncryptedString = [encryptedData base64EncodedStringWithOptions:0];
return base64EncryptedString;
}
// 加密的大小受限于SecKeyEncrypt函数,SecKeyEncrypt要求明文和密钥的长度一致,如果要加密更长的内容,需要把内容按密钥长度分成多份,然后多次调用SecKeyEncrypt来实现
-(NSData*) rsaEncryptData:(NSData*)data {
SecKeyRef key = [self getPublicKey];
size_t cipherBufferSize = SecKeyGetBlockSize(key);
uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
size_t blockSize = cipherBufferSize - 11; // 分段加密
size_t blockCount = (size_t)ceil([data length] / (double)blockSize);
NSMutableData *encryptedData = [[NSMutableData alloc] init] ;
for (int i=0; ilong bufferSize = MIN(blockSize,[data length] - i * blockSize);
NSData *buffer = [data subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];
OSStatus status = SecKeyEncrypt(key, kSecPaddingPKCS1, (const uint8_t *)[buffer bytes], [buffer length], cipherBuffer, &cipherBufferSize);
if (status == noErr){
NSData *encryptedBytes = [[NSData alloc] initWithBytes:(const void *)cipherBuffer length:cipherBufferSize];
[encryptedData appendData:encryptedBytes];
}else{
if (cipherBuffer) {
free(cipherBuffer);
}
return nil;
}
}
if (cipherBuffer){
free(cipherBuffer);
}
return encryptedData;
}
#pragma mark - 解密部分
-(NSString*) rsaDecryptString:(NSString*)string {
NSData* data = [[NSData alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSData* decryptData = [self rsaDecryptData: data];
NSString* result = [[NSString alloc] initWithData: decryptData encoding:NSUTF8StringEncoding];
return result;
}
-(NSData*) rsaDecryptData:(NSData*)data {
SecKeyRef key = [self getPrivateKey];
size_t cipherLen = [data length];
void *cipher = malloc(cipherLen);
[data getBytes:cipher length:cipherLen];
size_t plainLen = SecKeyGetBlockSize(key) - 12;
void *plain = malloc(plainLen);
OSStatus status = SecKeyDecrypt(key, kSecPaddingPKCS1, cipher, cipherLen, plain, &plainLen);
if (status != noErr) {
return nil;
}
NSData *decryptedData = [[NSData alloc] initWithBytes:(const void *)plain length:plainLen];
return decryptedData;
}
#pragma marke - verify file SHA1
-(BOOL) rsaSHA1VerifyData:(NSData *) plainData
withSignature:(NSData *) signature {
size_t signedHashBytesSize = SecKeyGetBlockSize([self getPublicKey]);
const void* signedHashBytes = [signature bytes];
size_t hashBytesSize = CC_SHA1_DIGEST_LENGTH;
uint8_t* hashBytes = malloc(hashBytesSize);
if (!CC_SHA1([plainData bytes], (CC_LONG)[plainData length], hashBytes)) {
return NO;
}
OSStatus status = SecKeyRawVerify(publicKey,kSecPaddingPKCS1SHA1,hashBytes,hashBytesSize,signedHashBytes,signedHashBytesSize);
return status == errSecSuccess;
}