beatty / applepay_crypto_demo

108 stars 18 forks source link

ephemeralPublicKey returns null #4

Closed MaxApp closed 9 years ago

MaxApp commented 9 years ago

with bcprov-jdk16 (from 1.45 to 1.49 ) and bcpkix-jdk16 (from 1.45 to 1.49), running the following code:

PEMReader pemReaderPublic = new PEMReader(new StringReader(ephemeralPubKeyStr)); 
ECPublicKey ephemeralPublicKey = (ECPublicKey) pemReaderPublic.readObject(); 

the 'ephemeralPublicKey' was null. Debug into the code:

private PublicKey readPublicKey(String endMarker)
        throws IOException
    {
        KeySpec keySpec = new X509EncodedKeySpec(readBytes(endMarker));
        String[] algorithms = { "DSA", "RSA" };
        for (int i = 0; i < algorithms.length; i++) 
        {
            try 
            {
                KeyFactory keyFact = KeyFactory.getInstance(algorithms[i], provider);
                PublicKey pubKey = keyFact.generatePublic(keySpec);
                return pubKey;
            }
            catch (NoSuchAlgorithmException e) 
            { 
                // ignore
            }
            catch (InvalidKeySpecException e) 
            { 
                // ignore
            }
            catch (NoSuchProviderException e)
            {
                throw new RuntimeException("can't find provider " + provider);
            }
        }
        return null;
    }

' PublicKey pubKey = keyFact.generatePublic(keySpec);' always fall into 'InvalidKeySpecException'

bentoo commented 9 years ago

Did you ever find a resolution to this issue?

bentoo commented 9 years ago

I was able to resolve this issue by using BouncyCastle 1.46

http://central.maven.org/maven2/org/bouncycastle/bcprov-jdk16/1.46/bcprov-jdk16-1.46.jar

bentoo commented 9 years ago

I talked to the CryptoWorkshop team that built the BouncyCastle library and they gave me the following fix:

PEMParser pemReaderPublic = new PEMParser(new StringReader(ephemeralPubKeyStr));
SubjectPublicKeyInfo ephemeralPublicKeyInfo = (SubjectPublicKeyInfo)pemReaderPublic.readObject();

ECPublicKey ephemeralPublicKey = (ECPublicKey)new JcaPEMKeyConverter().setProvider("BC").getPublicKey(ephemeralPublicKeyInfo);
MaxApp commented 9 years ago

So many thanks,bentoo. I use the following code for retrieving ECPublicKey:

KeySpec keySpec = new X509EncodedKeySpec(ephemeralPublicKey_bytes);
KeyFactory keyFact = KeyFactory.getInstance("EC", Security.getProvider("BC"));
PublicKey pubKey = keyFact.generatePublic(keySpec);
ephemeralPublicKey = (ECPublicKey)pubKey;

that runs well