我有以下功能
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
}
输出是encryptedMessage = [9,43,128 ...] 128长度
我必须将结果发送到C函数
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);
}
将swift中的messageEncrypted编码为C中的const char * aPassword的方法是什么
答案 0 :(得分:4)
C函数
void cfunc(const char* aPassword, uint32_t aPasswordLen);
以
的形式导入Swiftpublic func cfunc(_ aPassword: UnsafePointer<Int8>!, _ aPasswordLen: UInt32)
对于数组,withUnsafeBufferPointer()
为您提供指向
(连续的)元素存储。由于签名不同
(Int8 vs UInt8),指针必须是&#34;反弹&#34;。例如:
let encryptedMessage: [UInt8] = [9, 43, 128]
encryptedMessage.withUnsafeBufferPointer {
$0.baseAddress!.withMemoryRebound(to: Int8.self, capacity: encryptedMessage.count) {
cfunc($0, UInt32(encryptedMessage.count))
}
}
答案 1 :(得分:0)
我更喜欢这种方法:
如果我有:
let uint8ArrayVar:[UInt8]= [0,3,4,5]
如果我想通过我的c函数发送它,我只是这样做:
cfunc(uint8ArrayVar.map { Int8(bitPattern: $0) })