Example usage for java.security.interfaces ECPublicKey getW

List of usage examples for java.security.interfaces ECPublicKey getW

Introduction

In this page you can find the example usage for java.security.interfaces ECPublicKey getW.

Prototype

ECPoint getW();

Source Link

Document

Returns the public point W.

Usage

From source file:org.apache.xml.security.stax.ext.XMLSecurityUtils.java

public static void createKeyValueTokenStructure(AbstractOutputProcessor abstractOutputProcessor,
        OutputProcessorChain outputProcessorChain, PublicKey publicKey)
        throws XMLStreamException, XMLSecurityException {

    if (publicKey == null) {
        throw new XMLSecurityException("stax.signature.publicKeyOrCertificateMissing");
    }//from www.j av a2 s  . co  m

    String algorithm = publicKey.getAlgorithm();

    abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
            XMLSecurityConstants.TAG_dsig_KeyValue, true, null);

    if ("RSA".equals(algorithm)) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_RSAKeyValue, false, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Modulus, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(rsaPublicKey.getModulus().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Modulus);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Exponent, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(rsaPublicKey.getPublicExponent().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Exponent);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_RSAKeyValue);
    } else if ("DSA".equals(algorithm)) {
        DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey;
        BigInteger j = dsaPublicKey.getParams().getP().subtract(BigInteger.ONE)
                .divide(dsaPublicKey.getParams().getQ());
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_DSAKeyValue, false, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_P, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getP().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_P);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Q, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getQ().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Q);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_G, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getG().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_G);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Y, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(dsaPublicKey.getY().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Y);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_J, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(j.toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_J);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_DSAKeyValue);
    } else if ("EC".equals(algorithm)) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;

        List<XMLSecAttribute> attributes = new ArrayList<XMLSecAttribute>(1);
        attributes.add(abstractOutputProcessor.createAttribute(XMLSecurityConstants.ATT_NULL_URI,
                "urn:oid:" + ECDSAUtils.getOIDFromPublicKey(ecPublicKey)));
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_ECKeyValue, true, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_NamedCurve, false, attributes);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_NamedCurve);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_PublicKey, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(
                        ECDSAUtils.encodePoint(ecPublicKey.getW(), ecPublicKey.getParams().getCurve())));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_PublicKey);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_ECKeyValue);
    }

    abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
            XMLSecurityConstants.TAG_dsig_KeyValue);
}

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

/**
 * Print parameters of public part of a key.
 * /*from   w w  w .j  a  v a  2  s . c  o m*/
 * @param publK
 *            the key
 * @param ps
 *            stream to print to.
 */
public static void printPublicKeyInfo(final PublicKey publK, final PrintStream ps) {
    if (publK instanceof RSAPublicKey) {
        ps.println("RSA key:");
        final RSAPublicKey rsa = (RSAPublicKey) publK;
        ps.println("  modulus: " + rsa.getModulus().toString(16));
        ps.println("  public exponent: " + rsa.getPublicExponent().toString(16));
        return;
    }
    if (publK instanceof ECPublicKey) {
        ps.println("Elliptic curve key:");
        final ECPublicKey ec = (ECPublicKey) publK;
        ps.println("  the affine x-coordinate: " + ec.getW().getAffineX().toString(16));
        ps.println("  the affine y-coordinate: " + ec.getW().getAffineY().toString(16));
        return;
    }
    if (publK instanceof DHPublicKey) {
        ps.println("DH key:");
        final DHPublicKey dh = (DHPublicKey) publK;
        ps.println("  the public value y: " + dh.getY().toString(16));
        return;
    }
    if (publK instanceof DSAPublicKey) {
        ps.println("DSA key:");
        final DSAPublicKey dsa = (DSAPublicKey) publK;
        ps.println("  the public value y: " + dsa.getY().toString(16));
        return;
    }
}

From source file:org.cesecore.util.CertTools.java

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage,
        Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder,
        List<Extension> additionalExtensions)
        throws CertificateParsingException, IOException, OperatorCreationException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;/*from   ww w .  ja v a2s  .c o  m*/
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("RSA was not a known algorithm", e);
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            final String algo = ecpk.getAlgorithm();
            if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) {
                try {
                    publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("ECGOST3410 was not a known algorithm", e);
                }
            } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) {
                try {
                    publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("DSTU4145 was not a known algorithm", e);
                }
            } else {
                try {
                    publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("EC was not a known algorithm", e);
                }
            }
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random;
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("SHA1PRNG was not a known algorithm", e);
    }
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    SubjectPublicKeyInfo pkinfo;
    try {
        pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    } catch (IOException e) {
        throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e);
    }
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
            CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate,
            CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA || keyusage != 0) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }

    if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        if (privateKeyNotBefore != null) {
            v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore)));
        }
        if (privateKeyNotAfter != null) {
            v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter)));
        }
        certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v));
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {

            ASN1InputStream sAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream aAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) sAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) aAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                sAsn1InputStream.close();
                aAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    // Add any additional
    if (additionalExtensions != null) {
        for (final Extension extension : additionalExtensions) {
            certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue());
        }
    }
    final ContentSigner signer = new BufferingContentSigner(
            new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}

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

@Override
public JsonElement serialize(SecurityInfo src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject element = new JsonObject();

    element.addProperty("endpoint", src.getEndpoint());

    if (src.getIdentity() != null) {
        JsonObject psk = new JsonObject();
        psk.addProperty("identity", src.getIdentity());
        psk.addProperty("key", Hex.encodeHexString(src.getPreSharedKey()));
        element.add("psk", psk);
    }//from  ww  w. jav  a2 s. c  o  m

    if (src.getRawPublicKey() != null) {
        JsonObject rpk = new JsonObject();
        PublicKey rawPublicKey = src.getRawPublicKey();
        if (rawPublicKey instanceof ECPublicKey) {
            ECPublicKey ecPublicKey = (ECPublicKey) rawPublicKey;
            // Get x coordinate
            byte[] x = ecPublicKey.getW().getAffineX().toByteArray();
            if (x[0] == 0)
                x = Arrays.copyOfRange(x, 1, x.length);
            rpk.addProperty("x", Hex.encodeHexString(x));

            // Get Y coordinate
            byte[] y = ecPublicKey.getW().getAffineY().toByteArray();
            if (y[0] == 0)
                y = Arrays.copyOfRange(y, 1, y.length);
            rpk.addProperty("y", Hex.encodeHexString(y));

            // Get Curves params
            rpk.addProperty("params", ecPublicKey.getParams().toString());
        } else {
            throw new JsonParseException("Unsupported Public Key Format (only ECPublicKey supported).");
        }
        element.add("rpk", rpk);
    }

    return element;
}

From source file:org.ejbca.util.CertTools.java

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, String provider)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException,
        IllegalStateException, NoSuchProviderException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be 
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//from   w  w w. j ava  2  s.c  o m
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);
    certgen.setSerialNumber(new java.math.BigInteger(serno).abs());
    certgen.setNotBefore(firstDate);
    certgen.setNotAfter(lastDate);
    certgen.setSignatureAlgorithm(sigAlg);
    certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));
    certgen.setIssuerDN(CertTools.stringToBcX509Name(dn));
    certgen.setPublicKey(publicKey);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku);
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded()))
                            .readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);

            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded()))
                            .readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
            certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq);
    }

    X509Certificate selfcert = certgen.generate(privKey, provider);

    return selfcert;
}

From source file:org.gluu.oxeleven.rest.GenerateKeyRestServiceImpl.java

public Response generateKey(String sigAlg, Long expirationTime) {
    Response.ResponseBuilder builder = Response.ok();

    try {//  w w  w.jav a  2 s. co  m
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromName(sigAlg);

        if (signatureAlgorithm == null) {
            builder = Response.status(Response.Status.BAD_REQUEST);
            builder.entity(StringUtils.getErrorResponse("invalid_request",
                    "The request asked for an operation that cannot be supported because the server does not support the provided signatureAlgorithm parameter."));
        } else if (expirationTime == null) {
            builder = Response.status(Response.Status.BAD_REQUEST);
            builder.entity(StringUtils.getErrorResponse("invalid_request",
                    "The request asked for an operation that cannot be supported because the expiration time parameter is mandatory."));
        } else if (signatureAlgorithm == SignatureAlgorithm.NONE
                || signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.HMAC)) {
            builder = Response.status(Response.Status.BAD_REQUEST);
            builder.entity(StringUtils.getErrorResponse("invalid_request",
                    "The provided signature algorithm parameter is not supported."));
        } else {
            String dnName = configuration.getDnName();
            String alias = pkcs11Service.generateKey(dnName, signatureAlgorithm, expirationTime);
            PublicKey publicKey = pkcs11Service.getPublicKey(alias);
            Certificate certificate = pkcs11Service.getCertificate(alias);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put(KEY_ID, alias);
            jsonObject.put(KEY_TYPE, signatureAlgorithm.getFamily());
            jsonObject.put(KEY_USE, "sig");
            jsonObject.put(ALGORITHM, signatureAlgorithm.getName());
            jsonObject.put(EXPIRATION_TIME, expirationTime);
            if (SignatureAlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) {
                RSAPublicKeyImpl rsaPublicKey = (RSAPublicKeyImpl) publicKey;
                jsonObject.put(MODULUS, Base64Util.base64UrlEncode(rsaPublicKey.getModulus().toByteArray()));
                jsonObject.put(EXPONENT,
                        Base64Util.base64UrlEncode(rsaPublicKey.getPublicExponent().toByteArray()));
            } else if (SignatureAlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) {
                ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
                jsonObject.put(CURVE, signatureAlgorithm.getCurve());
                jsonObject.put(X, Base64Util.base64UrlEncode(ecPublicKey.getW().getAffineX().toByteArray()));
                jsonObject.put(Y, Base64Util.base64UrlEncode(ecPublicKey.getW().getAffineY().toByteArray()));
            }
            JSONArray x5c = new JSONArray();
            x5c.put(Base64.encodeBase64String(certificate.getEncoded()));
            jsonObject.put(CERTIFICATE_CHAIN, x5c);

            builder.entity(jsonObject.toString());
        }
    } catch (CertificateException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (KeyStoreException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (NoSuchProviderException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (SignatureException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (JSONException e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    } catch (Exception e) {
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        log.error(e.getMessage(), e);
    }

    CacheControl cacheControl = new CacheControl();
    cacheControl.setNoTransform(false);
    cacheControl.setNoStore(true);
    builder.cacheControl(cacheControl);
    builder.header("Pragma", "no-cache");
    return builder.build();
}

From source file:org.keycloak.jose.jwk.JWKBuilder.java

public JWK ec(Key key) {
    ECPublicKey ecKey = (ECPublicKey) key;

    ECPublicJWK k = new ECPublicJWK();

    String kid = this.kid != null ? this.kid : KeyUtils.createKeyId(key);
    int fieldSize = ecKey.getParams().getCurve().getField().getFieldSize();
    BigInteger affineX = ecKey.getW().getAffineX();
    BigInteger affineY = ecKey.getW().getAffineY();

    k.setKeyId(kid);//  w ww  . ja  v a  2s .c o  m
    k.setKeyType(KeyType.EC);
    k.setAlgorithm(algorithm);
    k.setPublicKeyUse(DEFAULT_PUBLIC_KEY_USE);
    k.setCrv("P-" + fieldSize);
    k.setX(Base64Url.encode(toIntegerBytes(ecKey.getW().getAffineX())));
    k.setY(Base64Url.encode(toIntegerBytes(ecKey.getW().getAffineY())));

    return k;
}

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 {/*ww w .ja va 2  s .co m*/
        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;
}