Java 类java.security.spec.ECGenParameterSpec 实例源码

项目:wycheproof    文件:EciesTest.java   
/**
 * Check that key agreement using ECIES works. This example does not specify an IESParametersSpec.
 * BouncyCastle v.1.52 uses the following algorithms: KDF2 with SHA1 for the key derivation
 * AES-CBC with PKCS #5 padding. HMAC-SHA1 with a 20 byte digest. The AES and the HMAC key are
 * both 128 bits.
 */
@SuppressWarnings("InsecureCryptoUsage")
@Test
public void testEciesBasic() throws Exception {
  ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
  KeyPairGenerator kf = KeyPairGenerator.getInstance("EC");
  kf.initialize(ecSpec);
  KeyPair keyPair = kf.generateKeyPair();
  PrivateKey priv = keyPair.getPrivate();
  PublicKey pub = keyPair.getPublic();
  byte[] message = "Hello".getBytes("UTF-8");
  Cipher ecies = Cipher.getInstance("ECIESwithAES-CBC");
  ecies.init(Cipher.ENCRYPT_MODE, pub);
  byte[] ciphertext = ecies.doFinal(message);
  System.out.println("testEciesBasic:" + TestUtil.bytesToHex(ciphertext));
  ecies.init(Cipher.DECRYPT_MODE, priv, ecies.getParameters());
  byte[] decrypted = ecies.doFinal(ciphertext);
  assertEquals(TestUtil.bytesToHex(message), TestUtil.bytesToHex(decrypted));
}
项目:BedrockProxy    文件:ServerHandshakePacket.java   
public ServerHandshakePacket(BedrockPlayer p) {
    super(PacketRegistry.NetworkType.SERVER_TO_CLIENT_HANDSHAKE_PACKET);

    try {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
        generator.initialize(new ECGenParameterSpec("secp384r1"));
        KeyPair serverKeyPair = generator.generateKeyPair();

        byte[] token = Security.generateRandomToken();
        byte[] serverKey = Security.getServerKey(serverKeyPair, token);
        p.enableEncryption(serverKey);

        publicKey = serverKeyPair;
        serverToken = token;
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | InvalidKeyException e) {
        e.printStackTrace();
    }
}
项目:ipack    文件:KeyPairGeneratorSpi.java   
public void initialize(
    int strength,
    SecureRandom random)
{
    this.random = random;

    if (ecParams != null)
    {
        try
        {
            initialize((ECGenParameterSpec)ecParams, random);
        }
        catch (InvalidAlgorithmParameterException e)
        {
            throw new InvalidParameterException("key size not configurable.");
        }
    }
    else
    {
        throw new InvalidParameterException("unknown key size.");
    }
}
项目:ipack    文件:KeyPairGeneratorSpi.java   
public void initialize(
    int             strength,
    SecureRandom    random)
{
    this.strength = strength;
    this.random = random;
    ECGenParameterSpec ecParams = (ECGenParameterSpec)ecParameters.get(Integers.valueOf(strength));

    if (ecParams != null)
    {
        try
        {
            initialize(ecParams, random);
        }
        catch (InvalidAlgorithmParameterException e)
        {
            throw new InvalidParameterException("key size not configurable.");
        }
    }
    else
    {
        throw new InvalidParameterException("unknown key size.");
    }
}
项目:ipack    文件:KeyPairGeneratorSpi.java   
public void initialize(
    int strength,
    SecureRandom random)
{
    this.strength = strength;
    this.random = random;

    if (ecParams != null)
    {
        try
        {
            initialize((ECGenParameterSpec)ecParams, random);
        }
        catch (InvalidAlgorithmParameterException e)
        {
            throw new InvalidParameterException("key size not configurable.");
        }
    }
    else
    {
        throw new InvalidParameterException("unknown key size.");
    }
}
项目:RISE-V2G    文件:SecurityUtils.java   
/**
 * 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;
    }
}
项目:RISE-V2G    文件:SecurityUtils.java   
/**
 * 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;
    }
}
项目:OpenJSharp    文件:ECKeyPairGenerator.java   
@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;
}
项目:wolfcrypt-jni    文件:EccTest.java   
@Test
public void getEccCurveNameFromSpec()
    throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {

    /* generate key pair */
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
    ECGenParameterSpec genSpec = new ECGenParameterSpec("secp256r1");
    kpg.initialize(genSpec);

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

    ECParameterSpec spec = priv.getParams();

    String curveName = Ecc.getCurveName(spec);

    assertEquals(curveName, "SECP256R1");
}
项目:wolfcrypt-jni    文件:WolfCryptKeyPairGeneratorTest.java   
@Test
public void testKeyPairGeneratorEccKeyGenAllCurves()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           InvalidAlgorithmParameterException {

    /* try generating keys for all supported curves */
    for (int i = 0; i < enabledCurves.size(); i++) {

        KeyPairGenerator kpg =
            KeyPairGenerator.getInstance("EC", "wolfJCE");

        ECGenParameterSpec ecSpec =
            new ECGenParameterSpec(enabledCurves.get(i));
        kpg.initialize(ecSpec);

        KeyPair kp = kpg.generateKeyPair();
    }
}
项目:wolfcrypt-jni    文件:WolfCryptKeyPairGeneratorTest.java   
@Test
public void testKeyPairGeneratorEccMultipleInits()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           InvalidAlgorithmParameterException {

    if (enabledCurves.size() > 0) {

        KeyPairGenerator kpg =
            KeyPairGenerator.getInstance("EC", "wolfJCE");

        ECGenParameterSpec ecSpec =
            new ECGenParameterSpec(enabledCurves.get(0));

        kpg.initialize(ecSpec);
        kpg.initialize(ecSpec);
    }
}
项目:wolfcrypt-jni    文件:WolfCryptKeyPairGeneratorTest.java   
@Test
public void testKeyPairGeneratorEccMultipleKeyGen()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           InvalidAlgorithmParameterException {

    if (enabledCurves.size() > 0) {

        KeyPairGenerator kpg =
            KeyPairGenerator.getInstance("EC", "wolfJCE");

        ECGenParameterSpec ecSpec =
            new ECGenParameterSpec(enabledCurves.get(0));
        kpg.initialize(ecSpec);

        KeyPair kp1 = kpg.generateKeyPair();
        KeyPair kp2 = kpg.generateKeyPair();
    }
}
项目:wolfcrypt-jni    文件:WolfCryptKeyPairGeneratorTest.java   
@Test
public void testKeyPairGeneratorEccNewKeyFromExisting()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           InvalidAlgorithmParameterException, InvalidKeySpecException {

    if (enabledCurves.size() > 0) {

        KeyPairGenerator kpg =
            KeyPairGenerator.getInstance("EC", "wolfJCE");

        ECGenParameterSpec ecSpec =
            new ECGenParameterSpec(enabledCurves.get(0));
        kpg.initialize(ecSpec);

        KeyPair kp = kpg.generateKeyPair();

        KeyFactory kf = KeyFactory.getInstance("EC");
        PublicKey pub = kf.generatePublic(new X509EncodedKeySpec(
                    kp.getPublic().getEncoded()));
        PrivateKey priv = kf.generatePrivate(new PKCS8EncodedKeySpec(
                    kp.getPrivate().getEncoded()));
    }
}
项目:jdk8u-jdk    文件:SupportedEllipticCurvesExtension.java   
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;
}
项目:jdk8u-jdk    文件:ECKeyPairGenerator.java   
@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;
}
项目:mi-firma-android    文件:JseCryptoHelper.java   
@Override
public KeyPair generateEcKeyPair(final EcCurve curveName) throws NoSuchAlgorithmException,
                                                                 InvalidAlgorithmParameterException {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
    KeyPairGenerator kpg;
    try {
        kpg = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME); //$NON-NLS-1$
    }
    catch (final Exception e) {
        Logger.getLogger("es.gob.jmulticard").warning( //$NON-NLS-1$
            "No se ha podido obtener un generador de pares de claves de curva eliptica con SpongyCastle, se usara el generador por defecto: " + e //$NON-NLS-1$
        );
        kpg = KeyPairGenerator.getInstance("EC"); //$NON-NLS-1$
    }

    Logger.getLogger("es.gob.jmulticard").info( //$NON-NLS-1$
        "Seleccionado el siguiente generador de claves de curva eliptica: " + kpg.getClass().getName() //$NON-NLS-1$
    );

    final AlgorithmParameterSpec parameterSpec = new ECGenParameterSpec(curveName.toString());
    kpg.initialize(parameterSpec);
    return kpg.generateKeyPair();
}
项目:openjdk9    文件:ECKeyPairGenerator.java   
@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;
}
项目:ReCRED_FIDO_UAF_OIDC    文件:AndroidKeyStoreController.java   
public KeyPair generateKeyPair(String keyAlias)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException
{
    if (!allGood)
        return null;

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");

    keyPairGenerator.initialize(
            new KeyGenParameterSpec.Builder(
                    keyAlias,
                    KeyProperties.PURPOSE_SIGN)
                    .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
                    .setDigests(KeyProperties.DIGEST_SHA256)
                    .setUserAuthenticationRequired(true)
                    .setUserAuthenticationValidityDurationSeconds(5 * 60)
                    .build());

    return keyPairGenerator.generateKeyPair();
}
项目:coinblesk-client-gui    文件:DHKeyExchangeHandler.java   
public DHKeyExchangeHandler(InputStream inputStream, OutputStream outputStream, OnResultListener<SecretKeySpec> resultListener) {
    super(inputStream,outputStream);
    this.resultListener = resultListener;

    Log.d(TAG,"starting exchange");
    try {
        final ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec("secp224k1");
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDH", "SC");
        keyPairGenerator.initialize(ecGenParameterSpec);
        keyPair = keyPairGenerator.generateKeyPair();
    } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException | NoSuchProviderException e) {
        Log.w(TAG, "Could not initialize DHKeyExchange: ", e);
        // TODO: we should not catch the exception here because we cannot continue with an error and we cannot know what went wrong.
        // FIXME: catch outside and abort.
    }
}
项目:wycheproof    文件:EciesTest.java   
/**
 * This test tries to detect ECIES implementations using ECB. This is insecure and also violates
 * the claims of ECIES, since ECIES is secure agains adaptive chosen-ciphertext attacks.
 */
@SuppressWarnings("InsecureCryptoUsage")
public void testNotEcb(String algorithm) throws Exception {
  Cipher ecies;
  try {
    ecies = Cipher.getInstance(algorithm);
  } catch (NoSuchAlgorithmException ex) {
    // This test is called with short algorithm names such as just "ECIES".
    // Requiring full names is typically a good practice. Hence it is OK
    // to not assigning default algorithms.
    System.out.println("No implementation for:" + algorithm);
    return;
  }
  ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
  KeyPairGenerator kf = KeyPairGenerator.getInstance("EC");
  kf.initialize(ecSpec);
  KeyPair keyPair = kf.generateKeyPair();
  PublicKey pub = keyPair.getPublic();
  byte[] message = new byte[512];
  ecies.init(Cipher.ENCRYPT_MODE, pub);
  byte[] ciphertext = ecies.doFinal(message);
  String block1 = TestUtil.bytesToHex(Arrays.copyOfRange(ciphertext, 241, 257));
  String block2 = TestUtil.bytesToHex(Arrays.copyOfRange(ciphertext, 257, 273));
  assertTrue("Ciphertext repeats:" + TestUtil.bytesToHex(ciphertext), !block1.equals(block2));
}
项目:wycheproof    文件:EcdhTest.java   
/** Checks that key agreement using ECDH works. */
@Test
public void testBasic() throws Exception {
  KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
  ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
  keyGen.initialize(ecSpec);
  KeyPair keyPairA = keyGen.generateKeyPair();
  KeyPair keyPairB = keyGen.generateKeyPair();

  KeyAgreement kaA = KeyAgreement.getInstance("ECDH");
  KeyAgreement kaB = KeyAgreement.getInstance("ECDH");
  kaA.init(keyPairA.getPrivate());
  kaB.init(keyPairB.getPrivate());
  kaA.doPhase(keyPairB.getPublic(), true);
  kaB.doPhase(keyPairA.getPublic(), true);
  byte[] kAB = kaA.generateSecret();
  byte[] kBA = kaB.generateSecret();
  assertEquals(TestUtil.bytesToHex(kAB), TestUtil.bytesToHex(kBA));
}
项目:jdk8u_jdk    文件:SupportedEllipticCurvesExtension.java   
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;
}
项目:jdk8u_jdk    文件:ECKeyPairGenerator.java   
@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;
}
项目:lookaside_java-1.8.0-openjdk    文件:SupportedEllipticCurvesExtension.java   
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;
}
项目:lookaside_java-1.8.0-openjdk    文件:ECKeyPairGenerator.java   
@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;
}
项目:Jose4j    文件:EllipticCurvesTest.java   
@Test
public void testNames() throws Exception
{
    // Test my names and the EllipticCurves class against the 'standard name' which I didn't know about
    // but someone pointed me to "Implementing ECC with Java Standard Edition 7" at http://www.academicpub.org/PaperInfo.aspx?PaperID=14496
    // which educated me a bit
    Map<String,String> names = new LinkedHashMap<>();
    names.put("secp256r1", EllipticCurves.P_256);
    names.put("secp384r1", EllipticCurves.P_384);
    names.put("secp521r1", EllipticCurves.P_521);

    for (Map.Entry<String,String> e : names.entrySet())
    {
        ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec(e.getKey());
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
        kpg.initialize(ecGenParameterSpec);
        KeyPair keyPair = kpg.generateKeyPair();
        ECPublicKey ecpub = (ECPublicKey) keyPair.getPublic();
        ECParameterSpec params = ecpub.getParams();
        Assert.assertEquals(e.getValue(), EllipticCurves.getName(params.getCurve()));
    }
}
项目:voxelwind    文件:InitialNetworkPacketHandler.java   
private void startEncryptionHandshake(PublicKey key) throws Exception {
    if (!CAN_USE_ENCRYPTION) {
        // Can't use encryption.
        initializePlayerSession();
        return;
    }

    // Generate a fresh key for each session
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(new ECGenParameterSpec("secp384r1"));
    KeyPair serverKeyPair = generator.generateKeyPair();

    // Enable encryption server-side
    byte[] token = EncryptionUtil.generateRandomToken();
    byte[] serverKey = EncryptionUtil.getServerKey(serverKeyPair, key, token);
    session.enableEncryption(serverKey);
    // Now send the packet to enable encryption on the client
    session.sendImmediatePackage(EncryptionUtil.createHandshakePacket(serverKeyPair, token));
}
项目:Aki-SSL    文件:KeyPairGeneratorSpi.java   
public void initialize(
    int strength,
    SecureRandom random)
{
    this.random = random;

    if (ecParams != null)
    {
        try
        {
            initialize((ECGenParameterSpec)ecParams, random);
        }
        catch (InvalidAlgorithmParameterException e)
        {
            throw new InvalidParameterException("key size not configurable.");
        }
    }
    else
    {
        throw new InvalidParameterException("unknown key size.");
    }
}
项目:Aki-SSL    文件:AlgorithmParametersSpi.java   
@Override
protected void engineInit(AlgorithmParameterSpec algorithmParameterSpec)
    throws InvalidParameterSpecException
{
    if (algorithmParameterSpec instanceof ECGenParameterSpec)
    {
        ECGenParameterSpec ecGenParameterSpec = (ECGenParameterSpec)algorithmParameterSpec;
        X9ECParameters params = ECUtils.getDomainParametersFromGenSpec(ecGenParameterSpec);

        if (params == null)
        {
            throw new InvalidParameterSpecException("EC curve name not recognized: " + ecGenParameterSpec.getName());
        }
        curveName = ecGenParameterSpec.getName();
        ecParameterSpec = EC5Util.convertToSpec(params);
    }
    else if (algorithmParameterSpec instanceof ECParameterSpec)
    {
        curveName = null;
        ecParameterSpec = (ECParameterSpec)algorithmParameterSpec;
    }
    else
    {
        throw new InvalidParameterSpecException("AlgorithmParameterSpec class not recognized: " + algorithmParameterSpec.getClass().getName());
    }
}
项目:Aki-SSL    文件:KeyPairGeneratorSpi.java   
public void initialize(
    int             strength,
    SecureRandom    random)
{
    this.strength = strength;
    this.random = random;

    ECGenParameterSpec ecParams = (ECGenParameterSpec)ecParameters.get(Integers.valueOf(strength));
    if (ecParams == null)
    {
        throw new InvalidParameterException("unknown key size.");
    }

    try
    {
        initialize(ecParams, random);
    }
    catch (InvalidAlgorithmParameterException e)
    {
        throw new InvalidParameterException("key size not configurable.");
    }
}
项目:Aki-SSL    文件:KeyPairGeneratorSpi.java   
public void initialize(
    int strength,
    SecureRandom random)
{
    this.strength = strength;
    this.random = random;

    if (ecParams != null)
    {
        try
        {
            initialize((ECGenParameterSpec)ecParams, random);
        }
        catch (InvalidAlgorithmParameterException e)
        {
            throw new InvalidParameterException("key size not configurable.");
        }
    }
    else
    {
        throw new InvalidParameterException("unknown key size.");
    }
}
项目:SI    文件:SecurityInfoSerDesTest.java   
@Test
public void security_info_rpk_ser_des_then_equal() throws Exception {
    byte[] publicX = Hex
            .decodeHex("89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5".toCharArray());
    byte[] publicY = Hex
            .decodeHex("cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68".toCharArray());
    // Get Elliptic Curve Parameter spec for secp256r1
    AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
    algoParameters.init(new ECGenParameterSpec("secp256r1"));
    ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

    // Create key specs
    KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)),
            parameterSpec);

    SecurityInfo si = SecurityInfo.newRawPublicKeyInfo("myendpoint",
            KeyFactory.getInstance("EC").generatePublic(publicKeySpec));

    byte[] data = SecurityInfoSerDes.serialize(si);

    assertEquals(
            "{\"ep\":\"myendpoint\",\"rpk\":{\"x\":\"89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5\",\"y\":\"cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68\",\"params\":\"secp256r1\"}}",
            new String(data));
    System.err.println(new String(SecurityInfoSerDes.serialize(SecurityInfoSerDes.deserialize(data))));
    assertEquals(si, SecurityInfoSerDes.deserialize(data));
}
项目:leshan    文件:SecurityInfoSerDesTest.java   
@Test
public void security_info_rpk_ser_des_then_equal() throws Exception {
    byte[] publicX = Hex
            .decodeHex("89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5".toCharArray());
    byte[] publicY = Hex
            .decodeHex("cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68".toCharArray());
    // Get Elliptic Curve Parameter spec for secp256r1
    AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
    algoParameters.init(new ECGenParameterSpec("secp256r1"));
    ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

    // Create key specs
    KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)),
            parameterSpec);

    SecurityInfo si = SecurityInfo.newRawPublicKeyInfo("myendpoint",
            KeyFactory.getInstance("EC").generatePublic(publicKeySpec));

    byte[] data = SecurityInfoSerDes.serialize(si);

    assertEquals(
            "{\"ep\":\"myendpoint\",\"rpk\":{\"x\":\"89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5\",\"y\":\"cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68\",\"params\":\"secp256r1\"}}",
            new String(data));
    System.err.println(new String(SecurityInfoSerDes.serialize(SecurityInfoSerDes.deserialize(data))));
    assertEquals(si, SecurityInfoSerDes.deserialize(data));
}
项目:keystore-explorer    文件:KeyPairUtil.java   
/**
 * Generate a EC key pair.
 *
 * @param curveName
 *            Name of the ECC curve
 * @param provider A JCE provider.
 * @return A key pair
 * @throws CryptoException
 *             If there was a problem generating the key pair
 */
public static KeyPair generateECKeyPair(String curveName, Provider provider) throws CryptoException {
    try {
        // Get a key pair generator
        KeyPairGenerator keyPairGen;
        if (provider != null) {
            keyPairGen = KeyPairGenerator.getInstance(KeyPairType.EC.jce(), provider);
        } else {
            keyPairGen = KeyPairGenerator.getInstance(KeyPairType.EC.jce(), BOUNCY_CASTLE.jce());
        }

        keyPairGen.initialize(new ECGenParameterSpec(curveName), SecureRandom.getInstance("SHA1PRNG"));

        // Generate and return the key pair
        KeyPair keyPair = keyPairGen.generateKeyPair();
        return keyPair;
    } catch (GeneralSecurityException ex) {
        throw new CryptoException(MessageFormat.format(res.getString("NoGenerateKeypair.exception.message"),
                KeyPairType.EC), ex);
    }
}
项目:UAF    文件:FidoKeyStoreBC.java   
@Override
public KeyPair generateKeyPair(String username) {
    try {
        ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp256r1");
        KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "SC");
        g.initialize(ecGenSpec, new SecureRandom());
        KeyPair keyPair = g.generateKeyPair();

        Preferences.setSettingsParam("pub", Base64url.encodeToString(keyPair.getPublic().getEncoded()));
        Preferences.setSettingsParam("priv", Base64url.encodeToString(keyPair.getPrivate().getEncoded()));

        return keyPair;
    } catch(GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}
项目:mcanalytics    文件:SSLUtil.java   
/**
 * Generates a new Elliptic Curve Digital Signature Algorithm (ECDSA) public/private key pair.
 *
 * System's default SecureRandom is used
 *
 * @param curveName the name of a pre-defined elliptic curve (e.g. secp521r1)
 * @param provider the JCE provider to use
 * @return a new ECDSA key pair
 */
public static KeyPair newECDSAKeyPair(String curveName, String provider) {
    KeyPair ret;
    try {
        ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(curveName);
        KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", provider);
        g.initialize(ecGenSpec, new SecureRandom());
        ret = g.generateKeyPair();
    } catch(NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchProviderException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace(System.err);
        ret = null;
    }

    return ret;
}
项目:infobip-open-jdk-8    文件:ECKeyPairGenerator.java   
@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;
}
项目:jdk8u-dev-jdk    文件:ECKeyPairGenerator.java   
@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;
}
项目:SI    文件:SecurityInfoSerDesTest.java   
@Test
public void security_info_rpk_ser_des_then_equal() throws Exception {
    byte[] publicX = Hex
            .decodeHex("89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5".toCharArray());
    byte[] publicY = Hex
            .decodeHex("cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68".toCharArray());
    // Get Elliptic Curve Parameter spec for secp256r1
    AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
    algoParameters.init(new ECGenParameterSpec("secp256r1"));
    ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

    // Create key specs
    KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)),
            parameterSpec);

    SecurityInfo si = SecurityInfo.newRawPublicKeyInfo("myendpoint",
            KeyFactory.getInstance("EC").generatePublic(publicKeySpec));

    byte[] data = SecurityInfoSerDes.serialize(si);

    assertEquals(
            "{\"ep\":\"myendpoint\",\"rpk\":{\"x\":\"89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5\",\"y\":\"cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68\",\"params\":\"secp256r1\"}}",
            new String(data));
    System.err.println(new String(SecurityInfoSerDes.serialize(SecurityInfoSerDes.deserialize(data))));
    assertEquals(si, SecurityInfoSerDes.deserialize(data));
}
项目:cryptopresencetest    文件:ECPublicKeyEncoding.java   
public void testEncodingAndDecodingECPublicECKey() throws NoSuchProviderException,
        NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        InvalidKeySpecException {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDH", "SC");
    final ECGenParameterSpec ecGenParameterSpec = new ECGenParameterSpec(ecName);
    keyPairGenerator.initialize(ecGenParameterSpec, new SecureRandom());
    final KeyPair testKeyPair = keyPairGenerator.generateKeyPair();

    byte[] x509EncodedPublicKey = testKeyPair.getPublic().getEncoded();

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(x509EncodedPublicKey);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDH", "SC");
    ECPublicKey reconstitutedPublicKey =
            (ECPublicKey) keyFactory.generatePublic(x509EncodedKeySpec);

    assertTrue(testKeyPair.getPublic().equals(reconstitutedPublicKey));
}