Example usage for java.security.cert X509Certificate getPublicKey

List of usage examples for java.security.cert X509Certificate getPublicKey

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getPublicKey.

Prototype

public abstract PublicKey getPublicKey();

Source Link

Document

Gets the public key from this certificate.

Usage

From source file:org.gluu.oxtrust.action.ManageCertificateAction.java

@Restrict("#{s:hasPermission('configuration', 'access')}")
public boolean compare(String fileName) {
    KeyPair pair = getKeyPair(fileName);
    X509Certificate cert = sslService.getCertificate(getTempCertDir() + fileName);

    boolean noFilesPresent = (pair == null) && (cert == null);

    boolean filesPresent = (pair != null) && (cert != null);
    boolean filesValid = false;
    if (filesPresent) {
        filesValid = (pair.getPublic() != null) && (pair.getPublic().equals(cert.getPublicKey()));
    }/*w w  w .java 2s . c  o m*/

    boolean compareResult = (noFilesPresent || (filesPresent && filesValid));
    log.debug(fileName + " compare result: " + compareResult);
    return compareResult;
}

From source file:org.gluu.saml.Response.java

public boolean isValid() throws Exception {
    NodeList nodes = xmlDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");

    if (nodes == null || nodes.getLength() == 0) {
        throw new Exception("Can't find signature in document.");
    }/* w ww  .j  a v a  2s . c  o  m*/

    if (setIdAttributeExists()) {
        tagIdAttributes(xmlDoc);
    }

    X509Certificate cert = samlSettings.getCertificate();
    DOMValidateContext ctx = new DOMValidateContext(cert.getPublicKey(), nodes.item(0));
    XMLSignatureFactory sigF = XMLSignatureFactory.getInstance("DOM");
    XMLSignature xmlSignature = sigF.unmarshalXMLSignature(ctx);

    return xmlSignature.validate(ctx);
}

From source file:org.jgrades.lic.api.crypto.decrypt.SignatureValidator.java

public boolean signatureValidated(File encryptedLicenceFile, File signatureFile)
        throws LicenceCryptographyException {
    try {//from   w w w.  j a  va  2  s.com
        X509Certificate certificate = keyExtractor.getCertificateForVerification();
        PublicKey publicKey = certificate.getPublicKey();

        Signature signature = Signature.getInstance(SIGNATURE_PROVIDER_INTERFACE);
        signature.initVerify(publicKey);

        signature.update(FileUtils.readFileToByteArray(encryptedLicenceFile));

        return signature.verify(FileUtils.readFileToByteArray(signatureFile));
    } catch (SignatureException e) {
        LOGGER.error("Signature {} validation failed", signatureFile.getAbsolutePath(), e);
        return false;
    } catch (NoSuchAlgorithmException | InvalidKeyException | IOException e) {
        throw new LicenceCryptographyException(e);
    }
}

From source file:org.jgrades.security.utils.KeyStoreContentExtractorTest.java

@Test
public void shouldExtractCertificateForVerification() throws Exception {
    // when//from ww w.  jav a  2 s  .  c  om
    X509Certificate certificate = extractor.getCertificateForVerification();

    // then
    assertThat(certificate).isNotNull();
    assertThat(certificate.getPublicKey().getAlgorithm()).isEqualTo("RSA");
    assertThat(certificate.getPublicKey().getEncoded()).isEqualTo(FileUtils.readFileToByteArray(publicKey));
}

From source file:org.jgrades.security.utils.SignatureProvider.java

public boolean signatureValidated(File encryptedLicenceFile, File signatureFile) {
    try {//  w  w  w. j  av a  2s .c o  m
        X509Certificate certificate = extractor.getCertificateForVerification();
        PublicKey publicKey = certificate.getPublicKey();

        Signature signature = Signature.getInstance(SIGNATURE_PROVIDER_INTERFACE);
        signature.initVerify(publicKey);

        signature.update(FileUtils.readFileToByteArray(encryptedLicenceFile));

        return signature.verify(FileUtils.readFileToByteArray(signatureFile));
    } catch (SignatureException e) {
        LOGGER.debug("Signature verification failed", e);
        return false;
    } catch (NoSuchAlgorithmException | InvalidKeyException | IOException e) {
        throw new CryptographyException(e);
    }
}

From source file:org.jvnet.hudson.update_center.Signing.java

/**
 * Generates a canonicalized JSON format of the given object, and put the signature in it.
 * Because it mutates the signed object itself, validating the signature needs a bit of work,
 * but this enables a signature to be added transparently.
 *///from  w  ww .j a v a 2  s .c o  m
public void sign(JSONObject o) throws GeneralSecurityException, IOException {
    JSONObject sign = new JSONObject();

    List<X509Certificate> certs = getCertificateChain();
    X509Certificate signer = certs.get(0); // the first one is the signer, and the rest is the chain to a root CA.

    // this is for computing a digest
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), sha1);

    // this is for computing a signature
    PrivateKey key = ((KeyPair) new PEMReader(new FileReader(privateKey)).readObject()).getPrivate();
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initSign(key);
    SignatureOutputStream sos = new SignatureOutputStream(sig);

    // this is for verifying that signature validates
    Signature verifier = Signature.getInstance("SHA1withRSA");
    verifier.initVerify(signer.getPublicKey());
    SignatureOutputStream vos = new SignatureOutputStream(verifier);

    o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(new TeeOutputStream(dos, sos), vos), "UTF-8"));

    // digest
    byte[] digest = sha1.digest();
    sign.put("digest", new String(Base64.encodeBase64(digest)));

    // signature
    byte[] s = sig.sign();
    sign.put("signature", new String(Base64.encodeBase64(s)));

    // and certificate chain
    JSONArray a = new JSONArray();
    for (X509Certificate cert : certs)
        a.add(new String(Base64.encodeBase64(cert.getEncoded())));
    sign.put("certificates", a);

    // did the signature validate?
    if (!verifier.verify(s))
        throw new GeneralSecurityException(
                "Signature failed to validate. Either the certificate and the private key weren't matching, or a bug in the program.");

    o.put("signature", sign);
}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

@Override
public KeyPair getKeyPair(KeyStore ks, String keyAlias, String certAlias, String keyPassword)
        throws CertException {
    KeyPair keyPair = null;/*from  w  ww  .j  a  v a2 s.  c  o m*/
    try {
        if (!ks.containsAlias(keyAlias)) {
            throw new CertException("Missing keystore key entry for key alias:" + keyAlias);
        }
        if (!ks.containsAlias(certAlias)) {
            throw new CertException("Missing keystore certificate entry for :" + certAlias);
        }
        PrivateKey privateKey = (PrivateKey) ks.getKey(keyAlias, keyPassword.toCharArray());
        X509Certificate cert = (X509Certificate) ks.getCertificate(certAlias);
        PublicKey publicKey = cert.getPublicKey();
        keyPair = new KeyPair(publicKey, privateKey);
    } catch (UnrecoverableKeyException e) {
        throw new CertException(e);
    } catch (KeyStoreException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    }
    return keyPair;
}

From source file:org.openanzo.rdf.utils.KeystoreUtils.java

/**
 * // w  ww  .  jav a 2s .  co  m
 * @param keyStoreFile
 * @param keystoreType
 * @param password
 * @param alias
 * @param in
 * @throws AnzoException
 */
public static void addTrustedCert(String keyStoreFile, String keystoreType, String password, String alias,
        InputStream in) throws AnzoException {
    try {

        CertificateFactory cf = CertificateFactory.getInstance("X509");

        X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
        if (cert.getSubjectDN().equals(cert.getIssuerDN())) {
            cert.verify(cert.getPublicKey());
        }
        addTrustedCert(keyStoreFile, keystoreType, password, alias, cert);

    } catch (Exception cce) {
        throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, cce);
    }
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

public String generateCertificateReq(final String keyStoreName, final String keyStorePwd, final String keyAlias,
        final String signAlg, final boolean withTag) {
    try {/*from   w  w w  . jav  a  2 s.  c o  m*/
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName);
        ctlKeyStore.load(fInputStream, keyStorePwd.toCharArray());
        if (ctlKeyStore.containsAlias(keyAlias)) {
            final X509Certificate odlCert = (X509Certificate) ctlKeyStore.getCertificate(keyAlias);
            final PublicKey pubKey = odlCert.getPublicKey();
            final PrivateKey privKey = (PrivateKey) ctlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray());
            final String subject = odlCert.getSubjectDN().getName();
            final X509Name xname = new X509Name(subject);
            final String signatureAlgorithm = signAlg;
            final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm, xname,
                    pubKey, null, privKey);
            final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded());
            if (withTag) {
                final StringBuilder sb = new StringBuilder();
                sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST);
                sb.append("\n");
                sb.append(certReq);
                sb.append("\n");
                sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST);
                return sb.toString();
            }
            return certReq;
        }
        LOG.info("{} KeyStore does not contain alias {}", keyStoreName, keyAlias);
        return null;
    } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException
            | UnrecoverableKeyException | InvalidKeyException | NoSuchProviderException
            | SignatureException e) {
        LOG.error("Failed to generate certificate request {}", e.getMessage());
        return null;
    }
}

From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java

public String generateCertificateReq(final KeyStore odlKeyStore, final String keyStorePwd,
        final String keyAlias, final String signAlg, final boolean withTag) {
    try {/*from  w w w .j  av  a2  s .  c o m*/
        if (odlKeyStore.containsAlias(keyAlias)) {
            final X509Certificate odlCert = (X509Certificate) odlKeyStore.getCertificate(keyAlias);
            final PublicKey pubKey = odlCert.getPublicKey();
            final PrivateKey privKey = (PrivateKey) odlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray());
            final String subject = odlCert.getSubjectDN().getName();
            final X509Name xname = new X509Name(subject);
            final String signatureAlgorithm = signAlg;
            final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm, xname,
                    pubKey, null, privKey);
            final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded());
            if (withTag) {
                final StringBuilder sb = new StringBuilder();
                sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST);
                sb.append("\n");
                sb.append(certReq);
                sb.append("\n");
                sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST);
                return sb.toString();
            }
            return certReq;
        }
        LOG.info("KeyStore does not contain alias {}", keyAlias);
        return null;
    } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException
            | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        LOG.error("Failed to generate certificate request", e);
        return null;
    }
}