Example usage for java.security KeyPair getPublic

List of usage examples for java.security KeyPair getPublic

Introduction

In this page you can find the example usage for java.security KeyPair getPublic.

Prototype

public PublicKey getPublic() 

Source Link

Document

Returns a reference to the public key component of this key pair.

Usage

From source file:cherry.goods.crypto.RSASignatureTest.java

private RSASignature create2(char[] password) throws Exception {

    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);/*from  w  ww .  jav  a  2s .c  o  m*/
    KeyPair key = keygen.generateKeyPair();

    String pbeAlgName = "PBEWithMD5AndDES";
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(RandomUtils.nextBytes(8), 20);
    SecretKey pbeKey = SecretKeyFactory.getInstance(pbeAlgName).generateSecret(pbeKeySpec);
    AlgorithmParameters pbeParam = AlgorithmParameters.getInstance(pbeAlgName);
    pbeParam.init(pbeParamSpec);
    Cipher cipher = Cipher.getInstance(pbeAlgName);
    cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParam);
    EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(pbeParam,
            cipher.doFinal(key.getPrivate().getEncoded()));

    RSASignature impl = new RSASignature();
    impl.setAlgorithm("SHA256withRSA");
    impl.setPublicKeyBytes(key.getPublic().getEncoded());
    impl.setPrivateKeyBytes(encryptedKeyInfo.getEncoded(), password);
    return impl;
}

From source file:cherry.goods.crypto.RSACryptoTest.java

private RSACrypto create2(char[] password) throws Exception {

    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);/*from ww  w  .ja va2  s . co m*/
    KeyPair key = keygen.generateKeyPair();

    String pbeAlgName = "PBEWithMD5AndDES";
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(RandomUtils.nextBytes(8), 20);
    SecretKey pbeKey = SecretKeyFactory.getInstance(pbeAlgName).generateSecret(pbeKeySpec);
    AlgorithmParameters pbeParam = AlgorithmParameters.getInstance(pbeAlgName);
    pbeParam.init(pbeParamSpec);
    Cipher cipher = Cipher.getInstance(pbeAlgName);
    cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParam);
    EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(pbeParam,
            cipher.doFinal(key.getPrivate().getEncoded()));

    RSACrypto impl = new RSACrypto();
    impl.setAlgorithm("RSA/ECB/PKCS1Padding");
    impl.setPublicKeyBytes(key.getPublic().getEncoded());
    impl.setPrivateKeyBytes(encryptedKeyInfo.getEncoded(), password);
    return impl;
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * Initialize the Diffie-Hellman keys. This method is not thread safe
 *//*from www  .  j  a v  a 2 s.  c  o  m*/
public static void initDHKeys(DistributionConfig config) throws Exception {

    dhSKAlgo = config.getSecurityClientDHAlgo();
    dhPrivateKey = null;
    dhPublicKey = null;
    // Initialize the keys when either the host is a client that has
    // non-blank setting for DH symmetric algo, or this is a server
    // that has authenticator defined.
    if ((dhSKAlgo != null && dhSKAlgo.length() > 0) /* || securityService.isClientSecurityRequired() */) {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
        DHParameterSpec dhSpec = new DHParameterSpec(dhP, dhG, dhL);
        keyGen.initialize(dhSpec);
        KeyPair keypair = keyGen.generateKeyPair();

        // Get the generated public and private keys
        dhPrivateKey = keypair.getPrivate();
        dhPublicKey = keypair.getPublic();

        random = new SecureRandom();
        // Force the random generator to seed itself.
        byte[] someBytes = new byte[48];
        random.nextBytes(someBytes);
    }
}

From source file:org.tolven.config.model.CredentialManager.java

private X509CertificatePrivateKeyPair createSelfSignedCertificate(X500Principal subjectX500Principal)
        throws GeneralSecurityException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);//from  www  .  ja  va2  s  .c  o  m
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    X509Certificate certificate = signCertificate(subjectX500Principal, keyPair.getPublic(),
            subjectX500Principal, keyPair.getPrivate());
    return new X509CertificatePrivateKeyPair(certificate, keyPair.getPrivate());
}

From source file:com.trsst.Command.java

private static final X509Certificate createCertificate(KeyPair keyPair, String algorithm) {
    org.bouncycastle.x509.X509V3CertificateGenerator certGen = new org.bouncycastle.x509.X509V3CertificateGenerator();

    long now = System.currentTimeMillis();
    certGen.setSerialNumber(java.math.BigInteger.valueOf(now));

    org.bouncycastle.jce.X509Principal subject = new org.bouncycastle.jce.X509Principal(
            "CN=Trsst Keystore,DC=trsst,DC=com");
    certGen.setIssuerDN(subject);//w  w w  .j  a v a  2 s . c om
    certGen.setSubjectDN(subject);

    Date fromDate = new java.util.Date(now);
    certGen.setNotBefore(fromDate);
    Calendar cal = new java.util.GregorianCalendar();
    cal.setTime(fromDate);
    cal.add(java.util.Calendar.YEAR, 100);
    Date toDate = cal.getTime();
    certGen.setNotAfter(toDate);

    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm(algorithm);
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.BasicConstraints, true,
            new org.bouncycastle.asn1.x509.BasicConstraints(false));
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.KeyUsage, true,
            new org.bouncycastle.asn1.x509.KeyUsage(org.bouncycastle.asn1.x509.KeyUsage.digitalSignature
                    | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment
                    | org.bouncycastle.asn1.x509.KeyUsage.keyCertSign
                    | org.bouncycastle.asn1.x509.KeyUsage.cRLSign));
    X509Certificate x509 = null;
    try {
        x509 = certGen.generateX509Certificate(keyPair.getPrivate());
    } catch (InvalidKeyException e) {
        log.error("Error generating certificate: invalid key", e);
    } catch (SecurityException e) {
        log.error("Unexpected error generating certificate", e);
    } catch (SignatureException e) {
        log.error("Error generating generating certificate signature", e);
    }
    return x509;
}

From source file:com.schoentoon.connectbot.PubkeyListActivity.java

/**
 * @param name/*from   w  w  w .  jav a2  s .c  o m*/
 */
private void readKeyFromFile(File file) {
    PubkeyBean pubkey = new PubkeyBean();

    // find the exact file selected
    pubkey.setNickname(file.getName());

    if (file.length() > MAX_KEYFILE_SIZE) {
        Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show();
        return;
    }

    // parse the actual key once to check if its encrypted
    // then save original file contents into our database
    try {
        byte[] raw = readRaw(file);

        String data = new String(raw);
        if (data.startsWith(PubkeyUtils.PKCS8_START)) {
            int start = data.indexOf(PubkeyUtils.PKCS8_START) + PubkeyUtils.PKCS8_START.length();
            int end = data.indexOf(PubkeyUtils.PKCS8_END);

            if (end > start) {
                char[] encoded = data.substring(start, end - 1).toCharArray();
                Log.d(TAG, "encoded: " + new String(encoded));
                byte[] decoded = Base64.decode(encoded);

                KeyPair kp = PubkeyUtils.recoverKeyPair(decoded);

                pubkey.setType(kp.getPrivate().getAlgorithm());
                pubkey.setPrivateKey(kp.getPrivate().getEncoded());
                pubkey.setPublicKey(kp.getPublic().getEncoded());
            } else {
                Log.e(TAG, "Problem parsing PKCS#8 file; corrupt?");
                Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG)
                        .show();
            }
        } else {
            PEMStructure struct = PEMDecoder.parsePEM(new String(raw).toCharArray());
            pubkey.setEncrypted(PEMDecoder.isPEMEncrypted(struct));
            pubkey.setType(PubkeyDatabase.KEY_TYPE_IMPORTED);
            pubkey.setPrivateKey(raw);
        }

        // write new value into database
        if (pubkeydb == null)
            pubkeydb = new PubkeyDatabase(this);
        pubkeydb.savePubkey(pubkey);

        updateHandler.sendEmptyMessage(-1);
    } catch (Exception e) {
        Log.e(TAG, "Problem parsing imported private key", e);
        Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show();
    }
}

From source file:mitm.common.security.ca.hibernate.CertificateRequestStoreImplTest.java

@Test
public void testGetKeyPairSpeedTest() throws Exception {
    AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

    KeyPair keyPair = generateKeyPair();

    CertificateRequest request = delegator.addRequest(null, "test@example.com", 365, "SHA1",
            "http://example.com", "dummy", new byte[] { 1, 2, 3 }, new Date(), "Some message", keyPair);

    long start = System.currentTimeMillis();

    int repeat = 100;

    for (int i = 0; i < repeat; i++) {
        KeyPair keyPairCopy = request.getKeyPair(encryptor);

        assertNotNull(keyPairCopy);/*from ww  w.  j av a  2  s . c  om*/
        assertEquals(keyPair.getPublic(), keyPairCopy.getPublic());
        assertEquals(keyPair.getPrivate(), keyPairCopy.getPrivate());
    }

    long diff = System.currentTimeMillis() - start;

    double perSecond = repeat * 1000.0 / diff;

    System.out.println("getKeyPair's/sec: " + perSecond);

    /*
     * NOTE: !!! can fail on a slower system. The speed depends on the system encryptor. If the default settings 
     * (like iteration count) have been changed this might be slower.
     * 
     * On my Quad CPU Q8300, should be about 500/sec
     */
    assertTrue("getKeyPair too slow. !!! this can fail on a slower system !!!", perSecond > 200);
}

From source file:org.loklak.api.aaa.PublicKeyRegistrationService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JSONObjectWithDefault permissions) throws APIException {

    if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) {
        throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'");
    }/*from  w  ww  .  j  av a2 s . c o m*/

    JSONObject result = new JSONObject();

    // return algorithm parameters and users for whom we are allowed to register a key
    if (post.get("getParameters", false)) {
        result.put("self", permissions.getBoolean("self", false));
        result.put("users", permissions.getJSONObject("users"));
        result.put("userRoles", permissions.getJSONObject("userRoles"));

        JSONObject algorithms = new JSONObject();

        JSONObject rsa = new JSONObject();
        JSONArray keySizes = new JSONArray();
        for (int i : allowedKeySizesRSA) {
            keySizes.put(i);
        }
        rsa.put("sizes", keySizes);
        rsa.put("defaultSize", defaultKeySizeRSA);
        algorithms.put("RSA", rsa);
        result.put("algorithms", algorithms);

        JSONArray formats = new JSONArray();
        for (String format : allowedFormats) {
            formats.put(format);
        }
        result.put("formats", formats);

        return result;
    }

    // for which id?
    String id;
    if (post.get("id", null) != null)
        id = post.get("id", null);
    else
        id = authorization.getIdentity().getName();

    // check if we are allowed register a key
    if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user

        // create Authentication to check if the user id is a registered user
        ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id);
        Authentication authentication = new Authentication(credential, DAO.authentication);

        if (authentication.getIdentity() == null) { // check if identity is valid
            authentication.delete();
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
        }

        // check if the current user is allowed to create a key for the user in question
        boolean allowed = false;
        // check if the user in question is in 'users'
        if (permissions.getJSONObject("users", null).has(id)
                && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) {
            allowed = true;
        } else { // check if the user role of the user in question is in 'userRoles'
            Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization,
                    DAO.userRoles);
            for (String key : permissions.getJSONObject("userRoles").keySet()) {
                if (key.equals(auth.getUserRole().getName())
                        && permissions.getJSONObject("userRoles").getBoolean(key)) {
                    allowed = true;
                }
            }
        }
        if (!allowed)
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
    } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users)
        if (!permissions.getBoolean("self", false))
            throw new APIException(403, "You are not allowed to register a public key");
    }

    // set algorithm. later, we maybe want to support other algorithms as well
    String algorithm = "RSA";
    if (post.get("algorithm", null) != null) {
        algorithm = post.get("algorithm", null);
    }

    if (post.get("create", false)) { // create a new key pair on the server

        if (algorithm.equals("RSA")) {
            int keySize = 2048;
            if (post.get("key-size", null) != null) {
                int finalKeyLength = post.get("key-size", 0);
                if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) {
                    throw new APIException(400, "Invalid key size.");
                }
                keySize = finalKeyLength;
            }

            KeyPairGenerator keyGen;
            KeyPair keyPair;
            try {
                keyGen = KeyPairGenerator.getInstance(algorithm);
                keyGen.initialize(keySize);
                keyPair = keyGen.genKeyPair();
            } catch (NoSuchAlgorithmException e) {
                throw new APIException(500, "Server error");
            }

            registerKey(authorization.getIdentity(), keyPair.getPublic());

            String pubkey_pem = null, privkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                privkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
            result.put("privatekey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("privatekey_PEM", privkey_pem);
            result.put("keyhash", IO.getKeyHash(keyPair.getPublic()));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("key-size", keySize);
            result.put("message",
                    "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    } else if (post.get("register", null) != null) {

        if (algorithm.equals("RSA")) {
            String type = post.get("type", null);
            if (type == null)
                type = "DER";

            RSAPublicKey pub;
            String encodedKey;
            try {
                encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8");
            } catch (Throwable e) {
                throw new APIException(500, "Server error");
            }
            Log.getLog().info("Key (" + type + "): " + encodedKey);

            if (type.equals("DER")) {
                try {
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Throwable e) {
                    throw new APIException(400, "Public key not readable (DER)");
                }
            } else if (type.equals("PEM")) {
                try {
                    PemReader pemReader = new PemReader(new StringReader(encodedKey));
                    PemObject pem = pemReader.readPemObject();
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent());
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Exception e) {
                    throw new APIException(400, "Public key not readable (PEM)");
                }
            } else {
                throw new APIException(400, "Invalid value for 'type'.");
            }

            // check key size (not really perfect yet)
            int keySize;
            int bitLength = pub.getModulus().bitLength();
            if (bitLength <= 512) {
                keySize = 512;
            } else if (bitLength <= 1024) {
                keySize = 1024;
            } else if (bitLength <= 2048) {
                keySize = 2048;
            } else if (bitLength <= 4096) {
                keySize = 4096;
            } else {
                keySize = 8192;
            }
            if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) {
                throw new APIException(400, "Invalid key length.");
            }

            registerKey(authorization.getIdentity(), pub);

            String pubkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("keyhash", IO.getKeyHash(pub));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("message", "Successfully registered key.");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    }

    throw new APIException(400, "Invalid parameter");
}

From source file:ai.susi.server.api.aaa.PublicKeyRegistrationService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JsonObjectWithDefault permissions) throws APIException {

    if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) {
        throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'");
    }//from   w w w.  jav a  2 s.  c om

    JSONObject result = new JSONObject();

    // return algorithm parameters and users for whom we are allowed to register a key
    if (post.get("getParameters", false)) {
        result.put("self", permissions.getBoolean("self", false));
        result.put("users", permissions.getJSONObject("users"));
        result.put("userRoles", permissions.getJSONObject("userRoles"));

        JSONObject algorithms = new JSONObject();

        JSONObject rsa = new JSONObject();
        JSONArray keySizes = new JSONArray();
        for (int i : allowedKeySizesRSA) {
            keySizes.put(i);
        }
        rsa.put("sizes", keySizes);
        rsa.put("defaultSize", defaultKeySizeRSA);
        algorithms.put("RSA", rsa);
        result.put("algorithms", algorithms);

        JSONArray formats = new JSONArray();
        for (String format : allowedFormats) {
            formats.put(format);
        }
        result.put("formats", formats);

        return result;
    }

    // for which id?
    String id;
    if (post.get("id", null) != null)
        id = post.get("id", null);
    else
        id = authorization.getIdentity().getName();

    // check if we are allowed register a key
    if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user

        // create Authentication to check if the user id is a registered user
        ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id);
        Authentication authentication = new Authentication(credential, DAO.authentication);

        if (authentication.getIdentity() == null) { // check if identity is valid
            authentication.delete();
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
        }

        // check if the current user is allowed to create a key for the user in question
        boolean allowed = false;
        // check if the user in question is in 'users'
        if (permissions.getJSONObject("users", null).has(id)
                && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) {
            allowed = true;
        } else { // check if the user role of the user in question is in 'userRoles'
            Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization,
                    DAO.userRoles);
            for (String key : permissions.getJSONObject("userRoles").keySet()) {
                if (key.equals(auth.getUserRole().getName())
                        && permissions.getJSONObject("userRoles").getBoolean(key)) {
                    allowed = true;
                }
            }
        }
        if (!allowed)
            throw new APIException(400, "Bad request"); // do not leak if user exists or not
    } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users)
        if (!permissions.getBoolean("self", false))
            throw new APIException(403, "You are not allowed to register a public key");
    }

    // set algorithm. later, we maybe want to support other algorithms as well
    String algorithm = "RSA";
    if (post.get("algorithm", null) != null) {
        algorithm = post.get("algorithm", null);
    }

    if (post.get("create", false)) { // create a new key pair on the server

        if (algorithm.equals("RSA")) {
            int keySize = 2048;
            if (post.get("key-size", null) != null) {
                int finalKeyLength = post.get("key-size", 0);
                if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) {
                    throw new APIException(400, "Invalid key size.");
                }
                keySize = finalKeyLength;
            }

            KeyPairGenerator keyGen;
            KeyPair keyPair;
            try {
                keyGen = KeyPairGenerator.getInstance(algorithm);
                keyGen.initialize(keySize);
                keyPair = keyGen.genKeyPair();
            } catch (NoSuchAlgorithmException e) {
                throw new APIException(500, "Server error");
            }

            registerKey(authorization.getIdentity(), keyPair.getPublic());

            String pubkey_pem = null, privkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                privkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
            result.put("privatekey_DER_BASE64",
                    Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("privatekey_PEM", privkey_pem);
            result.put("keyhash", IO.getKeyHash(keyPair.getPublic()));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("key-size", keySize);
            result.put("message",
                    "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    } else if (post.get("register", null) != null) {

        if (algorithm.equals("RSA")) {
            String type = post.get("type", null);
            if (type == null)
                type = "DER";

            RSAPublicKey pub;
            String encodedKey;
            try {
                encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8");
            } catch (Throwable e) {
                throw new APIException(500, "Server error");
            }
            Log.getLog().info("Key (" + type + "): " + encodedKey);

            if (type.equals("DER")) {
                try {
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Throwable e) {
                    throw new APIException(400, "Public key not readable (DER)");
                }
            } else if (type.equals("PEM")) {
                try {
                    PemReader pemReader = new PemReader(new StringReader(encodedKey));
                    PemObject pem = pemReader.readPemObject();
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent());
                    pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec);
                } catch (Exception e) {
                    throw new APIException(400, "Public key not readable (PEM)");
                }
            } else {
                throw new APIException(400, "Invalid value for 'type'.");
            }

            // check key size (not really perfect yet)
            int keySize;
            int bitLength = pub.getModulus().bitLength();
            if (bitLength <= 512) {
                keySize = 512;
            } else if (bitLength <= 1024) {
                keySize = 1024;
            } else if (bitLength <= 2048) {
                keySize = 2048;
            } else if (bitLength <= 4096) {
                keySize = 4096;
            } else {
                keySize = 8192;
            }
            if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) {
                throw new APIException(400, "Invalid key length.");
            }

            registerKey(authorization.getIdentity(), pub);

            String pubkey_pem = null;
            try {
                StringWriter writer = new StringWriter();
                PemWriter pemWriter = new PemWriter(writer);
                pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded()));
                pemWriter.flush();
                pemWriter.close();
                pubkey_pem = writer.toString();
            } catch (IOException e) {
            }

            result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded()));
            result.put("publickey_PEM", pubkey_pem);
            result.put("keyhash", IO.getKeyHash(pub));
            try {
                result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
            result.put("message", "Successfully registered key.");

            return result;
        }
        throw new APIException(400, "Unsupported algorithm");
    }

    throw new APIException(400, "Invalid parameter");
}

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

private X509Certificate getSelfCertificate(String myname, long validity, String sigAlg, KeyPair keyPair)
        throws InvalidKeyException, CertificateException {
    final long currentTime = new Date().getTime();
    final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000);
    final Date lastDate = new Date(currentTime + validity * 1000);
    final X500Name issuer = new X500Name(myname);
    final BigInteger serno = BigInteger.valueOf(firstDate.getTime());
    final PublicKey publicKey = keyPair.getPublic();
    if (publicKey == null) {
        throw new InvalidKeyException("Public key is null");
    }/*w  ww  . j a  v a 2s. co  m*/

    try {
        final X509v3CertificateBuilder cg = new JcaX509v3CertificateBuilder(issuer, serno, firstDate, lastDate,
                issuer, publicKey);
        log.debug("Keystore signing algorithm " + sigAlg);
        final ContentSigner signer = new BufferingContentSigner(
                new JcaContentSignerBuilder(sigAlg).setProvider(this.providerName).build(keyPair.getPrivate()),
                20480);
        final X509CertificateHolder cert = cg.build(signer);
        return (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded());
    } catch (OperatorCreationException e) {
        log.error("Error creating content signer: ", e);
        throw new CertificateException(e);
    } catch (IOException e) {
        throw new CertificateException("Could not read certificate", e);
    }
}