Hi All
I am generating a sharedSecret using apples API. When i use the same shared key inside my JWE object and send it to server, the server throws a pad block corrupted error / exception. I am pretty sure that the error is happening due to the way i have created the shared key. This is because when i flip that implementation of shareSecret using a 3rd party library it works fine. I am trying to get rid of this 3rd party implementation and trying to write my own implemenation. Can anyone suggest / spot any issues with my sharedSecret function below. If not can anyone let me know how to generate a shared secret ( 32 bytes ) out of a private and public EC key ?
Below Implementation which generates pad block corrupted exception.
let sharedZ = try! ecdhDeriveBits(ecPrivJwk: keyPair.getPrivate(),
ecPubJwk: publicKey,
bitLen: 256)
func ecdhDeriveBits(ecPrivJwk: ECPrivateKey, ecPubJwk: ECPublicKey, bitLen: Int = 0) throws -> Data {
if ecPrivJwk.crv != ecPubJwk.crv {
throw NSError(domain: "key derive fail", code: 10, userInfo: nil)
}
let pubKey = try ecPubJwk.converted(to: SecKey.self)
let eprivKey = try ecPrivJwk.converted(to: SecKey.self)
let parameters = [String: Any]()
var error: Unmanaged?
guard let derivedData = SecKeyCopyKeyExchangeResult(
eprivKey,
SecKeyAlgorithm.ecdhKeyExchangeStandard,
pubKey,
parameters as CFDictionary,
&error)
else {
let errStr = error?.takeRetainedValue().localizedDescription ?? "Derive Key Fail"
throw NSError(domain: "key derive fail", code: 10, userInfo: nil)
}
return bitLen > 0 ? truncateBitLen(from: (derivedData as Data), bitLen: bitLen) : (derivedData as Data) as Data
}
Implemention of sharedSecret which works fine using a 3rd party library called chilkat.
let sdkPrivateKey: CkoPrivateKey = loadPrivateKey(privateKeyPkcs1Enc: sdkPrivateKey)!
let sharedKey: Data = getSharedSecretKey(clientPrivateKey: sdkPrivateKey, serverPublicKey: acsPublicKey1)!
func loadPrivateKey(privateKeyPkcs1Enc: String) -> CkoPrivateKey? {
let success: Bool
let privateKey = CkoPrivateKey()
success = privateKey!.loadPkcs1(Data(base64Encoded: privateKeyPkcs1Enc))
if success != true {
print("\(privateKey!.lastErrorText ?? "no key")")
return nil
}
return privateKey
}
func getSharedSecretKey(clientPrivateKey: CkoPrivateKey, serverPublicKey: CkoPublicKey) -> Data? {
JweHelper.unlockLibrary()
let eccClient = CkoEcc()
let sharedSecret: String? = eccClient!.sharedSecretENC(clientPrivateKey, pubKey: serverPublicKey, encoding: "base64")
return Data(base64Encoded: sharedSecret!)
}