我正在關注RSA上的Apple示例代碼。我有一切工作,現在我試圖用動態分配的字符串(從我的textview)替換他們使用的字符串文字。
蘋果的代碼是:數組初始化器目標C
const uint8_t dataToEncrypt[] = "the quick brown fox jumps "
"over the lazy dog\0";
我需要能夠動態地設置這一點,但我不能確定如何做到這一點,因爲當我嘗試,我得到了以下錯誤:「數組初始化函數必須是一個初始化列表或字符串文字」
static const UInt8 publicKeyIdentifier[] = "com.apple.sample.publickey\0";
static const UInt8 privateKeyIdentifier[] = "com.apple.sample.privatekey\0";
- (IBAction)encrypt:(id)sender {
NSString *privateKey = [[NSUserDefaults standardUserDefaults]
stringForKey:@"privateKey"];
OSStatus status = noErr;
size_t cipherBufferSize;
uint8_t *cipherBuffer; // 1
// [cipherBufferSize]
///////////////////
NSString *textToEncode = [NSString stringWithFormat:@"%@%@", self.textView.text, @"\0"];
//////////////////////
const uint8_t dataToEncrypt[] = textToEncode;//This throws the error
//"the quick brown fox jumps over the lazy dog\0"; // 2
size_t dataLength = sizeof(dataToEncrypt)/sizeof(dataToEncrypt[0]);
SecKeyRef publicKey = NULL; // 3
NSData * publicTag = [NSData dataWithBytes:publicKeyIdentifier
length:strlen((const char *)publicKeyIdentifier)]; // 4
NSMutableDictionary *queryPublicKey =
[[NSMutableDictionary alloc] init]; // 5
[queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[queryPublicKey setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
[queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
// 6
status = SecItemCopyMatching
((__bridge CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKey); // 7
// Allocate a buffer
cipherBufferSize = SecKeyGetBlockSize(publicKey);
cipherBuffer = malloc(cipherBufferSize);
// Error handling
if (cipherBufferSize < sizeof(dataToEncrypt)) {
// Ordinarily, you would split the data up into blocks
// equal to cipherBufferSize, with the last block being
// shorter. For simplicity, this example assumes that
// the data is short enough to fit.
printf("Could not decrypt. Packet too large.\n");
}
// Encrypt using the public.
status = SecKeyEncrypt( publicKey,
kSecPaddingPKCS1,
dataToEncrypt,
(size_t) dataLength,
cipherBuffer,
&cipherBufferSize
); // 8
// Error handling
// Store or transmit the encrypted text
if (publicKey) CFRelease(publicKey);
//NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:dataLength];
NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
free(cipherBuffer);
self.textView.text = [NSString stringWithFormat:@"%@",encryptedData];
}
編輯:
替換:
const uint8_t dataToEncrypt[]
With:
NSData *someData = [self.textView.text dataUsingEncoding:NSUTF8StringEncoding];
const void *bytes = [someData bytes];
const uint8_t *dataToEncrypt = (uint8_t*)bytes;
向我們顯示您的代碼。 – NMK 2014-10-19 03:03:11
請參閱'NSString'上的'UTF8String'屬性 – Paulw11 2014-10-19 03:11:27
不要自己進行加密,安全性很強,而小小的錯誤可能會破壞安全性。搜索GitHub for RNCryptor並使用它,它爲Apple的加密系統提供了簡單的Objective-C包裝。 – 2014-10-19 05:56:29