OGeek|极客世界-中国程序员成长平台

标题: ios - 从 key 字符串生成 64 字节长的 NSData [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:08
标题: ios - 从 key 字符串生成 64 字节长的 NSData

我认为这会生成随机的 64 字节 NSData。

uint8_t buffer[64];
SecRandomCopyBytes(kSecRandomDefault, 64, buffer);
NSData *keyData = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)];

我想像这样生成 64 字节的 NSData,但不是随机数据。 如何使用给定的键(如“com.this.is.akey”)生成 64 字节的 NSData。

试过这个,但它给了我错误的字节大小(不是 64 字节)。

NSString *base64EncodedString = [[@"somekey.here" dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
NSData *encodedData = [[NSData alloc] initWithBase64EncodedString:base64EncodedString
                                                          options:0];



Best Answer-推荐答案


您可以使用 -[NSString dataUsingEncoding:]NSString 转换为 NSData

NSString *key = @"com.this.is.akey";
NSData *keyData = [key dataUsingEncoding:NSASCIIStringEncoding];

如果数据长度小于或大于 64 字节,则应填充或截断数据以精确到 64 字节。

if (keyData.length != 64) {
    NSMutableData *mutableData = keyData.mutableCopy;
    mutableData.length = 64;
    keyData = mutableData.copy;
}

然后,您可以将 NSData 对象传递给 RLMRealmConfiguration.encryptionKey

RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
config.encryptionKey = keyData;

NSError *error = nil;
RLMRealm *realm = [RLMRealm realmWithConfiguration:config error:&error];

关于ios - 从 key 字符串生成 64 字节长的 NSData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34854250/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4