How can I decrypt in objective-c from a file encrypted by Java Cipher
I have an encrypt method in Java.
public static String encrypt(String orignal){
SecretKeySpec key = new SecretKeySpec(keyString.getBytes(), "AES");
IvParameterSpec initalVector = new IvParameterSpec(initialVectorParam.getBytes());
try{
Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding");
/////////////// encrypt /////////////////
cipher.init(Cipher.ENCRYPT_MODE, key, initalVector);
Log.d("AES", "oriByte: "+ orignal.getBytes());
int length = orignal.length();
for(int i=0; i<length; i++){
}
byte[] test = cipher.doFinal(orignal.getBytes());
Log.d("AES", "encByte: "+ test);
retur开发者_Go百科n bytes2Hex(test);
}catch (Exception e) {
Log.d("AES", "Encrypt Exception:"+orignal);
return "";
}
}
For compatibility with PHP, I use "AES/CFB8/NoPadding" options. In PHP: $sCipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $sKey, $sStr, MCRYPT_MODE_CFB, $sIV);
And I have a Objective-c Cipher code from here. https://gist.github.com/838614
I found that there is no IvParameterSpec in Objective-c Cipher like java. Besides, the getBytes method returns a different value with java. (I think this is because java uses different encoding way.)
So, how can I apply IvParameterSpec in Objective-c. And is there any way to get 'getBytes' value like java in Objective-c?
For the initialization vector, see line 24 in your pastie:
NULL /* initialization vector (optional) */,
That's where you would pass your IV.
But without knowing the string encoding the Java code used to create the bytes used as the IV, you won't be able to seed the encryption properly to decrypt the data, even if you know what the string displays to the screen as. Put another way, just because the IV looks like "abc123" doesn't mean the bytes Java is writing to the IV buffer are going to be the same bytes you'll get if you strncpy()
from a C character literal buffer. You have to agree on the encoding as part of the protocol for handling the data.
You will also need to agree on a key size. Your Java code does not specify how many bits are in the AES key.
Once you've got that worked out, you'll want to use a call like:
const void *key = /* KEY BYTES */;
const void *iv = /* IV BYTES */;
const void *text = /* CIPHER TEXT */;
size_t textlen = /*...*/;
size_t outlen = 0;
(void)CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0/*use CBC mode*/,
key, kCCKeySizeAES128, iv,
text, textlen,
&text, textlen, &outlen);
The plaintext will be written over the ciphertext, assuming all goes well. The amount o data written to text
during decryption will be stored in outlen
. Error checking is your responsibility; the header is well-commented.
Once you have the data, you'll want to slurp it into an NSString
with the correct encoding (+[NSString initWithData:encoding:]
would work), and then you have a string you can work with from Obj-C like any other string.
精彩评论