I've went through all the posts with similar info about signature or keys used not working with openssll. But I haven't been able to patch it all together.
I will use some sample keys for what I tried,
let privPem = """
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgIUSrwhllMSminPZZ
Gx0YHUsL12IWIGI+4yhejpq90HihRANCAAT6pxKtIKm4VbfXeKpQ7rxITlC6b18Q
0X+Iz1UVDolyjx79bt5vUp0mPJ6hHBnK/Ap5gXpv89wmLPp7/O2NconE
-----END PRIVATE KEY-----
"""
let privKey = try! P256.Signing.PrivateKey(pemRepresentation: privPem)
let pubKey = privKey.publicKey
let challengeDev = "1122334455667788"
let dataToSignDev = challengeDev.hexadecimal
let digest = SHA256.hash(data: dataToSignDev!)
let signatureForDigest = try! privKey.signature(
for: digest)
let signature1 = try! P256.Signing.ECDSASignature(derRepresentation: signatureForDigest.derRepresentation)
let isValidSignature = pubKey.isValidSignature(signatureForDigest, for: digest)
I have tried the same using Security framework also to no avail.
What I tried is a direct application of what the openssl part does, So I have a device that will verify the signature that the iOS app will be sending. The public key is taken from a certificate I would share with the device. All data sent to the device including signature is in DER format.
openssl dgst -sha256 -sign app_private.key -out %OUT_RESOURCES_DIR%\signature.der -binary device_challenge.hex
openssl x509 -inform der -in cert.der -out cert.pem
openssl x509 -pubkey -noout -in cert.pem > public_key.pem
openssl dgst -sha256 -verify public_key.pem -signature signature.der challenge.hex
Here on the iOS side If I were to sign and verify everything is fine. But if the same signature is verified on OpenSSL it fails.
I tried to create a DER file on the terminal but asn1parse fails on it,
Test % echo 30450220198944e2a8352941036f227225940392cbd1bc720358ce29db29a2a85f2b2a30022100b4e75ceb0335e4b1955aab01edc8e7347f78dc627f8d02a78103cd9165571d57 > signature1.der
Test % openssl asn1parse -inform DER -in signature1.der
0:d=0 hl=2 l= 48 cons: PRINTABLESTRING
Error in encoding
140704639042368:error:0DFFF09B:asn1 encoding routines:CRYPTO_internal:too long:/AppleInternal/Library/BuildRoots/97f6331a-ba75-11ed-a4bc-863efbbaf80d/Library/Caches/com.apple.xbs/Sources/libressl/libressl-3.3/crypto/asn1/asn1_lib.c:143:
I'm assuming I need to manually do some changes to make them inter compatible?
Like this post
Can't export EC kSecAttrTokenIDSecureEnclave public key
Not sure how to get there though. All help appreciated.
Apple CryptoKit
RSS for tagPerform cryptographic operations securely and efficiently using Apple CryptoKit.
Posts under Apple CryptoKit tag
26 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Hello,
I am attempting to perform a Diffie Hellman Keyexchange with a server running on .Net.
However, the secretKey I am creating on the client side does not match with the secretKey on the server side, which I have for testing purposes.
I can import the server secret key as a SymetricKey, and if I use it to seal and open a box, it works. However, if I seal the box with my client key, I can not open it with the server shared key.
I create the SymetricKey like this:
let sharedHash = SHA256.self
let sharedInfo = serverPublicKey.rawRepresentation
let sharedLength = 32
let symetricKey = sharedSecret.x963DerivedSymmetricKey(
using: sharedHash,
sharedInfo: Data(),
outputByteCount: sharedLength)
The server key is created using .Net like this:
bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
bob.HashAlgorithm = CngAlgorithm.Sha256;
bobPublicKey = bob.PublicKey.ToByteArray();
bobKey = bob.DeriveKeyMaterial(CngKey.Import(Alice.alicePublicKey, CngKeyBlobFormat.EccPublicBlob));
My assumption is the keys should be the same. Is that correct?
How can I find out what format the server key is in? The .Net documentation is not particularly precise on that
You can find a Playground of my code, and when you google for ECDiffieHellmanCng Class, you will find an example on what .Net does.
Any help is appreciated
AES 128 CBC algorithm is not producing same results compared to Android code. We have all static strings for key, iv and salt, even then the IV we couldnt match and produce same output as android.
This is the Android code,
object AESEncyption {
fun encrypt(strToEncrypt: String) : String?
{
try
{
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
val factory =
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
val spec: KeySpec = PBEKeySpec(secretKey.toCharArray(), hex(salt), iterationCount, keySize)
val key: SecretKey = SecretKeySpec(factory.generateSecret(spec).encoded, "AES")
cipher.init(Cipher.ENCRYPT_MODE, key, IvParameterSpec(hex(iv)))
return base64(cipher.doFinal(strToEncrypt.toByteArray(Charsets.UTF_8)))
}
catch (e: Exception)
{
Log.i("Him","Error while encrypting: $e")
}
return null
}
private fun base64(bytes: ByteArray?): String {
return android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT)
}
/* fun base64(str: String?): ByteArray? {
return Base64.decodeBase64(str)
}*/
fun hex(bytes: ByteArray?): String? {
return Hex.encodeHexString(bytes)
}
fun hex(str: String): ByteArray? {
return try {
Hex.decodeHex(str.toCharArray())
} catch (e: DecoderException) {
throw IllegalStateException(e)
}
}
}
iOS code is
let enc = try AES(key: keyVar2!.bytes, blockMode: CBC(iv: iv.base64FromHex.ivToUInt8Array), padding: .pkcs5).encrypt(value.bytes)
let encryptedData = Data(enc)
I have a Build Phase which runs a script. The script is a swift file, which I have simplified to illustrate the crash, like so:
#!/usr/bin/env xcrun --sdk macosx swift
import Foundation
import CryptoKit
var sha256 = SHA256()
// Do other stuff...
All the Xcode 15 betas fail to build my app, instead throwing the error: Command PhaseScriptExecution failed with a nonzero exit code.
The logs:
JIT session error: Symbols not found: [ _$s9CryptoKit6SHA256VMa, _$s9CryptoKit6SHA256VACycfC ]
Failed to materialize symbols: { (main, { _$s20PropertyListModifier6sha2569CryptoKit6SHA256Vvp, _main, __swift_FORCE_LOAD_$_swiftDarwin_$_PropertyListModifier, __swift_FORCE_LOAD_$_swiftIOKit_$_PropertyListModifier, ___swift_project_value_buffer, __swift_FORCE_LOAD_$_swiftFoundation_$_PropertyListModifier, ___swift_allocate_value_buffer, __swift_FORCE_LOAD_$_swiftObjectiveC_$_PropertyListModifier, __swift_FORCE_LOAD_$_swiftXPC_$_PropertyListModifier, __swift_FORCE_LOAD_$_swiftCoreFoundation_$_PropertyListModifier, __swift_FORCE_LOAD_$_swiftDispatch_$_PropertyListModifier }) }
Does anyone know of a work-around or solution, or does this just look like nothing more than a bug in the betas, which I should "wait out"? It's had the same problem right from beta 1 to the current beta 5 so it's starting to look like it won't be fixed which is worrying me.
Hi guys,
I need to use deterministic ECDSA (described in RFC 6979 article: https://www.rfc-editor.org/rfc/rfc6979) algorithm to calculate signature in iOS project.
It is known that deterministic ECDSA is vulnerable to fault injection and side-channel attacks, so there is an updates for RFC 6979 described in following article (see section 4): https://www.ietf.org/archive/id/draft-mattsson-cfrg-det-sigs-with-noise-04.html#name-updates-to-rfc-6979-determi
I tried to find any information related to deterministic ECDSA algorithm implementation and support in iOS ecosystem, but unfortunately found nothing
Could you please provide me complete information whether the deterministic ECDSA with updates is implemented and provides by iOS API?
Any guidance or information on this matter would be greatly appreciated.
Looking forward for you soon. ))
I'm trying to implement client certificate authentication in the URLSessionDelegate.urlSession(:didReceive:completionHandler:) by using the URLCredential(identity:certificates:persistence:) and CryptoKit, but it appears this is currently not supported. On my client I generate a key and a CSR and after I sent that to the server, I receive an X.509 certificate which I store in the Keychain.
I used to create the keys as SecKey objects, which were also stored in the Keychain; this works fine. Now I would like to use the CryptoKit keys, preferably the SecureEnclave.P256 ones. It appears that storing these keys, as suggested by Apple (generic passwords), does not create the SecIdentity I'm after that's needed to create the URLCredential, nor have I been able to transform a SecKey created in the Secure Enclave to a CryptoKit.SecureEnclave.P256 key. The SecKeyCopyExternalRepresentation function simply returns an error telling me that I cannot export Secure Enclave keys (which is weird, as CryptoKit's implementation does somewhat allow this).
Also, the URLCredential.init does not allow you to add a private key directly, nor does the SecIdentity provide any way of manually creating it, by supplying the right keys and the right certificates.
How can I use CryptoKit for client certificate authentication or how can I use CryptoKit or the older SecKey implementations to create SecIdentity or URLCredential objects that will work?