Encrypt AES/CBC/PKCS7Padding

痴心易碎 提交于 2021-02-11 07:44:11

问题


Help me to make encryption AES/CBC/PKCS7Padding? Below is my code to decrypt AES/CBC/PKCS7. It's working but when I encrypt some string and decrypt from my self it's error. Below i adding code to encrypt and decrypt AES/CBC/PKCS7Padding.

- (NSData *)AES256Encrypt:(id)key
{
    NSString *iv = @"FEDCBA9876543210";
    NSData *keyPtr = [key copy];
    size_t dataLength = [self length];
    NSData *ivPtr = [iv dataUsingEncoding:NSUTF8StringEncoding];
    //NSData *encrypted = [self subdataWithRange:NSMakeRange(0, [self length])];

    //size_t bufferSize           = dataLength + kCCBlockSizeAES128;
    //void* buffer                = malloc(bufferSize);
    NSMutableData *ret = [NSMutableData dataWithLength:dataLength + kCCBlockSizeAES128];
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                      [keyPtr bytes], kCCKeySizeAES256,
                                      [ivPtr bytes],
                                      [self bytes], dataLength,
                                      [ret mutableBytes], [ret length],
                                      &numBytesDecrypted);

    NSLog(@"Err : %d",cryptStatus);
    NSLog(@"DataLength : %d, num : %d", (int)dataLength, (int)numBytesDecrypted);
    if (cryptStatus == kCCSuccess)
        return ret;

    return nil;
}

- (NSData *)AES256Decrypt:(id)key
{
    NSData *keyPtr = [key copy];
    size_t dataLength = [self length] - kCCBlockSizeAES128;
    NSData *ivPtr = [self subdataWithRange:NSMakeRange(0, kCCBlockSizeAES128)];
    NSData *encrypted = [self subdataWithRange:NSMakeRange(kCCBlockSizeAES128, dataLength)];

    NSMutableData *ret = [NSMutableData dataWithLength:dataLength + kCCBlockSizeAES128];
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
                                      [keyPtr bytes], kCCKeySizeAES256,
                                      [ivPtr bytes], /* initialization vector (optional) */
                                      [encrypted bytes], dataLength, /* input */
                                      [ret mutableBytes], [ret length], /* output */
                                      &numBytesDecrypted);

    NSLog(@"Err : %d",cryptStatus);
    NSLog(@"DataLength : %d, num : %d", (int)dataLength, (int)numBytesDecrypted);
    if (cryptStatus == kCCSuccess)
        return ret;

    return nil;
}

My String : "abcd"

Encrypt from Python = "fl6h8iBeXGO03ZIKzpDMwMaNc7Y1PsRc/s6XJKPCxKNyrYResv3oO1/bkbofmY7y8e2wOe2sIpk="

来源:https://stackoverflow.com/questions/39404038/encrypt-aes-cbc-pkcs7padding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!