0

I'm trying to generate EC key Pair and I want to send PublicKey in base64 to backend but I'm getting errors: java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: Detect premature EOF and java.lang.IllegalArgumentException: Illegal base64 character 4 Key pair generate:

let keyAttribute = [kSecAttrType as String: kSecAttrKeyTypeECSECPrimeRandom,
                    kSecAttrKeySizeInBits as String: 256] as CFDictionary

 func generatePair() {
      SecKeyGeneratePair(keyAttribute, &publicKeySec, &privateKeySec)
 }

getting base64 public key:

if let publicKeySec = publicKeySec, let cfData = SecKeyCopyExternalRepresentation(publicKeySec, &error) {
     let data: Data = cfData as Data
     let b64Key = data.base64EncodedString()
     return b64Key
}

here is how to backend is trying to decode my publicKey:

private static PublicKey decodePublicKey(String base64PublicKey) {
        PublicKey publicKey = null;
        try {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes()));
            KeyFactory keyFactory = KeyFactory.getInstance("EC");
            publicKey = keyFactory.generatePublic(keySpec);
            return publicKey;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return publicKey;
    }
Gorthez
  • 391
  • 3
  • 12
  • 1
    Can you post a sample for the key generated with the Swift code? – Topaco Mar 15 '21 at 09:01
  • @Topaco sure, here it is: BEWwrysH5qaztigcASqAmk3JdQUSY/tHrP/M5q/Rthf18SZlfTT5U+7cFsoW6QV1p7k6/2NG/OXA95pamMvUmzA= – Gorthez Mar 15 '21 at 09:05
  • 3
    The Base64 decoded data seems to define an uncompressed EC key: 0x04 + x + y. However, the Java code expects an X.509/SPKI key (DER encoded). Either the Swift side must be modified to export a key in this format or the Java code must be modified to import an uncompressed EC key. – Topaco Mar 15 '21 at 09:14
  • 3
    The answers in the question https://stackoverflow.com/questions/30445997/loading-raw-64-byte-long-ecdsa-public-key-in-java will help you in loading the uncompressed EC public key. – Michael Fehr Mar 15 '21 at 10:48

0 Answers0