AES / cbc / pkcs5padding encription IOS
我在android中使用AESalgorithm进行encryption。 下面的代码我们用于encryption。
String seed = "somekey"; Key key = null; // 128 bit key byte[] byteKey = seed.substring(0, 16).getBytes("UTF-8"); key = new SecretKeySpec(byteKey, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec( new byte[16])); byte[] encValue = cipher.doFinal(pValue.getBytes()); encryptedText = new BASE64Encoder().encode(encValue);
任何人都可以提供上述IOS的逻辑。
提前感谢。
您可以使用下面的代码片段作为起点:
+ (NSData*)encryptData:(NSData*)data key:(NSData*)key iv:(NSData*)iv; { NSData* result = nil; // setup key unsigned char cKey[FBENCRYPT_KEY_SIZE]; bzero(cKey, sizeof(cKey)); [key getBytes:cKey length:FBENCRYPT_KEY_SIZE]; // setup iv char cIv[FBENCRYPT_BLOCK_SIZE]; bzero(cIv, FBENCRYPT_BLOCK_SIZE); if (iv) { [iv getBytes:cIv length:FBENCRYPT_BLOCK_SIZE]; } // setup output buffer size_t bufferSize = [data length] + FBENCRYPT_BLOCK_SIZE; void *buffer = malloc(bufferSize); // do encrypt size_t encryptedSize = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, FBENCRYPT_ALGORITHM, kCCOptionPKCS7Padding, cKey, FBENCRYPT_KEY_SIZE, cIv, [data bytes], [data length], buffer, bufferSize, &encryptedSize); if (cryptStatus == kCCSuccess) { result = [NSData dataWithBytesNoCopy:buffer length:encryptedSize]; } else { free(buffer); NSLog(@"[ERROR] failed to encrypt|CCCryptoStatus: %d", cryptStatus); } return result; } + (NSData*)decryptData:(NSData*)data key:(NSData*)key iv:(NSData*)iv; { NSData* result = nil; // setup key unsigned char cKey[FBENCRYPT_KEY_SIZE]; bzero(cKey, sizeof(cKey)); [key getBytes:cKey length:FBENCRYPT_KEY_SIZE]; // setup iv char cIv[FBENCRYPT_BLOCK_SIZE]; bzero(cIv, FBENCRYPT_BLOCK_SIZE); if (iv) { [iv getBytes:cIv length:FBENCRYPT_BLOCK_SIZE]; } // setup output buffer size_t bufferSize = [data length] + FBENCRYPT_BLOCK_SIZE; void *buffer = malloc(bufferSize); // do decrypt size_t decryptedSize = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, FBENCRYPT_ALGORITHM, kCCOptionPKCS7Padding, cKey, FBENCRYPT_KEY_SIZE, cIv, [data bytes], [data length], buffer, bufferSize, &decryptedSize); if (cryptStatus == kCCSuccess) { result = [NSData dataWithBytesNoCopy:buffer length:decryptedSize]; } else { free(buffer); NSLog(@"[ERROR] failed to decrypt| CCCryptoStatus: %d", cryptStatus); } return result; }
常量
#define FBENCRYPT_ALGORITHM kCCAlgorithmAES128 #define FBENCRYPT_BLOCK_SIZE kCCBlockSizeAES128 #define FBENCRYPT_KEY_SIZE kCCKeySizeAES256
有关更多信息,请参阅FBEncryptor
希望这可以帮助。
由于AES的块大小为16个字节,因此PKCS#7Padding是必需的。 一些早期的AES库实现者错误地指定了PKCS#5Padding。
PKCS#5Padding仅针对最大为8个字节的块指定,对于最大为255个字节的块指定PKCS#7Padding。 参见Wikipedia: 填充 。 IOW PKCS#7Padding可以用来代替PKCS#5Padding。
它适用于Android与:
#define FBENCRYPT_KEY_SIZE kCCKeySizeAES128
代替:
#define FBENCRYPT_KEY_SIZE kCCKeySizeAES256