Question

Im trying to encrypt a string in IOS and then decrypt it in C#.

I have been able to encrypt and decrypt the string using only C# but the IOS side seems to be incorrect.

In C# i'm using this to decrypt the string:

private static RSACryptoServiceProvider _rsa;
private const int PROVIDER_RSA_FULL = 1;
private const string CONTAINER_NAME = "KeyContainer";
private const string PROVIDER_NAME = "Microsoft Strong Cryptographic Provider";

private static void _AssignParameter()
{
    CspParameters cspParams;
    cspParams = new CspParameters(PROVIDER_RSA_FULL, PROVIDER_NAME, CONTAINER_NAME);
    cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
    CryptoKeyAccessRule rule = new CryptoKeyAccessRule("everyone", CryptoKeyRights.FullControl, AccessControlType.Allow);
    cspParams.CryptoKeySecurity = new CryptoKeySecurity();
    cspParams.CryptoKeySecurity.SetAccessRule(rule);

    _rsa = new RSACryptoServiceProvider(cspParams);
    _rsa.PersistKeyInCsp = false;
}

private static void decrypt(byte[] data, byte[] PrivateKey)
{
    _AssignParameter();
    _rsa.ImportCspBlob(PrivateKey);
    _rsa.Decrypt(data, false);
}

The above C# code is just a snippet and not full code.

It seems simple enough, This is what i use for IOS,

        //get nsdata from mod and exp
        NSString *mod = publicKeyObjects[0];
        NSData *pubKeyModData= [mod dataUsingEncoding:NSUTF8StringEncoding]; //172 bytes
        NSString *exp = publicKeyObjects[1];
        NSData *pubKeyExpData= [exp dataUsingEncoding:NSUTF8StringEncoding];

        //create nsdata key with mod and exp
        NSMutableArray *publicKeyArray = [[NSMutableArray alloc] init];
        [publicKeyArray addObject:pubKeyModData];
        [publicKeyArray addObject:pubKeyExpData];
        NSData *publicKeyData = [publicKeyArray berData];

        //add the key to the keychain and create a ref
        NSData* peerTag = [@"KeyContainer" dataUsingEncoding:NSUTF8StringEncoding];
        NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];
        [publicKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
        [publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
        [publicKey setObject:peerTag forKey:(__bridge id)kSecAttrApplicationTag];
        SecItemDelete((__bridge CFDictionaryRef)publicKey);

        CFTypeRef persistKey = nil;

        // Add persistent version of the key to system keychain
        [publicKey setObject:publicKeyData forKey:(__bridge id)kSecValueData];
        [publicKey setObject:(__bridge id) kSecAttrKeyClassPublic forKey:(__bridge id)kSecAttrKeyClass];
        [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnPersistentRef];
        OSStatus secStatus = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);
        if (persistKey != nil)
            CFRelease(persistKey);

        // Now fetch the SecKeyRef version of the key
        SecKeyRef keyRef = nil;

        [publicKey removeObjectForKey:(__bridge id)kSecValueData];
        [publicKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
        [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
        [publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
        secStatus = SecItemCopyMatching((__bridge CFDictionaryRef)publicKey,(CFTypeRef *)&keyRef);


        NSData* stringData = [@"string to encrypt" dataUsingEncoding:NSUTF8StringEncoding];
        NSData* encryptedString = [self encrypt:passwordData usingKey:keyRef];


-(NSData *)encrypt:(NSData *)Bytes usingKey:(SecKeyRef)key
{
    size_t cipherBufferSize = SecKeyGetBlockSize(key); //returns 172
    uint8_t *cipherBuffer = NULL;
    cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
    memset((void *)cipherBuffer, 0x0, cipherBufferSize);
    OSStatus status = SecKeyEncrypt(key, kSecPaddingNone,
                                    (const uint8_t *)[Bytes bytes],
                                    [Bytes length], cipherBuffer,
                                    &cipherBufferSize);
    if (status == noErr)
    {
        NSData *encryptedBytes = [[NSData alloc]
                                   initWithBytes:(const void *)cipherBuffer
                                   length:cipherBufferSize];
        if (cipherBuffer)
        {
            free(cipherBuffer);
        }
        NSLog(@"Encrypted text (%d bytes): %@", [encryptedBytes length], [encryptedBytes description]);
        return encryptedBytes;
    }
    else
    {
        NSLog(@"encrypt:usingKey: Error: %d", (int)status);
        return nil;
    }
}

So once i try to decrypt the data on the C# code i get:

The data to be decrypted exceeds the maximum for this modulus of 128 bytes.

I have googled that error and see its got something to do with keysize, but the keysize after the i import the modulus with IOS is 172 bytes.

But im just exporting the public key with _rsa.ToXmlString(false);

EDIT

I think i fixed my own error,

    //get nsdata from mod and exp
    NSString *mod = publicKeyObjects[0];
    NSData *pubKeyModData= [mod dataUsingEncoding:NSUTF8StringEncoding];
    NSString *exp = publicKeyObjects[1];
    NSData *pubKeyExpData= [exp dataUsingEncoding:NSUTF8StringEncoding];

This is converting a base64 string directly with utf8 and it should be using:

NSData *pubKeyModData = [[NSData alloc] initWithBase64EncodedString:mod options:0];
NSData *pubKeyExpData = [[NSData alloc] initWithBase64EncodedString:exp options:0];

Now i get another error Bad Data

Could someone point me in the right direction here? I also apologise for all the code. I just dont know where the problem is.

Was it helpful?

Solution

Answered my own question,

//get nsdata from mod and exp
NSString *mod = publicKeyObjects[0];
NSData *pubKeyModData= [mod dataUsingEncoding:NSUTF8StringEncoding];
NSString *exp = publicKeyObjects[1];
NSData *pubKeyExpData= [exp dataUsingEncoding:NSUTF8StringEncoding];

became this:

//get nsdata from mod and exp
NSString *mod = publicKeyObjects[0];
NSData *pubKeyModData = [[NSData alloc] initWithBase64EncodedString:mod options:0];
NSString *exp = publicKeyObjects[1];
NSData *pubKeyExpData = [[NSData alloc] initWithBase64EncodedString:exp options:0];

Then this

OSStatus status = SecKeyEncrypt(key, kSecPaddingNone,
                                (const uint8_t *)[Bytes bytes],
                                [Bytes length], cipherBuffer,
                                &cipherBufferSize);

became:

OSStatus status = SecKeyEncrypt(key, kSecPaddingPKCS1,
                                (const uint8_t *)[Bytes bytes],
                                [Bytes length], cipherBuffer,
                                &cipherBufferSize);

Simple configurations fix.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top