我使用RNCryptor成功加密/解密iOS中的数据。
我正在尝试将公钥发送到服务器,因此它可以加密一些数据。
NSString *saltString = @"salt'n'peppa";
NSData *salt = [saltString dataUsingEncoding:NSUTF8StringEncoding];
NSData *key = [RNCryptor keyForPassword:password
salt:salt
settings:kRNCryptorAES256Settings.keySettings];
此时,key
中包含一些数据。但是,我似乎无法弄清楚如何将公钥作为字符串:
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;
}
我觉得我正在做一些重大错误,因为谷歌搜索很少。
答案 0 :(得分:4)
密钥不是字符串,而是数据。只是一个随机(某种)系列的字节。将它转换为字符串以发送到服务器的唯一真正方法是对字节进行编码。常用的方法是使用base 64编码。然后,服务器可以将基本64位编码的字符串转换回密钥的原始字节。