我必须使用AES / ECB / PKCS7Padding加密数据。我已经附加了正在运行的Java和Swift代码。对于swift,我使用了" SCrypto"荚。但是现在,为了在我的Obj C项目中使用相同的逻辑,我使用了以下的ObjC代码。但它返回一个diff值。
Java代码:(工作)
public String encryption(String unencryptedString) {
if (unencryptedString == null) {
return "";
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digestOfPassword = md.digest(SECRET_KEY.getBytes("utf-8"));
byte[] keyBytes = Arrays.copyOf(digestOfPassword, 16);
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] plainTextBytes = unencryptedString.getBytes("utf-8");
byte[] buf = cipher.doFinal(plainTextBytes);
return new String(Base64.encodeBase64(buf));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Swift Code :(工作)
class func MD5Encryption(stringToBeEncrypted: String) -> String
{
print("stringToBeEncrypted..\(stringToBeEncrypted)")
let plaintext = stringToBeEncrypted.data(using: String.Encoding.utf8)!
let digestKey = "##SECRETKEY##"
let sharedSecretKey = digestKey.data(using: String.Encoding.utf8)!.MD5() // AES-256
let ciphertext = try! plaintext.encrypt(.aes, options: [.PKCS7Padding, .ECBMode], key: sharedSecretKey)
let encryptedString = ciphertext.base64EncodedString()
return encryptedString
}
但是在下面的ObjC代码中,它提供了一个不同的加密字符串。
- (void) generateHeader
{
NSString *stringToBeEncyrpted = [NSString stringWithFormat:@"%@|%@", userId, contactName];
NSData *plainData = [stringToBeEncyrpted dataUsingEncoding:NSUTF8StringEncoding];
NSData * cipherText = [plainData AES256Operation:kCCEncrypt key:@"##SECRETKEY##" iv:nil];
NSString *encyrptedString = [cipherText base64Encoding];
NSLog(@"encyrptedString..%@", encyrptedString);
}
- (NSData *)AES256Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv
{
char keyPtr[kCCKeySizeAES128+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
key = [key stringFromMD5];
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES, kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr, kCCBlockSizeAES128,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
我的主要要求是: 1)首先,我需要在密钥上应用MD5算法 2)然后我需要加密' stringToBeEncrypted'使用AES / ECB / PKCS7Padding
这是因为它是在API端解密的方式。