如何在objective-c中从Java密码加密的文件中解密

如何在objective-c中从Java密码加密的文件中解密,java,iphone,ios,encryption,Java,Iphone,Ios,Encryption,我有一个Java加密方法 public static String encrypt(String orignal){ SecretKeySpec key = new SecretKeySpec(keyString.getBytes(), "AES"); IvParameterSpec initalVector = new IvParameterSpec(initialVectorParam.getBytes()); try{ Cipher cipher

我有一个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);
        return bytes2Hex(test);
    }catch (Exception e) {
        Log.d("AES", "Encrypt Exception:"+orignal);
        return "";
    }
}
公共静态字符串加密(字符串原始){
SecretKeySpec key=newsecretkeyspec(keyString.getBytes(),“AES”);
IvParameterSpec initalVector=新的IvParameterSpec(initialVectorParam.getBytes());
试一试{
Cipher Cipher=Cipher.getInstance(“AES/CFB8/NoPadding”);
///////////////加密/////////////////
cipher.init(cipher.ENCRYPT_模式,密钥,initalVector);
Log.d(“AES”,“oriByte:+orignal.getBytes());
int length=orignal.length();

对于(int i=0;i的初始化向量,请参见Paste中的第24行:

NULL /* initialization vector (optional) */,
那是你通过静脉注射的地方

但是,如果不知道用于创建用作IV的字节的Java代码的字符串编码,即使您知道字符串在屏幕上显示为什么,您也无法正确地对加密进行种子设定以解密数据。换句话说,就是因为IV看起来像“abc123”这并不意味着Java写入IV缓冲区的字节数将与从C字符文本缓冲区
strncpy()
获得的字节数相同。您必须同意将编码作为处理数据协议的一部分

您还需要就密钥大小达成一致。您的Java代码没有指定AES密钥中有多少位

一旦你解决了这个问题,你就会想打一个电话,比如:

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);
假设一切顺利,明文将被写入密文。解密期间写入
文本
的数据量将存储在
outlen
中。错误检查是您的责任;标题注释良好

一旦你有了数据,你就会想用正确的编码把它拼成一个
NSString
+[NSString initWithData:encoding://code>),然后你就有了一个字符串,你可以像其他任何字符串一样从Obj-C中使用它。

对于
getBytes()
,确保指明编码(有一个重载方法,它接受一个编码参数)。