IPhone CBC Encryption Restituisce NULL
-
13-12-2019 - |
Domanda
Ho il seguente codice all'interno della classe NSDATA + AES256.Sto provando la crittografia AES CBC a un NSString con il seguente codice.Ho una chiave e un IV.Ma per ottenere null nel risultato.Non riesci a scoprire cosa c'è che non va.Questo è ciò che ho provato -
NSString *initV= @"somekey*********";
NSData *input= [initV dataUsingEncoding:NSUTF8StringEncoding];
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCModeCBC,
keyPtr, kCCKeySizeAES256,
[input bytes] /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
. Soluzione
Questo è il codice che ha funzionato per me finalmente -
-(NSData *)AES256EncryptWithKey:(NSString *)key {
NSUInteger dataLength = [self length];
NSData *keyGiven= [key dataUsingEncoding:NSUTF8StringEncoding];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
NSString *initV= @"***************";
NSData *input= [initV dataUsingEncoding:NSUTF8StringEncoding];
size_t numBytesEncrypted = 0;
CCCryptorRef ccRef;
CCCryptorCreate(kCCEncrypt, kCCAlgorithmAES128, 0, (const void *)[keyGiven bytes], kCCKeySizeAES256, (const void *)[input bytes], &ccRef);
CCCryptorStatus cryptStatus = CCCryptorUpdate(ccRef, [self bytes], dataLength, buffer, bufferSize, &numBytesEncrypted);
CCCryptorRelease(ccRef);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
.
Sto convertendo un NSString in NSDATA e lo passa per la crittografia.Il NSString deve essere di 16 caratteri.Se è di meno di 16 caratteri, lo faccio 16 aggiungendo spazi.
Non so se questo aiuterà a chiunque.Ma ho solo pensato che dovrei condividere.Grazie.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow