0

I have a string which contains some special characters, spaces and, accented characters.

Example: j’aime trop ma série

I am using Commoncypto to encrypt the strings. It works when the string contains plain text. But, its not working when the string is as shown in the example above.

I am using following code:

+ (NSString *) EncryptString:(NSString *)plainSourceStringToEncrypt {
StringEncryption *crypto = [[StringEncryption alloc] init];
    
NSData *_secretData = [plainSourceStringToEncrypt dataUsingEncoding:NSASCIIStringEncoding];
    
NSData *encryptedData = [crypto encrypt:_secretData key:[_key dataUsingEncoding:NSUTF8StringEncoding] padding:&padding];
    
return [encryptedData base64EncodingWithLineLength:0];  }


- (NSData *)encrypt:(NSData *)plainText key:(NSData *)aSymmetricKey padding:(CCOptions *)pkcs7 {
return [self doCipher:plainText key:aSymmetricKey context:kCCEncrypt padding:pkcs7]; }

- (NSData *)doCipher:(NSData *)plainText key:(NSData *)aSymmetricKey
         context:(CCOperation)encryptOrDecrypt padding:(CCOptions *)pkcs7 {
CCCryptorStatus ccStatus = kCCSuccess;
// Symmetric crypto reference.
CCCryptorRef thisEncipher = NULL;
// Cipher Text container.
NSData * cipherOrPlainText = nil;
// Pointer to output buffer.
uint8_t * bufferPtr = NULL;
// Total size of the buffer.
size_t bufferPtrSize = 0;
// Remaining bytes to be performed on.
size_t remainingBytes = 0;
// Number of bytes moved to buffer.
size_t movedBytes = 0;
// Length of plainText buffer.
size_t plainTextBufferSize = 0;
// Placeholder for total written.
size_t totalBytesWritten = 0;
// A friendly helper pointer.
uint8_t * ptr;

// Initialization vector; dummy in this case 0's.
uint8_t iv[kChosenCipherBlockSize];
memset((void *) iv, 0x0, (size_t) sizeof(iv));

NSLog(@"doCipher: plaintext: %@", plainText);
NSLog(@"doCipher: key length: %lu", (unsigned long)[aSymmetricKey length]);

plainTextBufferSize = [plainText length];

//LOGGING_FACILITY(plainTextBufferSize > 0, @"Empty plaintext passed in." );

NSLog(@"pkcs7: %d", *pkcs7);
// We don't want to toss padding on if we don't need to
if(encryptOrDecrypt == kCCEncrypt) {
    if(*pkcs7 != kCCOptionECBMode) {
        
        if((plainTextBufferSize % kChosenCipherBlockSize) == 0) {
            *pkcs7 = 0x0000;
        } else {
            *pkcs7 = kCCOptionPKCS7Padding;
        }
    }
} else if(encryptOrDecrypt != kCCDecrypt) {
    NSLog(@"Invalid CCOperation parameter [%d] for cipher context.", *pkcs7 );
} 

// Create and Initialize the crypto reference.
ccStatus = CCCryptorCreate(encryptOrDecrypt,
                           kCCAlgorithmAES128,
                           *pkcs7,
                           (const void *)[aSymmetricKey bytes],
                           kChosenCipherKeySize,
                           (const void *)iv,
                           &thisEncipher
                           );

// Calculate byte block alignment for all calls through to and including final.
bufferPtrSize = CCCryptorGetOutputLength(thisEncipher, plainTextBufferSize, true);

// Allocate buffer.
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t) );

// Zero out buffer.
memset((void *)bufferPtr, 0x0, bufferPtrSize);

// Initialize some necessary book keeping.

ptr = bufferPtr;

// Set up initial size.
remainingBytes = bufferPtrSize;

// Actually perform the encryption or decryption.
ccStatus = CCCryptorUpdate(thisEncipher,
                           (const void *) [plainText bytes],
                           plainTextBufferSize,
                           ptr,
                           remainingBytes,
                           &movedBytes
                           );

// Handle book keeping.
ptr += movedBytes;
remainingBytes -= movedBytes;
totalBytesWritten += movedBytes;

// Finalize everything to the output buffer.
ccStatus = CCCryptorFinal(thisEncipher,
                          ptr,
                          remainingBytes,
                          &movedBytes
                          );

totalBytesWritten += movedBytes;

if(thisEncipher) {
    (void) CCCryptorRelease(thisEncipher);
    thisEncipher = NULL;
}

if (ccStatus == kCCSuccess)
    cipherOrPlainText = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)totalBytesWritten];
else
    cipherOrPlainText = nil;

if(bufferPtr) free(bufferPtr);

return cipherOrPlainText; }

In the above code i am passing a plain text (which is to be encrypted) to method

+ (NSString *) EncryptString:(NSString *)plainSourceStringToEncrypt

How i can encrypt above example string using CommonCrypto?

chandvoid
  • 133
  • 1
  • 12
  • What do you get when you decrypt the phrase with accented letters? A shorter, minimal, code example would help as well. – rossum Jan 16 '21 at 10:33
  • 1
    What if you use UTF-8 for `_secretData`? – sbooth Jan 16 '21 at 14:13
  • I am using following code to decrypt: + (NSString *)DecryptString:(NSString *)base64StringToDecrypt { StringEncryption *crypto = [[StringEncryption alloc] init]; NSData *data = [crypto decrypt:[base64StringToDecrypt dataUsingEncoding:NSUTF8StringEncoding] key:[_key dataUsingEncoding:NSUTF8StringEncoding] padding: &padding]; return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; } – chandvoid Jan 17 '21 at 02:57
  • Decrypted string is nil – chandvoid Jan 17 '21 at 02:59
  • If i use NSUTF8StringEncoding instead of NSASCIIStringEncoding, decrypted string is still nil. – chandvoid Jan 17 '21 at 03:02
  • Please post a minimal reproducible example (https://stackoverflow.com/help/minimal-reproducible-example) – sbooth Jan 17 '21 at 12:39
  • Could you please elaborate what shall i expected to post? – chandvoid Jan 26 '21 at 10:03

0 Answers0