java.security.spec.ECGenParameterSpec Java Examples

The following examples show how to use java.security.spec.ECGenParameterSpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecurityUtils.java    From RISE-V2G with MIT License 7 votes vote down vote up
/**
 * Returns the ECPublicKey instance from its encoded raw bytes. 
 * The first byte has the fixed value 0x04 indicating the uncompressed form.
 * Therefore, the byte array must be of form: [0x04, x coord of point (32 bytes), y coord of point (32 bytes)]
 * 
 * @param publicKeyBytes The byte array representing the encoded raw bytes of the public key
 * @return The ECPublicKey instance
 */
public static ECPublicKey getPublicKey(byte[] publicKeyBytes) {
	// First we separate x and y of coordinates into separate variables
    byte[] x = new byte[32];
    byte[] y = new byte[32];
    System.arraycopy(publicKeyBytes, 1, x, 0, 32);
    System.arraycopy(publicKeyBytes, 33, y, 0, 32);
    
    try {
		KeyFactory kf = KeyFactory.getInstance("EC");
		
		AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
		parameters.init(new ECGenParameterSpec("secp256r1"));
		ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
		
		ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)), ecParameterSpec);
		ECPublicKey ecPublicKey = (ECPublicKey) kf.generatePublic(ecPublicKeySpec);
		return ecPublicKey;
    } catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get public key from raw bytes", e);
        return null;
	}
}
 
Example #2
Source File: ECKeyTest.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
@Test
public void testFromJsonWebKey() throws Exception {
    ECGenParameterSpec gps = new ECGenParameterSpec(EcKey.P384);
    EC_KEY_GENERATOR.initialize(gps);
    KeyPair keyPair = EC_KEY_GENERATOR.generateKeyPair();
    
    ECPublicKey apub = (ECPublicKey) keyPair.getPublic();
    ECPoint point = apub.getW();
    ECPrivateKey apriv = (ECPrivateKey) keyPair.getPrivate();
    
    JsonWebKey jwk = new JsonWebKey()
            .withKid("kid")
            .withCrv(JsonWebKeyCurveName.P_384)
            .withX(point.getAffineX().toByteArray())
            .withY(point.getAffineY().toByteArray())
            .withD(apriv.getS().toByteArray())
            .withKty(JsonWebKeyType.EC);

    assertTrue(jwk.hasPrivateKey());
    
    EcKey newKey = EcKey.fromJsonWebKey(jwk, true);
    assertEquals("kid", newKey.getKid());
    doSignVerify(newKey, DIGEST_384);
}
 
Example #3
Source File: EllipticCurvesExtension.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isAvailableCurve(int curveId) {
    String oid = idToOidMap.get(curveId);
    if (oid != null) {
        AlgorithmParameters params = null;
        try {
            params = JsseJce.getAlgorithmParameters("EC");
            params.init(new ECGenParameterSpec(oid));
        } catch (Exception e) {
            return false;
        }

        // cache the parameters
        idToParams.put(curveId, params);

        return true;
    }

    return false;
}
 
Example #4
Source File: ECDHKeyExchange.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
ECDHEPossession(NamedGroup namedGroup, SecureRandom random) {
    try {
        KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("EC");
        ECGenParameterSpec params =
                (ECGenParameterSpec)namedGroup.getParameterSpec();
        kpg.initialize(params, random);
        KeyPair kp = kpg.generateKeyPair();
        privateKey = kp.getPrivate();
        publicKey = (ECPublicKey)kp.getPublic();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(
            "Could not generate ECDH keypair", e);
    }

    this.namedGroup = namedGroup;
}
 
Example #5
Source File: EllipticCurvesExtension.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isAvailableCurve(int curveId) {
    String oid = idToOidMap.get(curveId);
    if (oid != null) {
        AlgorithmParameters params = null;
        try {
            params = JsseJce.getAlgorithmParameters("EC");
            params.init(new ECGenParameterSpec(oid));
        } catch (Exception e) {
            return false;
        }

        // cache the parameters
        idToParams.put(curveId, params);

        return true;
    }

    return false;
}
 
Example #6
Source File: KeyPairGenerate.java    From ofdrw with Apache License 2.0 6 votes vote down vote up
@Test
void gen() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    // 获取SM2椭圆曲线的参数
    final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
    // 获取一个椭圆曲线类型的密钥对生成器
    final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
    // 使用SM2参数初始化生成器
    kpg.initialize(sm2Spec);

    // 使用SM2的算法区域初始化密钥生成器
    kpg.initialize(sm2Spec, new SecureRandom());
    // 获取密钥对
    KeyPair keyPair = kpg.generateKeyPair();

    PublicKey pubKey = keyPair.getPublic();
    String pubKEnc = Base64.toBase64String(pubKey.getEncoded());
    System.out.println(">> Pub Key: " + pubKEnc);

    PrivateKey priKey = keyPair.getPrivate();
    String priKEnc = Base64.toBase64String(priKey.getEncoded());
    System.out.println(">> Pri Key: " + priKEnc);
}
 
Example #7
Source File: CredentialSafe.java    From android-webauthn-authenticator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Generate a new ES256 keypair (COSE algorithm -7, ECDSA + SHA-256 over the NIST P-256 curve).
 *
 * @param alias The alias used to identify this keypair in the keystore. Needed to use key
 *              in the future.
 * @return The KeyPair object representing the newly generated keypair.
 * @throws VirgilException
 */
private KeyPair generateNewES256KeyPair(String alias) throws VirgilException {
    KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN)
            .setAlgorithmParameterSpec(new ECGenParameterSpec(CURVE_NAME))
            .setDigests(KeyProperties.DIGEST_SHA256)
            .setUserAuthenticationRequired(this.authenticationRequired) // fingerprint or similar
            .setUserConfirmationRequired(false) // TODO: Decide if we support Android Trusted Confirmations
            .setInvalidatedByBiometricEnrollment(false)
            .setIsStrongBoxBacked(this.strongboxRequired)
            .build();
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, KEYSTORE_TYPE);
        keyPairGenerator.initialize(spec);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return keyPair;
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        throw new VirgilException("couldn't generate key pair: " + e.toString());
    }
}
 
Example #8
Source File: SupportedGroupsExtension.java    From openjsse with GNU General Public License v2.0 6 votes vote down vote up
static ECGenParameterSpec getECGenParamSpec(NamedGroup namedGroup) {
    if (namedGroup.type != NamedGroupType.NAMED_GROUP_ECDHE) {
        throw new RuntimeException(
                "Not a named EC group: " + namedGroup);
    }

    AlgorithmParameters params = namedGroupParams.get(namedGroup);
    if (params == null) {
        throw new RuntimeException(
                "Not a supported EC named group: " + namedGroup);
    }

    try {
        return params.getParameterSpec(ECGenParameterSpec.class);
    } catch (InvalidParameterSpecException ipse) {
        // should be unlikely
        return new ECGenParameterSpec(namedGroup.oid);
    }
}
 
Example #9
Source File: ECKeyPairGenerator.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
        throws InvalidAlgorithmParameterException {

    if (params instanceof ECParameterSpec) {
        this.params = ECUtil.getECParameterSpec(null,
                                                (ECParameterSpec)params);
        if (this.params == null) {
            throw new InvalidAlgorithmParameterException(
                "Unsupported curve: " + params);
        }
    } else if (params instanceof ECGenParameterSpec) {
        String name = ((ECGenParameterSpec)params).getName();
        this.params = ECUtil.getECParameterSpec(null, name);
        if (this.params == null) {
            throw new InvalidAlgorithmParameterException(
                "Unknown curve name: " + name);
        }
    } else {
        throw new InvalidAlgorithmParameterException(
            "ECParameterSpec or ECGenParameterSpec required for EC");
    }
    this.keySize =
        ((ECParameterSpec)this.params).getCurve().getField().getFieldSize();
    this.random = random;
}
 
Example #10
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public void generateCA() throws NoSuchAlgorithmException, IOException, OperatorCreationException, InvalidAlgorithmParameterException {
    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp384k1");
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(ecGenSpec, SecurityHelper.newRandom());
    KeyPair pair = generator.generateKeyPair();
    LocalDateTime startDate = LocalDate.now().atStartOfDay();

    X500NameBuilder subject = new X500NameBuilder();
    subject.addRDN(BCStyle.CN, orgName.concat(" CA"));
    subject.addRDN(BCStyle.O, orgName);

    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(
            subject.build(),
            new BigInteger("0"),
            Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),
            Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()),
            new X500Name("CN=ca"),
            SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()));
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA");
    ContentSigner signer = csBuilder.build(pair.getPrivate());
    ca = builder.build(signer);
    caKey = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
}
 
Example #11
Source File: EciesEncryptionTest.java    From protect with MIT License 6 votes vote down vote up
@Test
public void testEncryptDecrypt() throws Exception {

	final String name = "secp256r1";

	// NOTE just "EC" also seems to work here
	final KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDH", BouncyCastleProvider.PROVIDER_NAME);
	kpg.initialize(new ECGenParameterSpec(name));

	// Key pair to store public and private key
	final KeyPair keyPair = kpg.generateKeyPair();

	// Message to encrypt
	byte[] message = "hello".getBytes(StandardCharsets.UTF_8);

	// Encrypt
	final BigInteger r = EciesEncryption.generateR();
	byte[] encrypted = EciesEncryption.encrypt(message, r, keyPair.getPublic());

	// Decrypt
	byte[] decrypted = EciesEncryption.decrypt(encrypted, keyPair.getPrivate());
	System.out.println("Decrypted message: " + new String(decrypted));

	Assert.assertArrayEquals(message, decrypted);

}
 
Example #12
Source File: KeyUtil.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
/**
 * Get the EC curve parameters used by the secp256k1 keys used for HD seeds
 */
public static ECParameterSpec getECHDSpec()
{
  try
  {
    ECGenParameterSpec spec = new ECGenParameterSpec("secp256k1");
    KeyPairGenerator key_gen = KeyPairGenerator.getInstance("ECDSA", Globals.getCryptoProviderName());
    key_gen.initialize(spec);

    KeyPair pair = key_gen.genKeyPair();
    ECPrivateKey priv = (ECPrivateKey)pair.getPrivate();

    return priv.getParams();
  }
  catch(Exception e)
  {
    throw new RuntimeException(e);
  }

}
 
Example #13
Source File: KeyUtil.java    From snowblossom with Apache License 2.0 6 votes vote down vote up
public static WalletKeyPair generateWalletDSTU4145Key(int curve)
{
  try
  {
    ECGenParameterSpec spec = new ECGenParameterSpec("1.2.804.2.1.1.1.1.3.1.1.2." + curve);

    KeyPairGenerator key_gen = KeyPairGenerator.getInstance("DSTU4145", Globals.getCryptoProviderName());

    key_gen.initialize(spec);
    KeyPair key_pair = key_gen.genKeyPair();

    WalletKeyPair wkp = WalletKeyPair.newBuilder()
      .setPublicKey(ByteString.copyFrom(key_pair.getPublic().getEncoded()))
      .setPrivateKey(ByteString.copyFrom(key_pair.getPrivate().getEncoded()))
      .setSignatureType(SignatureUtil.SIG_TYPE_DSTU4145)
      .build();
    return wkp;
  }
  catch(Exception e)
  {
    throw new RuntimeException(e);
  }
}
 
Example #14
Source File: MainActivity.java    From android-biometricprompt with Apache License 2.0 6 votes vote down vote up
private KeyPair generateKeyPair(String keyName, boolean invalidatedByBiometricEnrollment) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");

    KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(keyName,
            KeyProperties.PURPOSE_SIGN)
            .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
            .setDigests(KeyProperties.DIGEST_SHA256,
                    KeyProperties.DIGEST_SHA384,
                    KeyProperties.DIGEST_SHA512)
            // Require the user to authenticate with a biometric to authorize every use of the key
            .setUserAuthenticationRequired(true);

    // Generated keys will be invalidated if the biometric templates are added more to user device
    if (Build.VERSION.SDK_INT >= 24) {
        builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);
    }

    keyPairGenerator.initialize(builder.build());

    return keyPairGenerator.generateKeyPair();
}
 
Example #15
Source File: EllipticCurvesExtension.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isAvailableCurve(int curveId) {
    String oid = idToOidMap.get(curveId);
    if (oid != null) {
        AlgorithmParameters params = null;
        try {
            params = JsseJce.getAlgorithmParameters("EC");
            params.init(new ECGenParameterSpec(oid));
        } catch (Exception e) {
            return false;
        }

        // cache the parameters
        idToParams.put(curveId, params);

        return true;
    }

    return false;
}
 
Example #16
Source File: ECKeyTest.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
@Test
public void testToJsonWebKey() throws Exception {
	ECGenParameterSpec gps = new ECGenParameterSpec(EcKey.P521);
	EC_KEY_GENERATOR.initialize(gps);
	KeyPair keyPair = EC_KEY_GENERATOR.generateKeyPair();
	
	ECPublicKey apub = (ECPublicKey) keyPair.getPublic();
	ECPoint point = apub.getW();
	ECPrivateKey apriv = (ECPrivateKey) keyPair.getPrivate();
	
	JsonWebKey jwk = new JsonWebKey()
			.withKid("kid")
			.withCrv(JsonWebKeyCurveName.P_521)
			.withX(point.getAffineX().toByteArray())
			.withY(point.getAffineY().toByteArray())
			.withD(apriv.getS().toByteArray())
			.withKty(JsonWebKeyType.EC);
	
	EcKey newKey = new EcKey("kid", keyPair);
	
	JsonWebKey newJwk = newKey.toJsonWebKey();
	//set missing parameters
	newJwk.withKid("kid");
	
	assertEquals(jwk, newJwk);	
}
 
Example #17
Source File: SecurityUtils.java    From RISE-V2G with MIT License 6 votes vote down vote up
/**
 * Returns the ECPrivateKey instance from its raw bytes. Note that you must provide the "s" value of the 
 * private key, not e.g. the byte array from reading a PKCS#8 key file.
 * 
 * @param privateKeyBytes The byte array (the "s" value) of the private key
 * @return The ECPrivateKey instance
 */
public static ECPrivateKey getPrivateKey(byte[] privateKeyBytes) {
	try {
		AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
		parameters.init(new ECGenParameterSpec("secp256r1"));
		
		ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
		ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(privateKeyBytes), ecParameterSpec);
		
		ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(ecPrivateKeySpec);

		return privateKey;
	} catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidParameterSpecException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get private key from raw bytes", e);
		return null;
	}
}
 
Example #18
Source File: EllipticCurvesExtension.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isAvailableCurve(int curveId) {
    String oid = idToOidMap.get(curveId);
    if (oid != null) {
        AlgorithmParameters params = null;
        try {
            params = JsseJce.getAlgorithmParameters("EC");
            params.init(new ECGenParameterSpec(oid));
        } catch (Exception e) {
            return false;
        }

        // cache the parameters
        idToParams.put(curveId, params);

        return true;
    }

    return false;
}
 
Example #19
Source File: ECKeyPairGenerator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
        throws InvalidAlgorithmParameterException {

    if (params instanceof ECParameterSpec) {
        this.params = ECUtil.getECParameterSpec(null,
                                                (ECParameterSpec)params);
        if (this.params == null) {
            throw new InvalidAlgorithmParameterException(
                "Unsupported curve: " + params);
        }
    } else if (params instanceof ECGenParameterSpec) {
        String name = ((ECGenParameterSpec)params).getName();
        this.params = ECUtil.getECParameterSpec(null, name);
        if (this.params == null) {
            throw new InvalidAlgorithmParameterException(
                "Unknown curve name: " + name);
        }
    } else {
        throw new InvalidAlgorithmParameterException(
            "ECParameterSpec or ECGenParameterSpec required for EC");
    }
    this.keySize =
        ((ECParameterSpec)this.params).getCurve().getField().getFieldSize();
    this.random = random;
}
 
Example #20
Source File: EllipticCurvesExtension.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isAvailableCurve(int curveId) {
    String oid = idToOidMap.get(curveId);
    if (oid != null) {
        AlgorithmParameters params = null;
        try {
            params = JsseJce.getAlgorithmParameters("EC");
            params.init(new ECGenParameterSpec(oid));
        } catch (Exception e) {
            return false;
        }

        // cache the parameters
        idToParams.put(curveId, params);

        return true;
    }

    return false;
}
 
Example #21
Source File: ECKeyPairGenerator.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
        throws InvalidAlgorithmParameterException {

    if (params instanceof ECParameterSpec) {
        this.params = ECUtil.getECParameterSpec(null,
                                                (ECParameterSpec)params);
        if (this.params == null) {
            throw new InvalidAlgorithmParameterException(
                "Unsupported curve: " + params);
        }
    } else if (params instanceof ECGenParameterSpec) {
        String name = ((ECGenParameterSpec)params).getName();
        this.params = ECUtil.getECParameterSpec(null, name);
        if (this.params == null) {
            throw new InvalidAlgorithmParameterException(
                "Unknown curve name: " + name);
        }
    } else {
        throw new InvalidAlgorithmParameterException(
            "ECParameterSpec or ECGenParameterSpec required for EC");
    }
    this.keySize =
        ((ECParameterSpec)this.params).getCurve().getField().getFieldSize();
    this.random = random;
}
 
Example #22
Source File: SupportedEllipticCurvesExtension.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static boolean isAvailableCurve(int curveId) {
    String oid = idToOidMap.get(curveId);
    if (oid != null) {
        AlgorithmParameters params = null;
        try {
            params = JsseJce.getAlgorithmParameters("EC");
            params.init(new ECGenParameterSpec(oid));
        } catch (Exception e) {
            return false;
        }

        // cache the parameters
        idToParams.put(curveId, params);

        return true;
    }

    return false;
}
 
Example #23
Source File: ECKeyPairGenerator.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random)
        throws InvalidAlgorithmParameterException {

    if (params instanceof ECParameterSpec) {
        this.params = ECUtil.getECParameterSpec(null,
                                                (ECParameterSpec)params);
        if (this.params == null) {
            throw new InvalidAlgorithmParameterException(
                "Unsupported curve: " + params);
        }
    } else if (params instanceof ECGenParameterSpec) {
        String name = ((ECGenParameterSpec)params).getName();
        this.params = ECUtil.getECParameterSpec(null, name);
        if (this.params == null) {
            throw new InvalidAlgorithmParameterException(
                "Unknown curve name: " + name);
        }
    } else {
        throw new InvalidAlgorithmParameterException(
            "ECParameterSpec or ECGenParameterSpec required for EC");
    }
    this.keySize =
        ((ECParameterSpec)this.params).getCurve().getField().getFieldSize();
    this.random = random;
}
 
Example #24
Source File: EcKey.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
/**
 * Constructor.
 * 
 * Generates a new EcKey with the given curve and kid.
 * @param kid
 * @param curve
 * @param provider Java security provider
 * @throws InvalidAlgorithmParameterException
 * @throws NoSuchAlgorithmException
 */
public EcKey(String kid, JsonWebKeyCurveName curve, Provider provider) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {
	_kid = kid;
	_provider = provider;
	_curve = curve;
	
	_signatureAlgorithm = CURVE_TO_SIGNATURE.get(curve);
	if (_signatureAlgorithm == null) {
		throw new NoSuchAlgorithmException("Curve not supported.");
	}
	
	final KeyPairGenerator generator = KeyPairGenerator.getInstance("EC", provider);
	ECGenParameterSpec gps = new ECGenParameterSpec(CURVE_TO_SPEC_NAME.get(curve));

	generator.initialize(gps);
	_keyPair = generator.generateKeyPair();
	
}
 
Example #25
Source File: ECKeyTest.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void testFromJsonWebKeyPublicOnly() throws Exception {
	ECGenParameterSpec gps = new ECGenParameterSpec(EcKey.P256);
	EC_KEY_GENERATOR.initialize(gps);
	KeyPair keyPair = EC_KEY_GENERATOR.generateKeyPair();
	
	ECPublicKey apub = (ECPublicKey) keyPair.getPublic();
	ECPoint point = apub.getW();
	
	JsonWebKey jwk = new JsonWebKey()
			.withKid("kid")
			.withCrv(JsonWebKeyCurveName.P_256)
			.withX(point.getAffineX().toByteArray())
			.withY(point.getAffineY().toByteArray())
			.withKty(JsonWebKeyType.EC);

	assertFalse(jwk.hasPrivateKey());
	
	EcKey newKey = EcKey.fromJsonWebKey(jwk, false);
	assertEquals("kid", newKey.getKid());
	doSignVerify(newKey, DIGEST_256);
}
 
Example #26
Source File: cryptoCommon.java    From fido2 with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *
 * @param publickeybytes
 * @return
 * @throws java.security.spec.InvalidKeySpecException
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.NoSuchProviderException
 * @throws java.security.spec.InvalidParameterSpecException
 */
public static ECPublicKey getUserECPublicKey(byte[] publickeybytes) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException, InvalidParameterSpecException {

    //append the sign byte to the arrays
    byte[] processedXData = new byte[EC_POINTSIZE];
    byte[] processedYData = new byte[EC_POINTSIZE];
    System.arraycopy(publickeybytes, 1, processedXData, 0, EC_POINTSIZE);
    System.arraycopy(publickeybytes, EC_POINTSIZE + 1, processedYData, 0, EC_POINTSIZE);

    ECPoint pubPoint = new ECPoint(new BigInteger(1, processedXData), new BigInteger(1, processedYData));
    AlgorithmParameters params = AlgorithmParameters.getInstance("EC", BC_FIPS_PROVIDER);
    params.init(new ECGenParameterSpec("prime256v1"));
    ECParameterSpec ecParameters = params.getParameterSpec(ECParameterSpec.class);
    ECPublicKeySpec pubECSpec = new ECPublicKeySpec(pubPoint, ecParameters);
    return (ECPublicKey) KeyFactory.getInstance("EC", BC_FIPS_PROVIDER).generatePublic(pubECSpec);
}
 
Example #27
Source File: EllipticCurvesExtension.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static ECGenParameterSpec getECGenParamSpec(int index) {
    AlgorithmParameters params = idToParams.get(index);
    try {
        return params.getParameterSpec(ECGenParameterSpec.class);
    } catch (InvalidParameterSpecException ipse) {
        // should be unlikely
        String curveOid = getCurveOid(index);
        return new ECGenParameterSpec(curveOid);
    }
}
 
Example #28
Source File: LoginEncryptionUtils.java    From Geyser with MIT License 5 votes vote down vote up
private static void startEncryptionHandshake(GeyserSession session, PublicKey key) throws Exception {
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(new ECGenParameterSpec("secp384r1"));
    KeyPair serverKeyPair = generator.generateKeyPair();

    byte[] token = EncryptionUtils.generateRandomToken();
    SecretKey encryptionKey = EncryptionUtils.getSecretKey(serverKeyPair.getPrivate(), key, token);
    session.getUpstream().getSession().enableEncryption(encryptionKey);

    ServerToClientHandshakePacket packet = new ServerToClientHandshakePacket();
    packet.setJwt(EncryptionUtils.createHandshakeJwt(serverKeyPair, token).serialize());
    session.sendUpstreamPacketImmediately(packet);
}
 
Example #29
Source File: Crypto.java    From webauthndemo with Apache License 2.0 5 votes vote down vote up
public static KeyPair generateKeyPair() {
  try {
    ECGenParameterSpec spec = new ECGenParameterSpec("secp256r1");
    KeyPairGenerator gen = KeyPairGenerator.getInstance("EC");
    gen.initialize(spec);
    KeyPair keyPair = gen.generateKeyPair();
    return keyPair;
  } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
    throw new RuntimeException(e);
  }
}
 
Example #30
Source File: JsonWebKey.java    From swim with Apache License 2.0 5 votes vote down vote up
private static ECParameterSpec createECParameterSpec(String stdName) {
  try {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
    final ECGenParameterSpec parameterSpec = new ECGenParameterSpec(stdName);
    keyPairGenerator.initialize(parameterSpec);
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();
    final ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();
    return publicKey.getParams();
  } catch (GeneralSecurityException cause) {
    throw new RuntimeException(cause);
  }
}