今天公司测试,还在等待 bug 降临,闲来无事捯饬一个小问题.
    首先絮叨一下 RSA 的前世今生, RSA 是三个作者名字的简称,具体内容请自行百度,加密机制如下:首先生成两个密钥,一个公钥,一个私钥,前者加密,后者解密,客户端和服务器各执一份.当客户端向服务器发送数据的时候,先用公钥加密,再有私钥加签,到了服务器一端,用公钥验签,用私钥解密,然后再往下走.加密是为了安全,加签是为了防止冒充APP 客户端进行请求,导致服务器的瘫痪.
    👉安装OpenSSL
    使用OpenSSL获取公钥和私钥, OpenSSL 的安装请自行百度.
    👉获取公钥,私钥步骤
    ①生成 pem 文件
    openssl:关键字
    genrsa:格式
    -out:输出到…
    privatekey.pem:文件名任意取
    1024:文件长度

    openssl genrsa -out privatekey.pem 1024

    ②通过第一步生成的 pem 请求 csr 文件,这里会让你填写一些基本信息,最后一下密码可以选填
    req:发出请求
    -new:新的
    privatekey.pem:👆生成的证书
    requestrsacert.csr:证书请求文件

    openssl req -new -key privatekey.pem -out requestCert.csr

    ③ 通过上面两步生成的文件,请求公钥
    x509:证书格式
    -days:有效时长
    3650:10年(随意设置)
    -in:放入哪个文件
    requestrsacert.csr:👆生成的证书
    -signkey:key
    private.pem:👆生成的证书
    publickey.crt:请求到的公钥

    openssl x509 -req -days 3650 -in requestCert.csr -signkey privatekey.pem -out publickey.crt

    ④ 转换格式将base64转换为 bitcode
    -outform:输出格式

    openssl x509 -outform der -in publickey.crt -out publickey.der

    ⑤ 生成p12 私钥文件,会提示输入密码,这个密码是用来在加密是调用私钥的密码
    -export:导出

    openssl pkcs12 -export -out privatekey.p12 -inkey privatekey.pem -in publickey.crt

    👉将公钥和私钥添加到工程中,引入Security.framework,创建对应的类SRSA, 这是我自己命名,你自己也是可以去自己想用的名字.记得设置为 MRC 的模式(-fno-objc-arc)

    OC(十二)-加密算法(一)-RSA - 图1
    👉.h

    1. //
    2. // SRSA.h
    3. // RSA
    4. //
    5. // Created by HMC on 2016/11/1.
    6. // Copyright © 2016年 HMC. All rights reserved.
    7. //
    8. #import <Foundation/Foundation.h>
    9. @interface SRSA : NSObject
    10. /**
    11. *
    12. * 加密
    13. * originalString 原始字符串
    14. */
    15. +(NSString *)encryptString:(NSString *) originalString;
    16. /**
    17. *
    18. * 解密
    19. *
    20. * ciphertextString 加密字符串
    21. */
    22. +(NSString *)decryptString:(NSString *) ciphertextString;
    23. @end

    👉.m

    1. //
    2. // SRSA.m
    3. // RSA
    4. //
    5. // Created by HMC on 2016/11/1.
    6. // Copyright © 2016年 HMC. All rights reserved.
    7. //
    8. #import "SRSA.h"
    9. //私钥的密码
    10. static NSString * pwd = @"123456";
    11. @implementation SRSA
    12. +(NSString *)encryptString:(NSString *)originalString{
    13. if (!originalString)
    14. return nil;
    15. SecKeyRef publicKey = [self getPublicKeyRef];
    16. size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
    17. uint8_t *cipherBuffer = malloc(cipherBufferSize);
    18. uint8_t *nonce = (uint8_t *) [originalString UTF8String];
    19. SecKeyEncrypt(publicKey,
    20. kSecPaddingPKCS1,
    21. nonce,
    22. strlen((char *) nonce),
    23. &cipherBuffer[0],
    24. &cipherBufferSize);
    25. NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
    26. free(cipherBuffer);
    27. return [encryptedData base64EncodedStringWithOptions:0];
    28. }
    29. +(NSString *)decryptString:(NSString *)ciphertextString{
    30. if (!ciphertextString)
    31. return nil;
    32. SecKeyRef privateKey = [self getPrivateKeyRef];
    33. size_t plainBufferSize = SecKeyGetBlockSize(privateKey);
    34. uint8_t *plainBuffer = malloc(plainBufferSize);
    35. NSData *incomingData = [[NSData alloc] initWithBase64EncodedString:ciphertextString options:NSDataBase64DecodingIgnoreUnknownCharacters];
    36. uint8_t *cipherBuffer = (uint8_t *) [incomingData bytes];
    37. size_t cipherBufferSize = SecKeyGetBlockSize(privateKey);
    38. SecKeyDecrypt(privateKey,
    39. kSecPaddingPKCS1,
    40. cipherBuffer,
    41. cipherBufferSize,
    42. plainBuffer,
    43. &plainBufferSize);
    44. NSData *decryptedData = [NSData dataWithBytes:plainBuffer length:plainBufferSize];
    45. NSString *originalString = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
    46. [incomingData release];
    47. free(plainBuffer);
    48. return originalString;
    49. ;
    50. }
    51. //获取公钥
    52. +(SecKeyRef)getPublicKeyRef{
    53. NSString * path = [[NSBundle mainBundle] pathForResource:@"publickey.der" ofType:nil];
    54. NSData *certData = [NSData dataWithContentsOfFile:path];
    55. if (!certData) {
    56. return nil;
    57. }
    58. SecCertificateRef cert = SecCertificateCreateWithData(NULL, (CFDataRef)certData);
    59. SecKeyRef publicKey = NULL;
    60. SecTrustRef trust = NULL;
    61. SecPolicyRef policy = NULL;
    62. if (cert != NULL) {
    63. policy = SecPolicyCreateBasicX509();
    64. if (policy) {
    65. if (SecTrustCreateWithCertificates((CFTypeRef)cert, policy, &trust) == noErr) {
    66. SecTrustResultType result;
    67. if (SecTrustEvaluate(trust, &result) == noErr) {
    68. publicKey = SecTrustCopyPublicKey(trust);
    69. }
    70. }
    71. }
    72. }
    73. if (policy) CFRelease(policy);
    74. if (trust) CFRelease(trust);
    75. if (cert) CFRelease(cert);
    76. return publicKey;
    77. }
    78. //获取私钥
    79. +(SecKeyRef)getPrivateKeyRef{
    80. NSString * path = [[NSBundle mainBundle] pathForResource:@"privatekey.p12" ofType:nil];
    81. NSData *p12Data = [NSData dataWithContentsOfFile:path];
    82. NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
    83. SecKeyRef privateKeyRef = NULL;
    84. //这里的密码改成实际私钥的密码
    85. [options setObject:pwd forKey:(__bridge id)kSecImportExportPassphrase];
    86. CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
    87. OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) p12Data,
    88. (__bridge CFDictionaryRef)options, &items);
    89. if (securityError == noErr && CFArrayGetCount(items) > 0) {
    90. CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
    91. SecIdentityRef identityApp =
    92. (SecIdentityRef)CFDictionaryGetValue(identityDict,
    93. kSecImportItemIdentity);
    94. securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
    95. if (securityError != noErr) {
    96. privateKeyRef = NULL;
    97. }
    98. }
    99. CFRelease(items);
    100. [options release];
    101. return privateKeyRef;
    102. }
    103. @end

    👉调用

    1. //
    2. // ViewController.m
    3. // RSA
    4. //
    5. // Created by HMC on 2016/11/1.
    6. // Copyright © 2016年 HMC. All rights reserved.
    7. //
    8. #import "ViewController.h"
    9. #import "SRSA.h"
    10. @interface ViewController ()
    11. @end
    12. @implementation ViewController
    13. - (void)viewDidLoad {
    14. [super viewDidLoad];
    15. NSString * str = [SRSA encryptString:@"I am a Chinese"];
    16. NSLog(@"加密后:%@",str);
    17. NSLog(@"%@ 解密后:%@",str,[SRSA decryptString:str]);
    18. }
    19. @end

    OC(十二)-加密算法(一)-RSA - 图2

    PS: 客户端的 RSA 是配合后台进行加密解密的,所以也要后台(本文是 Java 的后台)有同样的公钥和私钥,只是格式不同.命令如下:
    公钥:

    openssl rsa -in privatekey.pem -out publickeyForJava.pem -pubout

    私钥

    openssl pkcs8 -topk8 -in privatekey.pem -out privatekeyForJava.pem -nocrypt