0

I have the following function

public func encryptWithRSAKey(_ data: String, rsaKeyRef: SecKey, padding: SecPadding) -> [UInt8]? {

    let blockSize = SecKeyGetBlockSize(rsaKeyRef)
    var messageEncrypted = [UInt8](repeating: 0, count: blockSize)
    var messageEncryptedSize = blockSize

    var status: OSStatus!

    status = SecKeyEncrypt(rsaKeyRef, SecPadding.OAEP, data, data.count, &messageEncrypted, &messageEncryptedSize)

    if status != noErr {
        print("\(logClassName): Encryption Error!")
    }

    return messageEncrypted

}

the output is encryptedMessage = [9,43,128...] 128 length

and I have to send the result into a C function

void STDCALL CpProxyAvOpenhomeOrgCredentials1BeginSet(THandle aHandle, const char* aId, const char* aUserName, const char* aPassword, uint32_t aPasswordLen, OhNetCallbackAsync aCallback, void* aPtr)
{
    CpProxyAvOpenhomeOrgCredentials1C* proxyC = reinterpret_cast<CpProxyAvOpenhomeOrgCredentials1C*>(aHandle);
    ASSERT(proxyC != NULL);
    Brh buf_aId(aId);
    Brh buf_aUserName(aUserName);
    Brh buf_aPassword;
    buf_aPassword.Set((const TByte*)aPassword, aPasswordLen);
    FunctorAsync functor = MakeFunctorAsync(aPtr, (OhNetFunctorAsync)aCallback);
    proxyC->BeginSet(buf_aId, buf_aUserName, buf_aPassword, functor);
}

What is the way for encoding messageEncrypted in swift to const char* aPassword in C

1
  • I see no C code anywhere! Commented Nov 12, 2017 at 19:50

2 Answers 2

6

A C function

void cfunc(const char* aPassword, uint32_t aPasswordLen);

is imported to Swift as

public func cfunc(_ aPassword: UnsafePointer<Int8>!, _ aPasswordLen: UInt32)

For an array, withUnsafeBufferPointer() gives you a pointer to the (contiguous) element storage. Due to the different signedness (Int8 vs UInt8), the pointer must be "rebound". Example:

let encryptedMessage: [UInt8] = [9, 43, 128]

encryptedMessage.withUnsafeBufferPointer {
    $0.baseAddress!.withMemoryRebound(to: Int8.self, capacity: encryptedMessage.count) {
        cfunc($0, UInt32(encryptedMessage.count))
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for your answer. and would be the other way back?
0

I prefer this approach:

If I have:

let uint8ArrayVar:[UInt8]= [0,3,4,5]

If i want to sent it throught my c function I just do:

cfunc(uint8ArrayVar.map { Int8(bitPattern: $0) })

1 Comment

You can do that, but it creates an additional array, which is then passed to the C function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.