Example usage for java.security PublicKey getEncoded

List of usage examples for java.security PublicKey getEncoded

Introduction

In this page you can find the example usage for java.security PublicKey getEncoded.

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:org.niord.core.keycloak.KeycloakIntegrationService.java

/**
 * Returns the Keycloak public key for the Niord realm.
 * The public key is returned in the format used by keycloak.json.
 * <p>//from ww w  .  j a  v a  2 s .c  om
 * If the setting for the public key has not been defined, the public key is
 * fetched directly from Keycloak.
 *
 * @return the Keycloak public key
 */
private String getKeycloakPublicRealmKey() throws Exception {
    if (StringUtils.isNotBlank(authServerRealmKey)) {
        return authServerRealmKey;
    }

    // Fetch the public key from Keycloak
    PublicKey publicKey = resolveKeycloakPublicRealmKey();
    authServerRealmKey = new String(Base64.getEncoder().encode(publicKey.getEncoded()), "utf-8");

    // Update the underlying setting
    settingsService.set("authServerRealmKey", authServerRealmKey);
    return authServerRealmKey;
}

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

@Override
public void generateCertReq(String alias, String sDN, boolean explicitEccParameters) throws Exception {
    PublicKey publicKey = getCertificate(alias).getPublicKey();
    final PrivateKey privateKey = getPrivateKey(alias);
    if (log.isDebugEnabled()) {
        log.debug("alias: " + alias + " SHA1 of public key: "
                + CertTools.getFingerprintAsString(publicKey.getEncoded()));
    }/* w  w  w .jav a  2  s  .  c o m*/
    String sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(publicKey).iterator().next();
    if (sigAlg == null) {
        sigAlg = "SHA1WithRSA";
    }
    if (sigAlg.contains("ECDSA") && explicitEccParameters) {
        log.info("Using explicit parameter encoding for ECC key.");
        publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC");
    } else {
        log.info("Using named curve parameter encoding for ECC key.");
    }
    X500Name sDNName = sDN != null ? new X500Name(sDN) : new X500Name("CN=" + alias);
    final PKCS10CertificationRequest certReq = CertTools.genPKCS10CertificationRequest(sigAlg, sDNName,
            publicKey, new DERSet(), privateKey, this.keyStore.getProvider().getName());
    ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(publicKey);
    if (!certReq.isSignatureValid(verifier)) {
        String msg = intres.getLocalizedMessage("token.errorcertreqverify", alias);
        throw new Exception(msg);
    }
    String filename = alias + ".pem";
    final Writer writer = new FileWriter(filename);
    writer.write(CertTools.BEGIN_CERTIFICATE_REQUEST + "\n");
    writer.write(new String(Base64.encode(certReq.getEncoded())));
    writer.write("\n" + CertTools.END_CERTIFICATE_REQUEST + "\n");
    writer.close();
    log.info("Wrote csr to file: " + filename);
}

From source file:test.integ.be.agiv.security.IPSTSTest.java

private SubjectKeyIdentifier createSubjectKeyId(PublicKey publicKey) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
    SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(bais).readObject());
    return new SubjectKeyIdentifier(info);
}

From source file:test.integ.be.agiv.security.IPSTSTest.java

private AuthorityKeyIdentifier createAuthorityKeyId(PublicKey publicKey) throws IOException {

    ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
    SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(bais).readObject());

    return new AuthorityKeyIdentifier(info);
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void storeDeviceList(DeviceList deviceList, ObfuscationKeyDB obKeys, ShareKeyDB shareKeys)
        throws SQLException, PersistanceException {
    Connection con = null;/*from  www . j  a  v a2  s.c o m*/
    PublicKey pKey = deviceList.getMasterSignatureKey();
    String fingerprint = DigestUtils.sha256Hex(pKey.getEncoded());
    String url = dbURL + fingerprint + ".db";
    try {
        con = DriverManager.getConnection(url, p);
        storeDeviceList(con, deviceList, pKey);
        Collection<PublicKey> pKeys = deviceList.getPublicKeys();
        logger.debug("User " + DigestUtils.md2Hex(deviceList.getMasterSignatureKey().getEncoded()) + " has "
                + pKeys.size() + " devices");
        storeKeys(shareKeys.get(pKeys), obKeys.get(pKeys), con);
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                logger.warn("Could not close DataBase Connection", e);
            }
        }
    }
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void storeDeviceList(Connection con, DeviceList deviceList, PublicKey pKey)
        throws SQLException, PersistanceException {

    Statement s = con.createStatement();
    try {// www .  j a v a 2  s. c  o  m
        createDLTables(s);
    } catch (SQLException e) {
        logger.error("Could not create DeviceList tables", e);
    } finally {
        s.close();
    }

    PreparedStatement insert = con.prepareStatement(INSERT_DEVICE_LIST);

    Iterator<String> it = deviceList.getAliasIterator();
    while (it.hasNext()) {
        String devAlias = it.next();
        PublicKey devPubKey = deviceList.getPublicKey(devAlias);
        final byte[] encodedPubKey = devPubKey.getEncoded();
        insert.setString(1, devAlias);
        insert.setBytes(2, encodedPubKey);
        int i = insert.executeUpdate();
        logger.debug("Inserted " + i + " rows of devicelist");
    }

    storeSignature(con, deviceList.getSignature());
    if (insert != null) {
        try {
            insert.close();
        } catch (Exception e) {
            logger.warn("Could not close Statement", e);
        }
    }
}

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

@Override
public void installCertificate(final String fileName) throws Exception {
    log.info("Installing " + fileName + ": ");
    final X509Certificate chain[] = ((Collection<?>) CertTools.getCertsFromPEM(new FileInputStream(fileName)))
            .toArray(new X509Certificate[0]);
    final Enumeration<String> eAlias = this.keyStore.aliases();
    boolean notFound = true;
    while (eAlias.hasMoreElements() && notFound) {
        final String alias = eAlias.nextElement();
        final PublicKey hsmPublicKey = getCertificate(alias).getPublicKey();
        final PublicKey importPublicKey = chain[0].getPublicKey();
        if (log.isDebugEnabled()) {
            log.debug("alias: " + alias + " SHA1 of public hsm key: "
                    + CertTools.getFingerprintAsString(hsmPublicKey.getEncoded())
                    + " SHA1 of first public key in chain: "
                    + CertTools.getFingerprintAsString(importPublicKey.getEncoded())
                    + (chain.length == 1 ? ""
                            : ("SHA1 of last public key in chain: " + CertTools.getFingerprintAsString(
                                    chain[chain.length - 1].getPublicKey().getEncoded()))));
        }/*from   w ww.ja va2  s . c  om*/
        if (hsmPublicKey.equals(importPublicKey)) {
            log.info("Found a matching public key for alias \"" + alias + "\".");
            this.keyStore.setKeyEntry(alias, getPrivateKey(alias), null, chain);
            notFound = false;
        }
    }
    if (notFound) {
        final String msg = intres.getLocalizedMessage("token.errorkeynottoken");
        throw new Exception(msg);
    }
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void storeSharePaticipants(Connection con, ShareMetaData smd)
        throws SQLException, PersistanceException {
    Iterator<String> it = smd.shareParticipants.getAliases();

    Statement s = con.createStatement();
    s.executeUpdate(DROP_SPL);//from  w  ww .  j a  v a 2  s .c o m
    s.executeUpdate(CREATE_SPL);
    s.close();
    PreparedStatement insert = con.prepareStatement(INSERT_SPL);
    while (it.hasNext()) {
        String alias = it.next();
        PublicKey pKey = smd.shareParticipants.getPublicKey(alias);
        insert.setString(1, alias);
        insert.setBytes(2, pKey.getEncoded());
        int i = insert.executeUpdate();
        logger.debug("Inserted " + i + " rows of shareparticipants");
        insert.clearParameters();
    }
    if (insert != null) {
        try {
            insert.close();
        } catch (Exception e) {
            logger.warn("Could not close Statement", e);
        }
    }
    storeSignature(con, smd.shareParticipants.getSignature());
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void initDeviceLists(ShareMetaData smd)
        throws SQLException, InitializaionException, SignatureException, DeviceListException {

    smd.deviceLists = new TreeMap<PublicKey, DeviceList>(Utils.PK_COMPARATOR);

    Connection con = null;/*from   www .  j  a  v a  2 s .  c o m*/
    SharePartList spl = smd.getSharePartList();
    if (spl != null) {
        Iterator<String> it = spl.getAliases();

        while (it.hasNext()) {
            String alias = (String) it.next();
            PublicKey pKey = spl.getPublicKey(alias);
            String fingerprint = DigestUtils.sha256Hex(pKey.getEncoded());
            String url = dbURL + fingerprint + ".db";
            try {
                con = DriverManager.getConnection(url, p);
                Statement s = con.createStatement();
                ResultSet rs = s.executeQuery(DEVICELIST_HAS_TABLES);
                if (rs.next() && DEVICELIST_NUM_TABLES == rs.getInt(1)) {
                    rs.close();
                    s.close();
                    logger.debug("Tables exist, loading devicelist for user " + alias);
                    loadDeviceList(con, smd, pKey);
                } else {
                    rs.close();
                    logger.debug("new Volume, creating tables for devicelist for user " + alias);
                    createDLTables(s);
                    s.close();
                }
            } catch (SQLException e) {
                logger.error("Error reading device list DB", e);
                SQLiteErrorCode code = SQLiteErrorCode.getErrorCode(e.getErrorCode());
                if (code.equals(SQLiteErrorCode.SQLITE_NOTADB) || code.equals(SQLiteErrorCode.SQLITE_CORRUPT)) {
                    // TODO: corrupt DB, consider deleting .db file
                    logger.warn("DB was corrupt, URL: " + dbURL);
                }
                continue;
            } finally {
                if (con != null) {
                    try {
                        con.close();
                    } catch (SQLException e) {
                        logger.warn("Could not close DataBase Connection", e);
                    }
                }
            }
        }

        // check devicelist signatures
        it = spl.getAliases();
        LinkedList<PublicKey> corruptDeviceList = new LinkedList<>();
        while (it.hasNext()) {
            String alias = (String) it.next();
            PublicKey pKey = spl.getPublicKey(alias);
            DeviceList list = smd.deviceLists.get(pKey);
            try {
                verifyDeviceList(smd, pKey, list);
            } catch (Exception e) {
                logger.warn("Could not verifiy device list of user" + alias, e);
                corruptDeviceList.add(pKey);
                if (list != null) {
                    for (PublicKey deviceKey : list.getPublicKeys()) {
                        smd.removeObfuscationKey(deviceKey);
                        smd.getShareKeys().removeDevice(deviceKey);
                    }
                }
            }
        }
        if (!corruptDeviceList.isEmpty()) {
            throw new DeviceListException("Could not verify DeviceList(s)!", corruptDeviceList);
        }
    }
}

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

/** Generates a certificate request (CSR) in PKCS#10 format and writes to file
 * @param alias for the key to be used//from w  w w  . j  ava2 s .com
 * @param dn the DN to be used. If null the 'CN=alias' will be used
 * @param explicitEccParameters false should be default and will use NamedCurve encoding of ECC public keys (IETF recommendation), use true to include all parameters explicitly (ICAO ePassport requirement).
 * @throws Exception
 */
public void generateCertReq(String alias, String sDN, boolean explicitEccParameters) throws Exception {
    PublicKey publicKey = getCertificate(alias).getPublicKey();
    final PrivateKey privateKey = getPrivateKey(alias);
    if (log.isDebugEnabled()) {
        log.debug("alias: " + alias + " SHA1 of public key: "
                + CertTools.getFingerprintAsString(publicKey.getEncoded()));
    }
    String sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(publicKey).iterator().next();
    if (sigAlg == null) {
        sigAlg = "SHA1WithRSA";
    }
    if (sigAlg.contains("ECDSA") && explicitEccParameters) {
        log.info("Using explicit parameter encoding for ECC key.");
        publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC");
    } else {
        log.info("Using named curve parameter encoding for ECC key.");
    }
    X500Name sDNName = sDN != null ? new X500Name(sDN) : new X500Name("CN=" + alias);
    final PKCS10CertificationRequest certReq = CertTools.genPKCS10CertificationRequest(sigAlg, sDNName,
            publicKey, new DERSet(), privateKey, this.keyStore.getProvider().getName());
    ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(publicKey);
    if (!certReq.isSignatureValid(verifier)) {
        String msg = intres.getLocalizedMessage("token.errorcertreqverify", alias);
        throw new Exception(msg);
    }
    String filename = alias + ".pem";
    final Writer writer = new FileWriter(filename);
    writer.write(CertTools.BEGIN_CERTIFICATE_REQUEST + "\n");
    writer.write(new String(Base64.encode(certReq.getEncoded())));
    writer.write("\n" + CertTools.END_CERTIFICATE_REQUEST + "\n");
    writer.close();
    log.info("Wrote csr to file: " + filename);
}