【问题标题】:Objective C AES encrypt equal to java versionObjective C AES加密等于java版本
【发布时间】:2012-12-19 06:30:14
【问题描述】:

我有java代码来加密密码,

public static String encryptToString(String content,String password) throws IOException {
    return parseByte2HexStr(encrypt(content, password));
}
private static byte[] encrypt(String content, String password) {
    try {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(password.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        byte[] byteContent = content.getBytes("utf-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] result = cipher.doFinal(byteContent);
        return result;
    } catch (Exception e) {
        log.error(e.getMessage(),e);
    }
    return null;
}
public static String parseByte2HexStr(byte buf[]) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < buf.length; i++) {
        String hex = Integer.toHexString(buf[i] & 0xFF);
        if (hex.length() == 1) {
            hex = '0' + hex;
        }
        sb.append(hex.toUpperCase());
    }
    return sb.toString();
}

现在我需要使用 Objective-c 对其进行加密/解密,我进行了大量搜索,但没有一种方法会生成相同的加密输出。
objective-c版本代码等于java代码是多少?

测试用例:encryptToString("test","password") => DA180930496EC69BFEBA923B7311037A

【问题讨论】:

    标签: objective-c ios


    【解决方案1】:

    我相信这个问题的答案就是您正在寻找的:Any cocoa source code for AES encryption decryption?

    我改编了一个有人发布为答案的函数:https://gist.github.com/4335132

    使用方法:

    NSString *content = @"test";
    NSData *dataToEncrypt = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [dataToEncrypt AES128EncryptWithKey:@"password"];
    NSString *hex = [data hexString];
    

    这并不完全相同,因为您的 Java 代码不使用密码本身进行加密,而是使用它来生成随机数生成器。但我认为这仍然适用于您正在尝试做的事情。

    【讨论】:

    • 是的,它显示了 CommonCrypto 中的 AES 功能是如何工作的。有了这些知识,您可以轻松地将 Java 代码转换为 Objective-C。
    • 是的,如果我使用 java 版本指定相同的密钥字节,这可以工作,现在的问题是如何生成/计算正确的密钥。
    • 如果我理解正确,您将永远无法得到完全相同的结果,因为密钥只是随机字节。 Security.framework 中也有类似的方法。试试他在博客上记录的 Rob Napiers AESKeyForPassword 函数:robnapier.net/blog/aes-commoncrypto-564
    • 我需要与java版本相同的方式,因为我需要解密iOS上java代码生成的密码。我只是对关键字节进行硬编码,它就可以工作。
    • @xfx 你能分享你的目标c代码吗?我使用上面的目标c代码得到“D870F7E3B4B00465AB95EB58DB5278DF”,请帮助我需要改变什么?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 2014-03-24
    • 1970-01-01
    • 2011-03-06
    • 2017-06-16
    • 2013-04-19
    • 1970-01-01
    相关资源
    最近更新 更多