博客> 写下我AES加密的问题,希望能帮助大家!
写下我AES加密的问题,希望能帮助大家!
2017-10-19 16:31 评论:0 阅读:243 耀一片男
ios 加密 AES 问题
小白我是第一次发博客,不知道格式也不知道内容规不规范。只是将我个人遇到的问题曝露出来,为以后小伙伴们遇到相同问题能第一时间找到方案。好了闲话不多说,下面主题:

up主新进一公司做小额贷款,所以对数据需要加密处理,那么久用到了AES+base64的加密,于是乎就被后台甩了一个android的加密方法给我。如下:

public static String Encrypt(String sSrc) throws Exception {

    String sKey = Constants.KEY;
    byte[] raw = sKey.getBytes("utf-8");
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
    return parseByte2HexStr(encrypted);//此处使用BASE64做转码功能。
}

那么我就只有网上找demo进行相比较测试咯、接着就出现了下面一个网上demo适合于我,主要加密方法如下: //data加密

  • (NSData ) AES256_Encrypt:(NSString )key{ char keyPtr[kCCKeySizeAES256+1]; bzero(keyPtr, sizeof(keyPtr)); [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [self length]; size_t bufferSize = dataLength + kCCBlockSizeAES128; void *buffer = malloc(bufferSize); size_t numBytesEncrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,kCCOptionPKCS7Padding | kCCOptionECBMode,keyPtr, kCCBlockSizeAES128,NULL,[self bytes], dataLength,buffer, bufferSize,&numBytesEncrypted); if (cryptStatus == kCCSuccess) { return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; } free(buffer); return nil; }

//NSString加密

  • (NSString ) AES256_Encrypt:(NSString )key{ const char cstr = [self cStringUsingEncoding:NSUTF8StringEncoding]; NSData data = [NSData dataWithBytes:cstr length:self.length];

    //对数据进行加密 NSData *result = [data AES256_Encrypt:key];

    //转换为2进制字符串 if (result && result.length > 0) {

    Byte *datas = (Byte *)[result bytes];
    NSMutableString *output = [NSMutableString stringWithCapacity:result.length * 2];
    for(int i = 0; i < result key=@ xss=removed xss=removed json=[[NSString xss=removed xss=removed xss=removed xss=removed> 0) {
    Byte *datas = (Byte *)[result bytes];
    NSMutableString *output = [NSMutableString stringWithCapacity:result.length * 2];
    for(int i = 0; i &lt; result.length; i++){
        [output appendFormat:@"X", datas[i]];
    }
    return output;

    } return nil; }

即将: const char cstr = [self cStringUsingEncoding:NSUTF8StringEncoding]; NSData data = [NSData dataWithBytes:cstr length:self.length];

改为: NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];

完毕!!!

以上是小白我第一次博客内容,经供参考,希望能为游客提供帮助!谢谢大家~~~~

   最后留下网上demo地址(具体如何修改还得看个人项目需要!):[ Enter your link description here: ](https://github.com/AllLuckly/LBAES/tree/master)
收藏
1
sina weixin mail 回到顶部