嗨我在解密使用带有ECB模式的AES256在IOS环境中加密的字符串时遇到问题。我必须在java中解密这个加密的字符串。
让我在java中分享我的解密代码
public static String decrypt(String strToDecrypt) throws UnsupportedEncodingException
{
byte[] key = "12345678911234567891123456789112".getBytes("UTF-8");
try
{ Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
final String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt.getBytes("UTF-8"))));
return decryptedString;
}
catch (Exception e)
{
System.out.println("Error while decrypting"+ e);
}
return null;
}
IOS平台上的加密代码
- (NSData *)AES256EncryptWithKey:(NSString *)key:(NSString *)plaintext {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSLog(@" key ptr string %s",keyPtr);
NSData *dTextIn=[plaintext dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = [dTextIn 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, kCCAlgorithmAES128,kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[dTextIn bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
original string is "my name is nitish" // which is encoded in IOS Platform, padding PKCS7Padding and ECB Mode
Encrypted String1 in IOS platform is "p1sBWnbfE/5g3RdT7PHBFy6idtGJlpLBq5IqKV4wXKQ="
Encrypted string in java platform is "p1sBWnbfE/5g3RdT7PHBF8z1aSePf1f9hn6Z33GdrRI="
我不知道是什么错误以及为什么我无法解密java平台中的ios String但我可以在Java平台中解密加密的字符串。请给出一些解决方案。
错误是decryptingjavax.crypto.BadPaddingException:pad block corrupted
提前致谢