iOS 大部分的加密与解密

好久没有写简书了。一直在懒惰着。

最近新项目涉及了加密。而且是繁琐 嵌套的加密。仔细了研究了好久。在这里总结一下。

现在市面上大多数的加密,简单来说 base64,AES128,AES256,MD5,Salt,HMAC,Sha256。

首先说一下Base64.
iOS端有自己原生的base64加密。

  • NSdata
[NSData alloc]initWithBase64EncodedData:<#(nonnull NSData *)#> options:<#(NSDataBase64DecodingOptions)#>
  • NSString
[NSData alloc]initWithBase64EncodedData:<#(nonnull NSData *)#> options:<#(NSDataBase64DecodingOptions)#>

AES分为AES128 和 AES256,AES128他是需要iv 和key 去生成一个新的data。AES256 只需要一个key

  • AES128
- (NSData *)AES128Operation:(CCOperation)operation key:(NSData *)key iv:(NSData *)iv
{
    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                          kCCAlgorithmAES128,
                                          kCCModeCTR,
                                          key.bytes,
                                          kCCBlockSizeAES128,
                                          iv.bytes,
                                          [self bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
    }
    free(buffer);
    return nil;
}
- CCOperation 是一个枚举  
```objc 
enum {
    kCCEncrypt = 0,
    kCCDecrypt,
};
typedef uint32_t CCOperation;
  • AES256
- (NSData *) AES256EncryptedDataUsingKey: (id) key error: (NSError **) error
{
    CCCryptorStatus status = kCCSuccess;
    NSData * result = [self dataEncryptedUsingAlgorithm: kCCAlgorithmAES128
                                                  key: key
                                              options: kCCOptionECBMode|kCCOptionPKCS7Padding
                                                error: &status];
    if ( result != nil )
        return ( result );
    if ( error != NULL )
        *error = [NSError errorWithCCCryptorStatus: status];    
    return ( nil );
}

在这里多说几句。其实这里AES128加密需要设计很多类型。这都是AES128的类型。其实就是代表他的偏移量。我们公司用的是偏移量为0。0x0000就好。

    kCCModeECB      = 1,
    kCCModeCBC      = 2,
    kCCModeCFB      = 3,
    kCCModeCTR      = 4,
    kCCModeOFB      = 7,
    kCCModeRC4      = 9,
    kCCModeCFB8     = 10,

MD5 加密操作是不可逆的。只有加密。

- (NSData *) MD5Sum
{
    unsigned char hash[CC_MD5_DIGEST_LENGTH];
    (void) CC_MD5( [self bytes], (CC_LONG)[self length], hash );
    return ( [NSData dataWithBytes: hash length: CC_MD5_DIGEST_LENGTH] );
}

Salt 加盐操作。

这个基本都是结合其他加密一起用。首先和云端沟通好一段盐, 用你的参数+盐 然后经过Base64或者AES 加密后 传给云端。云端解密后去掉盐。

SHA256 其实也是另类的MD5 只不过参数不一样。同样是生成哈希值。

+ (NSData*)sha256HashFor:(NSData*)input{   
    unsigned char result[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(input.bytes, (CC_LONG)strlen(input.bytes), result);
   return [NSData dataWithBytes:result length:CC_SHA256_DIGEST_LENGTH];
}

!!下面重点来了。我们公司这个独特的加密机制。

  • CRC16
  • HKDF
  • ECDSA
1.CRC16

这个每个公司有不同的算法。
看网上也有不同的处理办法。

  • 关键的参数有 0x1021
uint16_t crc_16_CCITT_False(char * pucFrame,int offset ,short usLen)
{
    int start = offset; //选择数据要计算CRC的起始位
    int end = offset + usLen; //选择数据要CRC计算的范围段
 
    unsigned short  crc = 0xffff; // initial value
    unsigned short  polynomial = 0x1021; // poly value
    for (int index = start; index < end; index++)
    {
        Byte b = pucFrame[index];
        for (int i = 0; i < 8; i++) {
            BOOL bit = ((b >> (7 - i) & 1) == 1);
            BOOL c15 = ((crc >> 15 & 1) == 1);
            crc <<= 1;
            if (c15 ^ bit)
                crc ^= polynomial;
        }
    }
    crc &= 0xffff;
    return crc;
}

参考:https://blog.csdn.net/aming090/article/details/82878485

2. HKDF

gihub上有个大神的demo。可以直接用。
HKDF https://github.com/signalapp/HKDFKit

3. ECDSA 双曲线螺旋算法。

这个加密可苦了我了。我们这边给的是安卓代码。让你看安卓去还原。
首先设备端给的64的byte。叫raw。 谁知道raw 是什么东西。
后来看了好多文章。解释可能是x,y.
苹果这边ecc 生成 公钥私钥。打印公钥 log 能看见x,y
但是打印出来 也没法key value 去获取。

<SecKeyRef curve type: kSecECCurveSecp256r1, algorithm id: 3, key type: ECPublicKey, version: 4, block size: 256 bits, y: CF2311CE011C624741B67E3910412A18A48DB6AA0BB2D0E4D0EBC61C07D0A7D2, x: 979E2AB57FD9D29D2DEF531C34F3CE11A13DD0AFC2024AC6C2696D9E86D1BB16, addr: 0x153e143e0>

然后去集成openssl 发现生成的pem publickkey 和privitekey 无法还原byte 和iOS原生的SeckeyRef

openSSL https://stackoverflow.com/questions/15728636/how-to-pin-the-public-key-of-a-certificate-on-ios
pem转化成SecKeyRefhttps://www.jianshu.com/p/783f2605f3e9

安卓 iOS 客户端 rsa转化http://blog.sina.com.cn/s/blog_48d4cf2d0102vctu.html

后来终于找到了一片解释的文章。

Creating and Dismantling EC Key in SecKey Swift iOS

他详细了解释了 Seckeyref raw data 三者的关系 以及转化。

1.Creating and Dismantling EC Key in SecKey Swift iOS

  var xStr = /* ...... */ //Base64 Formatted data
  var yStr = /* ...... */
  var dStr = /* ...... */ //For Public key we won't be using d value
  //Padding required 
  xStr = xStr.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
  if xStr.count % 4 == 2 {
   xStr.append("==")
  }
  if xStr.count % 4 == 3 {
   xStr.append("=")
  }
  let xBytes = Data(base64Encoded: xStr)
  /*Same with y and d*/
  let yBytes = Data(base64Encoded: yStr)
  let dBytes = Data(base64Encoded: dStr)
        
  //Now this bytes we have to append such that [0x04 , /* xBytes */, /* yBytes */, /* dBytes */]
  //Initial byte for uncompressed y as Key.
  let keyData = NSMutableData.init(bytes: [0x04], length: [0x04].count)
        keyData.append(xBytes)
        keyData.append(yBytes)
        keyData.append(dBytes)
        let attributes: [String: Any] = [
            kSecAttrKeyType as String: kSecAttrKeyTypeEC,
            kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
            kSecAttrKeySizeInBits as String: 256,
            kSecAttrIsPermanent as String: false
        ]
        var error: Unmanaged<CFError>?
        let keyReference = SecKeyCreateWithData(keyData as CFData, attributes as CFDictionary, &error) as! SecKey
  • for public key we wont be using d component else everything will be same.
  • 公钥这里不需要d 因为没有Z轴

2.Getting x, y and d from SecKey EC Key

var error: Unmanaged<CFError>?
let keyData = SecKeyCopyExternalRepresentation(privateKey, &error)
let data = keyData! as Data
var privateKeyBytes = data.bytes
privateKeyBytes.removeFirst()
//For public key bytes will be divide into 2
let pointSize = privateKeyBytes.count / 3
let xBytes = privateKeyBytes[0..<pointSize]
let yBytes = privateKeyBytes[pointSize..<pointSize*2]
//dBytes wont be there in public key
let dBytes = privateKeyBytes[pointSize*2..<pointSize*3]
//this x, y and d bytes can be expressed in HexaDecimal format or base64 format

3.x, y and d (JWK) to SecKey

  • 这里是我要的。
dStr = dStr.replacingOccurrences(of: “-”, with: “+”).replacingOccurrences(of: “_”, with: “/”)
if dStr.count % 4 == 2 {
    dStr.append(“==”)
}
if dStr.count % 4 == 3 {
    dStr.append(“=”)
}
xStr = xStr.replacingOccurrences(of: “-”, with: “+”).replacingOccurrences(of: “_”, with: “/”)
if xStr.count % 4 == 2 {
    xStr.append(“==”)
}
if xStr.count % 4 == 3 {
    xStr.append(“=”)
}
yStr = yStr.replacingOccurrences(of: “-”, with: “+”).replacingOccurrences(of: “_”, with: “/”)
if yStr.count % 4 == 2 {
    yStr.append(“==”)
}
if yStr.count % 4 == 3 {
    yStr.append(“=”)
}
let d : [UInt8] = (Data.init(base64Encoded: dStr)?.bytes)!
let x : [UInt8] = (Data.init(base64Encoded: xStr)?.bytes)!
let y : [UInt8] = (Data.init(base64Encoded: yStr)?.bytes)!
let i : [UInt8] = [0x04]
let privBytes = i + x + y + d
let pubBytes = i + x + y
let privateKey = SecKeyCreateWithData(Data.init(bytes: privBytes) as CFData, attributesECPri as CFDictionary, &error)
//Optional<SecKeyRef> — some : <SecKeyRef curve type: kSecECCurveSecp256r1, algorithm id: 3, key type: ECPrivateKey, version: 4, block size: 256 bits, addr: 0x7f944bc1fc20>
let publicKey = SecKeyCreateWithData(Data.init(bytes: pubBytes) as CFData, attributesECPub as CFDictionary, &error)
//Optional<SecKeyRef> — some : <SecKeyRef curve type: kSecECCurveSecp256r1, algorithm id: 3, key type: ECPublicKey, version: 4, block size: 256 bits, y: 2E4D27C6DBA042BD31C5326049F24198A667213EBF61FA31918E9DD535D6BF7B, x: 405964ECD9FB3142E17FFC9A765300F50005761207275E27A98F554BB78E904B, addr: 0x7f944bc1dff0>

4.SecKey to x, y and d

let ixyd = SecKeyCopyExternalRepresentation(privateKey!, &error)
//Optional<CFDataRef> — some : <04405964 ecd9fb31 42e17ffc 9a765300 f5000576 1207275e 27a98f55 4bb78e90 4b2e4d27 c6dba042 bd31c532 6049f241 98a66721 3ebf61fa 31918e9d d535d6bf 7b538932 67a86d63 d134001e 5690436f e6afb05f 04820ba5 8a219734 7c97b527 9a>
let ixy = SecKeyCopyExternalRepresentation(publicKey!, &error)
//Optional<CFDataRef> — some : <04405964 ecd9fb31 42e17ffc 9a765300 f5000576 1207275e 27a98f55 4bb78e90 4b2e4d27 c6dba042 bd31c532 6049f241 98a66721 3ebf61fa 31918e9d d535d6bf 7b>
if publicKeySec == publicKey && privateKey == privateKeySec && error == nil {
    print(“the end”)
}

总结

从这篇文章看来。对应64byte 的raw = x(32byte)+y(byte).
而iOS端的 公钥 = 04 + raw
私钥 = 04 + raw + z (32)byte

附上测试的网站

在线AES加密解密
hex pem ask2码
[Encryption / desrypton tool]https://8gwifi.org/bccrypt.jsp

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容