private static Key loadEcPublicKey(final byte [] pubKey, final EcCurve curveName) throws NoSuchAlgorithmException, InvalidKeySpecException { final ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName.toString()); KeyFactory kf; try { kf = KeyFactory.getInstance(ECDH, BouncyCastleProvider.PROVIDER_NAME); } catch (final NoSuchProviderException e) { LOGGER.warning( "No se ha podido obtener el KeyFactory ECDH de BouncyCastle, se intentara el por defecto: " + e //$NON-NLS-1$ ); kf = KeyFactory.getInstance(ECDH); } final ECNamedCurveSpec params = new ECNamedCurveSpec(curveName.toString(), spec.getCurve(), spec.getG(), spec.getN()); final ECPoint point = ECPointUtil.decodePoint(params.getCurve(), pubKey); final java.security.spec.ECPublicKeySpec pubKeySpec = new java.security.spec.ECPublicKeySpec(point, params); return kf.generatePublic(pubKeySpec); }
/** * <p>Get an EC public key from a byte array suitable for use with ssh operations</p> * * <p>Note: This is not a Bitcoin EC public key</p> * * @param pubKey The ecdsa-sha2-nistp256 EC public key encoded as bytes * * @return An EC public key * * @throws NoSuchAlgorithmException If ECDSA is not available * @throws InvalidKeySpecException If the key is invalid */ public static ECPublicKey getPublicKeyFromBytes(byte[] pubKey) throws NoSuchAlgorithmException, InvalidKeySpecException { ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("P-256"); KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider()); ECNamedCurveSpec params = new ECNamedCurveSpec("P-256", spec.getCurve(), spec.getG(), spec.getN()); ECPoint point = ECPointUtil.decodePoint(params.getCurve(), pubKey); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params); ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec); return pk; }
/** * <p> * Get an EC public key from a byte array suitable for use with ssh * operations</p> * * <p> * Note: This is not a Bitcoin EC public key</p> * * @param pubKey The ecdsa-sha2-nistp256 EC public key encoded as bytes * * @return An EC public key * * @throws NoSuchAlgorithmException If ECDSA is not available * @throws InvalidKeySpecException If the key is invalid */ public static ECPublicKey decodeNISTP256PublicKeyFromBytes(byte[] pubKey) throws NoSuchAlgorithmException, InvalidKeySpecException { ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("P-256"); KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider()); ECNamedCurveSpec params = new ECNamedCurveSpec("P-256", spec.getCurve(), spec.getG(), spec.getN()); ECPoint point = ECPointUtil.decodePoint(params.getCurve(), pubKey); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params); ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec); return pk; }