Search code examples
c#swiftcryptographysignecdsa

SWIFT. Verification of the document signature issue. 64 bytes instead of 71


I have a task to verify of signature compliance for the metadata, but for some reason all the methods that I used return 'false'. The document is signed via C # in the following way:

//Cert format X509Certificate2
var ecdsa = cert.GetECDsaPrivateKey());
byte[] signature;
signature = ecdsa.SignData(bufferedFileStream, HashAlgorithmName.SHA512);

And we get the signature with size = 64 bytes

But swift native method generate signature with size = 71 bytes:

let signature = SecKeyCreateSignature(privateKey,
                                      .ecdsaSignatureMessageX962SHA256,
                                      fileData as CFData,
                                      &signError)

Certificate generated with ECDSA NIST p256 Sig. Algorithm - ecdsa-with-SHA256

Till now I tried 3 ways of ways of checking:

//1
SecKeyVerifySignature(publicKey,
                      .ecdsaSignatureMessageX962SHA256,
                      fileData as CFData,
                      signature as! CFData,
                      &error)
//2
SecKeyRawVerify(publicKey,
                .PKCS1SHA512,
                hashedDataBytes,
                digestLength,
                signatureBytes,
                signatureData.count)
//3
let publicKeyP265 = try! P256.Signing.PublicKey(x963Representation: bytesArray)
let ecdsaSignature = try! P256.Signing.ECDSASignature(rawRepresentation: signature)             
let result = publicKeyP265.isValidSignature(ecdsaSignature, for: fileData)

The result is negative for each method

So far, I have not been able to achieve success and validate the signature, perhaps someone has encountered a similar problem.


Solution

  • I solved my problem with next code:

        let publicKeyP265 = try! P256.Signing.PublicKey(x963Representation: bytesArray)
        let ecdsaSignature = try! P256.Signing.ECDSASignature(rawRepresentation: signature)
        let fileDataDigest = SHA512.hash(data: fileData)
        
        let result = publicKeyP265.isValidSignature(ecdsaSignature, for: fileDataDigest)
    

    I hope it will be useful for somebody else.