如何使用DES加密Java中的数据并将该数据解密为Object-c

时间:2012-07-10 10:34:31

标签: java objective-c encryption

这是我的java代码使用des

public class DES {

    public static String encode(String str, String key) throws Exception {
        byte[] rawKey=Base64.decode(key);
        IvParameterSpec sr=new IvParameterSpec(rawKey);
        DESKeySpec dks=new DESKeySpec(rawKey);
        SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("DES");
        SecretKey secretKey=keyFactory.generateSecret(dks);

        javax.crypto.Cipher cipher=Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);

        byte data[]=str.getBytes("UTF8");
        byte encryptedData[]=cipher.doFinal(data);
        return Base64.encode(encryptedData).trim();
    }

    public static String decode(String str, String key) throws Exception {
        byte[] rawKey=Base64.decode(key);
        IvParameterSpec sr=new IvParameterSpec(rawKey);
        DESKeySpec dks=new DESKeySpec(rawKey);
        SecretKeyFactory keyFactory=SecretKeyFactory.getInstance("DES");
        SecretKey secretKey=keyFactory.generateSecret(dks);
        Cipher cipher=Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);
        byte encryptedData[]=Base64.decode(str);
        byte decryptedData[]=cipher.doFinal(encryptedData);
        return new String(decryptedData, "UTF8").trim();
    }
}

我是Objective-c的新手,在Ojbective-c DES中遇到一些麻烦, 上面的代码是使用java,我想加密或解密一个字符串,最后在Object-c中得到相同的结果。

1 个答案:

答案 0 :(得分:0)

CommonCrypto库(在C中,因此可以从Objective-C使用,并且是Mac OS X和iOS的一部分)实现DES算法。例如,请参阅此问题:Encryption for Objective-C