Example usage for java.security.spec ECGenParameterSpec ECGenParameterSpec

List of usage examples for java.security.spec ECGenParameterSpec ECGenParameterSpec

Introduction

In this page you can find the example usage for java.security.spec ECGenParameterSpec ECGenParameterSpec.

Prototype

public ECGenParameterSpec(String stdName) 

Source Link

Document

Creates a parameter specification for EC parameter generation using a standard (or predefined) name stdName in order to generate the corresponding (precomputed) elliptic curve domain parameters.

Usage

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Generates a keypair//from   w ww .ja va 2s.co m
 * 
 * @param keySpec
 *            string specification of keys to generate, typical value is 2048 for RSA keys,
 *            1024 for DSA keys, secp256r1 for ECDSA keys, or null if algspec is to be used.
 * @param algSpec
 *            AlgorithmParameterSpec of keys to generate, typically an EXParameterSpec for EC keys, or null if keySpec is to be used.
 * @param keyAlg
 *            algorithm of keys to generate, typical value is RSA, DSA or ECDSA, see AlgorithmConstants.KEYALGORITHM_XX
 * 
 * @see org.cesecore.certificates.util.core.model.AlgorithmConstants
 * @see org.bouncycastle.asn1.x9.X962NamedCurves
 * @see org.bouncycastle.asn1.nist.NISTNamedCurves
 * @see org.bouncycastle.asn1.sec.SECNamedCurves
 * 
 * @return KeyPair the generated keypair
 * @throws InvalidAlgorithmParameterException
 * @see org.cesecore.certificates.util.AlgorithmConstants#KEYALGORITHM_RSA
 */
public static KeyPair genKeys(final String keySpec, final AlgorithmParameterSpec algSpec, final String keyAlg)
        throws InvalidAlgorithmParameterException {
    if (log.isTraceEnabled()) {
        log.trace(">genKeys(" + keySpec + ", " + keyAlg + ")");
    }

    KeyPairGenerator keygen;
    try {
        keygen = KeyPairGenerator.getInstance(keyAlg, BouncyCastleProvider.PROVIDER_NAME);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Algorithm " + keyAlg + "was not recognized.", e);
    } catch (NoSuchProviderException e) {
        throw new IllegalStateException("BouncyCastle was not found as a provider.", e);
    }
    if (StringUtils.equals(keyAlg, AlgorithmConstants.KEYALGORITHM_ECDSA)) {
        AlgorithmParameterSpec ecSpec = null;
        if ((keySpec != null) && !StringUtils.equals(keySpec, "implicitlyCA")) {
            log.debug("Generating named curve ECDSA key pair: " + keySpec);
            // We have EC keys
            ECGenParameterSpec bcSpec = new ECGenParameterSpec(keySpec);
            keygen.initialize(bcSpec, new SecureRandom());
            // The old code should work in BC v1.50b6 and later, but in vesions prior to that the below produces a key with explicit parameter encoding instead of named curves.
            // There is a test for this in KeyToolsTest.testGenKeysECDSAx9
            //                ecSpec = ECNamedCurveTable.getParameterSpec(keySpec);
            //                if (ecSpec == null) {
            //                    throw new InvalidAlgorithmParameterException("keySpec " + keySpec + " is invalid for ECDSA.");
            //                }
            //                keygen.initialize(ecSpec, new SecureRandom());
        } else if (algSpec != null) {
            log.debug("Generating ECDSA key pair from AlgorithmParameterSpec: " + algSpec);
            ecSpec = algSpec;
            keygen.initialize(ecSpec, new SecureRandom());
        } else if (StringUtils.equals(keySpec, "implicitlyCA")) {
            log.debug("Generating implicitlyCA encoded ECDSA key pair");
            // If the keySpec is null, we have "implicitlyCA" defined EC parameters
            // The parameters were already installed when we installed the provider
            // We just make sure that ecSpec == null here
            keygen.initialize(ecSpec, new SecureRandom());
        } else {
            throw new InvalidAlgorithmParameterException("No keySpec no algSpec and no implicitlyCA specified");
        }
    } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) {
        AlgorithmParameterSpec ecSpec = null;
        if (keySpec != null) {
            log.debug("Generating keys from given key specifications : " + keySpec);
            ecSpec = ECGOST3410NamedCurveTable.getParameterSpec(keySpec);
            if (ecSpec == null)
                throw new InvalidAlgorithmParameterException(
                        "Key specification " + keySpec + " is invalid for ECGOST3410");
        } else if (algSpec != null) {
            log.debug("Generating keys from given algorithm parameters : " + algSpec);
            ecSpec = algSpec;
        } else {
            throw new InvalidAlgorithmParameterException("No key or algorithm specifications");
        }
        keygen.initialize(ecSpec, new SecureRandom());
    } else if (keyAlg.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) {
        AlgorithmParameterSpec ecSpec = null;
        if (keySpec != null) {
            log.debug("Generating keys from given key specifications : " + keySpec);
            ecSpec = dstuOidToAlgoParams(keySpec);
            if (ecSpec == null)
                throw new InvalidAlgorithmParameterException(
                        "Key specification " + keySpec + " is invalid for DSTU4145");
        } else if (algSpec != null) {
            log.debug("Generating keys from given algorithm parameters : " + algSpec);
            ecSpec = algSpec;
        } else {
            throw new InvalidAlgorithmParameterException("No key or algorithm specifications");
        }
        keygen.initialize(ecSpec, new SecureRandom());
    } else if (keySpec.startsWith("DSA")) {
        // DSA key with "DSA" in keyspec
        final int keysize = Integer.parseInt(keySpec.substring(3));
        keygen.initialize(keysize);
    } else {
        // RSA or DSA key where keyspec is simply the key length
        final int keysize = Integer.parseInt(keySpec);
        keygen.initialize(keysize);
    }

    final KeyPair keys = keygen.generateKeyPair();

    if (log.isDebugEnabled()) {
        final PublicKey pk = keys.getPublic();
        final int len = getKeyLength(pk);
        log.debug("Generated " + keys.getPublic().getAlgorithm() + " keys with length " + len);
    }
    log.trace("<genKeys()");
    return keys;
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Gets the parameter spec from a given OID of a DSTU curve (they don't have names) 
 *//*from  www . j a v  a 2 s.c o  m*/
public static AlgorithmParameterSpec dstuOidToAlgoParams(String dstuOid) {
    return new ECGenParameterSpec(dstuOid);
}

From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java

public static KeyPair getKeyPair()
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
    //ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("prime192v1");
    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp256r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "SC");
    g.initialize(ecGenSpec, new SecureRandom());
    return g.generateKeyPair();
}

From source file:org.eclipse.leshan.server.demo.LeshanServerDemo.java

public static void createAndStartServer(int webPort, String localAddress, int localPort,
        String secureLocalAddress, int secureLocalPort, String redisUrl) throws Exception {
    // Prepare LWM2M server
    LeshanServerBuilder builder = new LeshanServerBuilder();
    builder.setLocalAddress(localAddress, localPort);
    builder.setLocalSecureAddress(secureLocalAddress, secureLocalPort);
    builder.setEncoder(new DefaultLwM2mNodeEncoder());
    LwM2mNodeDecoder decoder = new DefaultLwM2mNodeDecoder();
    builder.setDecoder(decoder);/*from  ww  w. j  av  a 2 s.c  o m*/

    // connect to redis if needed
    Pool<Jedis> jedis = null;
    if (redisUrl != null) {
        // TODO: support sentinel pool and make pool configurable
        jedis = new JedisPool(new URI(redisUrl));
    }

    // Get public and private server key
    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    try {
        // Get point values
        byte[] publicX = Hex
                .decodeHex("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73".toCharArray());
        byte[] publicY = Hex
                .decodeHex("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a".toCharArray());
        byte[] privateS = Hex
                .decodeHex("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400".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);
        KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec);

        // Get keys
        publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
        privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec);
        builder.setPublicKey(publicKey);
        builder.setPrivateKey(privateKey);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidParameterSpecException e) {
        LOG.error("Unable to initialize RPK.", e);
        System.exit(-1);
    }

    // Define model provider
    LwM2mModelProvider modelProvider = new StandardModelProvider();
    builder.setObjectModelProvider(modelProvider);

    // Set securityStore & registrationStore
    EditableSecurityStore securityStore;
    if (jedis == null) {
        // use file persistence
        securityStore = new FileSecurityStore();
    } else {
        // use Redis Store
        securityStore = new RedisSecurityStore(jedis);
        builder.setRegistrationStore(new RedisRegistrationStore(jedis));
    }
    builder.setSecurityStore(securityStore);

    // Create and start LWM2M server
    LeshanServer lwServer = builder.build();

    // Now prepare Jetty
    Server server = new Server(webPort);
    WebAppContext root = new WebAppContext();
    root.setContextPath("/");
    root.setResourceBase(LeshanServerDemo.class.getClassLoader().getResource("webapp").toExternalForm());
    root.setParentLoaderPriority(true);
    server.setHandler(root);

    // Create Servlet
    EventServlet eventServlet = new EventServlet(lwServer, lwServer.getSecureAddress().getPort());
    ServletHolder eventServletHolder = new ServletHolder(eventServlet);
    root.addServlet(eventServletHolder, "/event/*");

    ServletHolder clientServletHolder = new ServletHolder(
            new ClientServlet(lwServer, lwServer.getSecureAddress().getPort()));
    root.addServlet(clientServletHolder, "/api/clients/*");

    ServletHolder securityServletHolder = new ServletHolder(new SecurityServlet(securityStore, publicKey));
    root.addServlet(securityServletHolder, "/api/security/*");

    ServletHolder objectSpecServletHolder = new ServletHolder(
            new ObjectSpecServlet(lwServer.getModelProvider()));
    root.addServlet(objectSpecServletHolder, "/api/objectspecs/*");

    // Start Jetty & Leshan
    lwServer.start();
    server.start();
    LOG.info("Web server started at {}.", server.getURI());
}

From source file:org.eclipse.leshan.standalone.servlet.json.SecurityDeserializer.java

@Override
public SecurityInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    if (json == null) {
        return null;
    }/*from ww  w .j  a v  a  2  s. c om*/

    SecurityInfo info = null;

    if (json.isJsonObject()) {
        JsonObject object = (JsonObject) json;

        String endpoint = null;
        if (object.has("endpoint")) {
            endpoint = object.get("endpoint").getAsString();
        } else {
            throw new JsonParseException("Missing endpoint");
        }

        JsonObject psk = (JsonObject) object.get("psk");
        JsonObject rpk = (JsonObject) object.get("rpk");
        if (psk != null) {
            // PSK Deserialization
            String identity = null;
            if (psk.has("identity")) {
                identity = psk.get("identity").getAsString();
            } else {
                throw new JsonParseException("Missing PSK identity");
            }
            byte[] key;
            try {
                key = Hex.decodeHex(psk.get("key").getAsString().toCharArray());
            } catch (DecoderException e) {
                throw new JsonParseException(e);
            }

            info = SecurityInfo.newPreSharedKeyInfo(endpoint, identity, key);
        } else if (rpk != null) {
            PublicKey key;
            try {
                byte[] x = Hex.decodeHex(rpk.get("x").getAsString().toCharArray());
                byte[] y = Hex.decodeHex(rpk.get("y").getAsString().toCharArray());
                String params = rpk.get("params").getAsString();

                AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
                algoParameters.init(new ECGenParameterSpec(params));
                ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

                KeySpec keySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)),
                        parameterSpec);

                key = KeyFactory.getInstance("EC").generatePublic(keySpec);
            } catch (DecoderException | InvalidKeySpecException | NoSuchAlgorithmException
                    | InvalidParameterSpecException e) {
                throw new JsonParseException("Invalid security info content", e);
            }
            info = SecurityInfo.newRawPublicKeyInfo(endpoint, key);
        } else {
            throw new JsonParseException("Invalid security info content");
        }
    }

    return info;
}

From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java

/** 
 * @see org.ejbca.util.keystore.KeyStoreContainer#generate(java.lang.String, java.lang.String)
 *//*from   w w  w  .  ja  va2 s  .c  o  m*/
private byte[] generateEC(final String name, final String keyEntryName) throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">generate EC: curve name " + name + ", keyEntryName " + keyEntryName);
    }
    // Generate the EC Keypair
    final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", this.providerName);
    try {
        Provider prov = Security.getProvider(this.providerName);
        if (StringUtils.contains(prov.getClass().getName(), "iaik")) {
            throw new InvalidAlgorithmParameterException("IAIK ECC key generation not implemented.");
            /*
            ECDSAPrivateKey privateKeyTemplate = new ECDSAPrivateKey();
            privateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
            privateKeyTemplate.getToken().setBooleanValue(Boolean.FALSE);
                    
            ECDSAPublicKey publicKeyTemplate = new ECDSAPublicKey();
            publicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE);
            publicKeyTemplate.getToken().setBooleanValue(Boolean.FALSE);
                    
            ObjectID eccCurveObjectID = new ObjectID(objectID);
            publicKeyTemplate.getEcdsaParams().setByteArrayValue(DerCoder.encode(eccCurveObjectID));
                    
            PKCS11KeyPairGenerationSpec keyPairGenerationSpec =
               new PKCS11KeyPairGenerationSpec(tokenManager, publicKeyTemplate, privateKeyTemplate, 
               PKCS11Spec.USE_READ_WRITE_SESSION, PKCS11Spec.USE_USER_SESSION);
                    
            keyPairGenerator.initialize(keyPairGenerationSpec);
            */
        } else {
            kpg.initialize(new ECGenParameterSpec(name));
        }
    } catch (InvalidAlgorithmParameterException e) {
        log.debug("EC name " + name + " not supported.");
        throw e;
    }
    final byte result[] = generate(kpg, keyEntryName, "SHA1withECDSA");
    if (log.isTraceEnabled()) {
        log.trace("<generate: curve name " + name + ", keyEntryName " + keyEntryName);
    }
    return result;
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

private KeyPair generateKey(String encryptionName, String curveName) throws CryptoException {
    try {/*from  w  ww  .  jav a 2s  . c  o m*/
        ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(curveName);
        KeyPairGenerator g = SECURITY_PROVIDER == null ? KeyPairGenerator.getInstance(encryptionName)
                : KeyPairGenerator.getInstance(encryptionName, SECURITY_PROVIDER);
        g.initialize(ecGenSpec, new SecureRandom());
        return g.generateKeyPair();
    } catch (Exception exp) {
        throw new CryptoException("Unable to generate key pair", exp);
    }
}

From source file:org.psl.fidouaf.core.crypto.KeyCodec.java

public static KeyPair getKeyPair()
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
    // ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("prime192v1");
    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp256r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecGenSpec, new SecureRandom());
    return g.generateKeyPair();
}

From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java

@Override
public JSONObject generateKey(SignatureAlgorithm signatureAlgorithm, Long expirationTime) throws Exception {

    KeyPairGenerator keyGen = null;

    if (signatureAlgorithm == null) {
        throw new RuntimeException("The signature algorithm parameter cannot be null");
    } else if (SignatureAlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) {
        keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC");
        keyGen.initialize(2048, new SecureRandom());
    } else if (SignatureAlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) {
        ECGenParameterSpec eccgen = new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias());
        keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC");
        keyGen.initialize(eccgen, new SecureRandom());
    } else {// w w w . j a va2 s. c om
        throw new RuntimeException("The provided signature algorithm parameter is not supported");
    }

    // Generate the key
    KeyPair keyPair = keyGen.generateKeyPair();
    java.security.PrivateKey pk = keyPair.getPrivate();

    // Java API requires a certificate chain
    X509Certificate cert = generateV3Certificate(keyPair, dnName, signatureAlgorithm.getAlgorithm(),
            expirationTime);
    X509Certificate[] chain = new X509Certificate[1];
    chain[0] = cert;

    String alias = UUID.randomUUID().toString();

    keyStore.setKeyEntry(alias, pk, keyStoreSecret.toCharArray(), chain);
    FileOutputStream stream = new FileOutputStream(keyStoreFile);
    keyStore.store(stream, keyStoreSecret.toCharArray());

    PublicKey publicKey = keyPair.getPublic();

    JSONObject jsonObject = new JSONObject();
    jsonObject.put(KEY_TYPE, signatureAlgorithm.getFamily());
    jsonObject.put(KEY_ID, alias);
    jsonObject.put(KEY_USE, Use.SIGNATURE);
    jsonObject.put(ALGORITHM, signatureAlgorithm.getName());
    jsonObject.put(EXPIRATION_TIME, expirationTime);
    if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        jsonObject.put(MODULUS, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getModulus()));
        jsonObject.put(EXPONENT, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getPublicExponent()));
    } else if (publicKey instanceof ECPublicKey) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
        jsonObject.put(CURVE, signatureAlgorithm.getCurve());
        jsonObject.put(X, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineX()));
        jsonObject.put(Y, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineY()));
    }
    JSONArray x5c = new JSONArray();
    x5c.put(Base64.encodeBase64String(cert.getEncoded()));
    jsonObject.put(CERTIFICATE_CHAIN, x5c);

    return jsonObject;
}