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 去获取。


然后去集成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?
        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?
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..

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 — some : 
let publicKey = SecKeyCreateWithData(Data.init(bytes: pubBytes) as CFData, attributesECPub as CFDictionary, &error)
//Optional — some : 

4.SecKey to x, y and d

let ixyd = SecKeyCopyExternalRepresentation(privateKey!, &error)
//Optional — 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 — 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

你可能感兴趣的:(iOS 大部分的加密与解密)