经过长时间的搜索后,我今天来找你。
我想用特定的方法加密一个单词。
此方法已在Java中实现。我会用客观的C语言或swift得到同样的东西。
我已经探索了几种方法。例如,我尝试运行或RNCryptManager CPCryptController。但我没有得出确凿的结果。
我的java代码如下:
public String encrypt(String texte) {
byte[] bytePassword = Base64.decode(PASSWORD, Base64.DEFAULT);
byte[] byteSalt = Base64.decode(SALT, Base64.DEFAULT);
byte[] bytesIv = Base64.decode(IV, Base64.DEFAULT);
SecretKeyFactory factory = null;
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(PASSWORD.toCharArray(), byteSalt, NB_ITER_RFC, 128);
SecretKey temp = null;
temp = factory.generateSecret(spec);
byte[] clef = temp.getEncoded();
Cipher c = Cipher.getInstance("DESede/CBC/PKCS5Padding");
IvParameterSpec ivParam = new IvParameterSpec(bytesIv);
c.init(Cipher.ENCRYPT_MODE, temp, ivParam);
byte[] encrypted = c.doFinal(texte.getBytes("UTF-8"));
mdp = Base64.encodeToString(encrypted, Base64.DEFAULT);
Log.i("MDP CHIFFRE", " = " + mdp);
}
我打算使用https://developer.apple.com/library/mac/#samplecode/CryptoCompatibility/
我现在的代码是
QCCPBKDF2SHA1KeyDerivation * op;
NSString * passwordString;
NSData * saltData;
NSData * expectedKeyData;
passwordString = @ "Hello Cruel World!";
saltData = [@ "Some salt sir?" dataUsingEncoding: NSUTF8StringEncoding];
expectedKeyData = [QHex dataWithHexString: @ "e56c27f5eed251db50a3"];
op = [[QCCPBKDF2SHA1KeyDerivation alloc] initWithPasswordString: passwordString saltData: saltData]
op.rounds = 1000;
op.derivedKeyLength = 10;
[[ToolCommon sharedInstance] synchronouslyRunOperation: op];
if (nil == op.error) {
NSString * newStr = [[NSString alloc] initWithData: op.derivedKeyData encoding: NSUTF8StringEncoding]
NSLog (@ "This is it:% @", newStr);
} Else {
NSLog (@ "Error");
}
然而,当我运行此代码时,我得到一个null结果。 我没有看到或可以犯错误?转换PBKDF2-HMAC-SHA1的正确解决方案是什么?
提前谢谢。
答案 0 :(得分:-1)
正确的解决方案是:
+ (NSData *)AESKeyForPassword:(NSString *)password
salt:(NSData *)salt {
NSMutableData *
derivedKey = [NSMutableData dataWithLength:kAlgorithmKeySize];
int
result = CCKeyDerivationPBKDF(kCCPBKDF2, // algorithm
password.UTF8String, // password
[password lengthOfBytesUsingEncoding:NSUTF8StringEncoding], // passwordLength
salt.bytes, // salt
salt.length, // saltLen
kCCPRFHmacAlgSHA1, // PRF
kPBKDFRounds, // rounds
derivedKey.mutableBytes, // derivedKey
derivedKey.length); // derivedKeyLen
// Do not log password here
NSAssert(result == kCCSuccess,
@"Unable to create AES key for password: %d", result);
return derivedKey;
}
我在这篇文章中找到了这段代码: http://robnapier.net/aes-commoncrypto