我正在使用RNCryptor在iOS中成功加密/解密数据。
我正在尝试将公钥发送到服务器,以便它可以加密一些数据。
NSString *saltString = @"salt'n'peppa";
NSData *salt = [saltString dataUsingEncoding:NSUTF8StringEncoding];
NSData *key = [RNCryptor keyForPassword:password
salt:salt
settings:kRNCryptorAES256Settings.keySettings];
此时,
key
中包含一些数据。但是,我似乎无法弄清楚如何将 public 密钥作为字符串获取:NSString *publicKey = [[NSString alloc] initWithData:key encoding:NSUTF8StringEncoding];
我尝试了不同的编码,但似乎没有任何效果。
这是RNCryptor的keyForPassword方法:
+ (NSData *)keyForPassword:(NSString *)password salt:(NSData *)salt settings:(RNCryptorKeyDerivationSettings)keySettings
{
NSMutableData *derivedKey = [NSMutableData dataWithLength:keySettings.keySize];
// See Issue #77. V2 incorrectly calculated key for multi-byte characters.
NSData *passwordData;
if (keySettings.hasV2Password) {
passwordData = [NSData dataWithBytes:[password UTF8String] length:[password length]];
}
else {
passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];
}
// Use the built-in PBKDF2 if it's available. Otherwise, we have our own. Hello crazy function pointer.
int result;
int (*PBKDF)(CCPBKDFAlgorithm algorithm, const char *password, size_t passwordLen,
const uint8_t *salt, size_t saltLen,
CCPseudoRandomAlgorithm prf, uint rounds,
uint8_t *derivedKey, size_t derivedKeyLen);
PBKDF = CCKeyDerivationPBKDF ?: RN_CCKeyDerivationPBKDF;
result = PBKDF(keySettings.PBKDFAlgorithm, // algorithm
passwordData.bytes, // password
passwordData.length, // passwordLength
salt.bytes, // salt
salt.length, // saltLen
keySettings.PRF, // PRF
keySettings.rounds, // 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;
}
我觉得自己在做一些重大错误,因为谷歌搜索很少。
最佳答案
密钥不是字符串,而是数据。只是随机的(某种)字节系列。将其转换为字符串以发送到服务器的唯一真实方法是对字节进行编码。一种常见的方法是使用base 64编码。然后,服务器可以将基数为64的编码字符串转换回密钥的原始字节。