1

这是我的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中得到相同的结果。

4

1 回答 1

0

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

于 2012-07-10T10:57:32.137 回答