Objective C AES加密等于java版本 [英] Objective C AES encrypt equal to java version

查看:119
本文介绍了Objective C AES加密等于java版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有java代码来加密密码,

I have java code to encrypt a password,

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代码?

Now I need to encrypt/decrypt it with objective-c, I do a lot of search and none method would generate the same encrypted output.
What's the objective-c version code equal to java code?

测试用例:encryptToString(test ,密码)=> DA180930496EC69BFEBA923B7311037A

test case: encryptToString("test","password") => DA180930496EC69BFEBA923B7311037A

推荐答案

我相信这个问题的答案正是您所寻找的:用于AES加密解密的任何可可源代码?

I believe the answers to this question are what you are looking for: Any cocoa source code for AES encryption decryption?

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

I adapted a function somebody posted as answer: https://gist.github.com/4335132

使用:

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

由于您的Java代码不使用密码,因此不完全相同本身用于加密,但使用它来播种随机数生成器。但我认为这仍然适用于你想要做的事情。

It's not exactly the same because your Java code does not use the password itself for encrypting but uses it to seed a random number generator. But I think that this should still work with what you are trying to do.

这篇关于Objective C AES加密等于java版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆