如何在 Objective c 中使用 AES 加密发送 CommonCrypto POST 请求?

How to send CommonCrypto POST request using AES Crypto in Objective c?

我只是尝试从 iOS 应用向 objective c 中的 php 平台 Web 服务发送安全请求。我尝试了 2 天,但我没有找到逻辑或任何如何实现此目的的方法:

以下是 Swift 使用 CryptoSwift Framework

的代码
func HTTPPostJSON(url: String, jsonData: Dictionary<String, AnyObject>, type: String = "POST", encrypt: Bool = false, callback: (String, String?) -> Void) {
        if Debug().state {
            print("** Start HTTP")
        }
        crypto_enabled = encrypt
        let req = NSMutableURLRequest(URL: NSURL(string: url)!)
        req.HTTPMethod = type
        req.addValue(self.dataType, forHTTPHeaderField: self.headerType)
        let json: JSON = JSON(jsonData)
        //        var data: NSData = NSJSONSerialization.dataWithJSONObject(json.object, options: nil, error: nil)!
        var data: NSData = NSData()
        do {
            data = try NSJSONSerialization.dataWithJSONObject(json.object, options: NSJSONWritingOptions.init(rawValue: 0))
        } catch {
            print("JSON to NSData error: \(error)")
        }
        if Debug().state {
            print("JSON Object: \(json)")
        }
        if crypto_enabled {
            if Debug().state {
                print("Encryption enabled")
            }
            let iv = Cipher.randomIV(AES.blockSize)
            //            println("UInt8 IV: \(iv)")
            let iv_size = iv.count //count(iv)
            print("IV Size: \(iv_size)")
            var key = [UInt8] (self.secret.utf8)
            //            println("UInt8 Key: \(key)")
            let secret_len = self.secret.characters.count
            print("Key length: \(secret_len)")

            if self.secret.characters.count != 32 {
                if Debug().state {
                    print("Hashing Secret")
                }
                let data: NSData = self.secret.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
                //                key = (CryptoSwift.Hash.md5(data).calculate()!).arrayOfBytes()
                key = (CryptoSwift.Hash.sha256(data).calculate()!).arrayOfBytes()
                if Debug().state {
                    print("New UInt8 Key: \(key)")
                    let new_key_len = key.count
                    print("New Key Length: \(new_key_len)")
                }
            }

            let aes = AES(key: key, iv: iv, blockMode: .CBC)!
            var encrypted: [UInt8] = []
            do {
                encrypted = try aes.encrypt(data.arrayOfBytes())
            } catch {
                print("Encrypt data failed: \(error)")
            }
            // IV
            let ivData: NSData = NSData.withBytes(iv)
            //            println("IV in NSData: \(ivData)\n")
            let ivBase64 = ivData.base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
            //            println("IV in Base64: \(ivBase64)\n")
            let ivBase64String = NSString(data: ivBase64, encoding: NSUTF8StringEncoding) as! String
            //            println("IV in Base64 String: \(ivBase64String)\n")
            // cData
            let cData_Data = NSData.withBytes(encrypted)
            // 1st cData Base64 encoding
            let cData_Base64 = cData_Data.base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
            let cData_Base64String = NSString(data: cData_Base64, encoding: NSUTF8StringEncoding) as! String
            // 2nd cData Base64 encoding
            let cData_Base64String_Data = cData_Base64String.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
            let cData_L2_Base64 = cData_Base64String_Data.base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
            let cData_L2_Base64String = NSString(data: cData_L2_Base64, encoding: NSUTF8StringEncoding) as! String

            let cipheredDict: Dictionary<String, AnyObject> = [
                "iv": ivBase64String,
                "cData": cData_L2_Base64String // cData_Base64String
            ]
            var cipheredJSON: JSON = JSON(cipheredDict)
            //            let cipheredData: NSData = NSJSONSerialization.dataWithJSONObject(cipheredJSON.object, options: nil, error: nil)!
            var cipheredData: NSData = NSData()
            do {
                cipheredData = try NSJSONSerialization.dataWithJSONObject(cipheredJSON.object, options: NSJSONWritingOptions.init(rawValue: 0))
            } catch {
                print("Ciphered JSON to NSData error: \(error)")
            }
            //            if Debug().state {
            //                println("Ciphered Data: \(cipheredData)")
            //            }
            data = cipheredData
        }
        //let jsonString = json //self.JSONStringify(json)
        //let data: NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
        req.HTTPBody = data
        self.HTTPSendReq(req, callback: callback)
    }

我尝试使用 MIHCrypto

在 objective c 中实现
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://00.00.00.000/member/slogin"]];


    NSMutableDictionary *parameters = [NSMutableDictionary new];
    [parameters setObject:@"POS" forKey:@"from"];
    [parameters setObject:@"52001" forKey:@"username"];
    [parameters setObject:@"111111" forKey:@"password"];

    // Specify that it will be a POST request
    request.HTTPMethod = @"POST";

    // This is how we set header fields
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
     NSError *jsonSerializationError = nil;

    NSString*secrate = @"keythatuser";



    // Convert your data and set your request's HTTPBody property
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&jsonSerializationError];



    NSError *error;
    NSData *encryptedData = [RNEncryptor encryptData:jsonData
                                        withSettings:kRNCryptorAES256Settings
                                            password:secrate
                                               error:&error];



    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    [conn start];

坦率地说,我不知道如何解析它,你能指导我加密 PHP 服务器请求并在解密后得到加密响应。

如果您只需要向 Web 服务器发送安全请求,只需使用 https。使用 https 加密整个传输,甚至任何查询参数。你不能做得更好。

为了添加 MITM 安全固定证书。

如果您需要更高的安全性,请使用 RNCryptor,它在多个平台上以多种语言提供。它非常安全,经过严格审查,并且处于最新状态 development/maintenance。它提供了所有细节,例如随机 iv、消息身份验证、密钥扩展和版本控制以实现强大的安全性。

我们可以通过在 Objective-C 项目中创建 Swift 的助手 class 来实现。

使用

在您的项目中安装 pods
platform :ios, '8.0'
use_frameworks!

target 'CryptoTest' do
    pod 'CryptoSwift'
end

添加一个带桥接的助手 swift 文件 header

为此,转到设置 > 打包 > 定义模块 = True

现在 import 帮助文件 CryptoSwift

例如:

//
//  CryptoHelper.swift
//  CryptoTest

import UIKit
import CryptoSwift

class CryptoHelper: NSObject {
    func cryptTest(){
        /* Hash enum usage */
        let input:[UInt8] = [49, 50, 51]

        let output = input.md5()
        // alternatively: let output = CryptoSwift.Hash.md5(input).calculate()

        print(output.toHexString())
    }
}

现在在您的任何 Objective-C (.m) 文件中使用该帮助文件

例如:

#import "ViewController.h"
#import "CryptoTest-Swift.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    CryptoHelper *testCrypt = [[CryptoHelper alloc]init];
    [testCrypt cryptTest];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

这里#import "CryptoTest-Swift.h"表示#import "YourProjectModuleName-Swift.h".

希望对你有帮助。