Java Code Examples for java.security.cert.Certificate#getPublicKey()
The following examples show how to use
java.security.cert.Certificate#getPublicKey() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SAMLServletAdapterTest.java From keycloak with Apache License 2.0 | 6 votes |
@Test public void testDOMAssertion() throws Exception { assertSuccessfulLogin(employeeDomServletPage, bburkeUser, testRealmSAMLPostLoginPage, "principal=bburke"); assertSuccessfullyLoggedIn(employeeDomServletPage, "principal=bburke"); driver.navigate().to(employeeDomServletPage.getUriBuilder().clone().path("getAssertionFromDocument").build().toURL()); waitForPageToLoad(); String xml = driver.getPageSource(); Assert.assertNotEquals("", xml); Document doc = DocumentUtil.getDocument(new StringReader(xml)); String certBase64 = DocumentUtil.getElement(doc, new QName("http://www.w3.org/2000/09/xmldsig#", "X509Certificate")).getTextContent(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate cert = cf.generateCertificate(new ByteArrayInputStream(Base64.decode(certBase64))); PublicKey pubkey = cert.getPublicKey(); Assert.assertTrue(AssertionUtil.isSignatureValid(doc.getDocumentElement(), pubkey)); employeeDomServletPage.logout(); checkLoggedOut(employeeDomServletPage, testRealmSAMLPostLoginPage); }
Example 2
Source File: CertUtil.java From littleca with Apache License 2.0 | 6 votes |
public static PublicKey getPublicKey(KeyStore keyStore, String alias) throws CertException { try { if (alias == null) { Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { alias = aliases.nextElement(); break; } } Certificate certificate = keyStore.getCertificate(alias); if (certificate == null) { throw new CertException(alias + " alias not found"); } return certificate.getPublicKey(); } catch (Exception e) { throw new CertException("analyze KeyStore failed", e); } }
Example 3
Source File: InvalidBitString.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
private static boolean test(Certificate target, Certificate signer, String title, boolean expected) throws Exception { System.out.print("Checking " + title + ": expected: " + (expected ? " verified" : "NOT verified")); boolean actual; try { PublicKey pubKey = signer.getPublicKey(); target.verify(pubKey); actual = true; } catch (SignatureException se) { actual = false; } System.out.println(", actual: " + (actual ? " verified" : "NOT verified")); return actual == expected; }
Example 4
Source File: SecretKeyProvider.java From Oauth2-Stateless-Authentication-with-Spring-and-JWT-Token with MIT License | 6 votes |
private KeyPair getKeyPair() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException { FileInputStream is = new FileInputStream("mykeys.jks"); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(is, "mypass".toCharArray()); String alias = "mykeys"; Key key = keystore.getKey(alias, "mypass".toCharArray()); if (key instanceof PrivateKey) { // Get certificate of public key Certificate cert = keystore.getCertificate(alias); // Get public key PublicKey publicKey = cert.getPublicKey(); // Return a key pair return new KeyPair(publicKey, (PrivateKey) key); } else throw new UnrecoverableKeyException(); }
Example 5
Source File: Signature.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
private static PublicKey getPublicKeyFromCert(Certificate cert) throws InvalidKeyException { // If the certificate is of type X509Certificate, // we should check whether it has a Key Usage // extension marked as critical. //if (cert instanceof java.security.cert.X509Certificate) { if (cert instanceof X509Certificate) { // Check whether the cert has a key usage extension // marked as a critical extension. // The OID for KeyUsage extension is 2.5.29.15. X509Certificate c = (X509Certificate)cert; Set<String> critSet = c.getCriticalExtensionOIDs(); if (critSet != null && !critSet.isEmpty() && critSet.contains("2.5.29.15")) { boolean[] keyUsageInfo = c.getKeyUsage(); // keyUsageInfo[0] is for digitalSignature. if ((keyUsageInfo != null) && (keyUsageInfo[0] == false)) throw new InvalidKeyException("Wrong key usage"); } } return cert.getPublicKey(); }
Example 6
Source File: TckBusiness.java From juddi with Apache License 2.0 | 6 votes |
private boolean verifySignedJAXBObject(Object obj) { try { DOMResult domResult = new DOMResult(); JAXB.marshal(obj, domResult); Document doc = ((Document) domResult.getNode()); Element docElement = doc.getDocumentElement(); KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE); URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE); ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray()); KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(SIGNATURE_KEYSTORE_ALIAS, new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray())); PrivateKey privateKey = keyEntry.getPrivateKey(); Certificate origCert = keyEntry.getCertificate(); PublicKey validatingKey = origCert.getPublicKey(); return TckSigningUtil.verifySignature(docElement, validatingKey); } catch (Exception e) { throw new RuntimeException(e); } }
Example 7
Source File: InvalidBitString.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
private static boolean test(Certificate target, Certificate signer, String title, boolean expected) throws Exception { System.out.print("Checking " + title + ": expected: " + (expected ? " verified" : "NOT verified")); boolean actual; try { PublicKey pubKey = signer.getPublicKey(); target.verify(pubKey); actual = true; } catch (SignatureException se) { actual = false; } System.out.println(", actual: " + (actual ? " verified" : "NOT verified")); return actual == expected; }
Example 8
Source File: NettyServerSslUtil.java From util4j with Apache License 2.0 | 5 votes |
public static void printPfxInfo(InputStream pfx, String strPassword){ try { String keyStoreType="PKCS12"; KeyStore ks = KeyStore.getInstance(keyStoreType); char[] nPassword = null; if ((strPassword == null) || strPassword.trim().equals("")){ nPassword = null; }else { nPassword = strPassword.toCharArray(); } ks.load(pfx, nPassword); pfx.close(); Enumeration<String> enumas = ks.aliases(); String keyAlias = null; if (enumas.hasMoreElements()) { keyAlias = (String)enumas.nextElement(); System.out.println("alias=[" + keyAlias + "]"); } System.out.println("is key entry=" + ks.isKeyEntry(keyAlias)); PrivateKey pkey = (PrivateKey) ks.getKey(keyAlias, nPassword); Certificate cert = ks.getCertificate(keyAlias); PublicKey pubkey = cert.getPublicKey(); System.out.println("cert class = " + cert.getClass().getName()); System.out.println("cert = " + cert); System.out.println("public key = " + pubkey); System.out.println("private key = " + pkey); } catch (Exception e) { e.printStackTrace(); } }
Example 9
Source File: SignatureUtil.java From jam-collaboration-sample with Apache License 2.0 | 5 votes |
/** * convert a base64 encoded certificate into a java object public key */ public static PublicKey makePublicKey(final String certificateBase64) { if (certificateBase64 == null || certificateBase64.isEmpty()) { throw new IllegalArgumentException("Supplied 'certificateBase64' argument is null or empty."); } try { final CertificateFactory cf = CertificateFactory.getInstance(PUBLIC_CERT_ALGORITHM); final Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(Base64.decode(certificateBase64))); return certificate.getPublicKey(); } catch (final CertificateException e) { throw new RuntimeException("Unable to generate certificates (" + PUBLIC_CERT_ALGORITHM + ") " + e.getMessage(), e); } }
Example 10
Source File: PolicyTool.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
/** * Retrieve the public key mapped to a particular name. * If the key has expired, a KeyException is thrown. */ PublicKey getPublicKeyAlias(String name) throws KeyStoreException { if (keyStore == null) { return null; } Certificate cert = keyStore.getCertificate(name); if (cert == null) { return null; } PublicKey pubKey = cert.getPublicKey(); return pubKey; }
Example 11
Source File: X509KeySelector.java From secure-data-service with Apache License 2.0 | 5 votes |
/** * Searches the specified keystore for a certificate that matches the * criteria specified in the CertSelector. * * @return a KeySelectorResult containing the cert's public key if there * is a match; otherwise null */ private KeySelectorResult keyStoreSelect(CertSelector cs) throws KeyStoreException { Enumeration aliases = ks.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate cert = ks.getCertificate(alias); if (cert != null && cs.match(cert)) { return new SimpleKeySelectorResult(cert.getPublicKey()); } } return null; }
Example 12
Source File: X509KeySelector.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
/** * Searches the specified keystore for a certificate that matches the * criteria specified in the CertSelector. * * @return a KeySelectorResult containing the cert's public key if there * is a match; otherwise null */ private KeySelectorResult keyStoreSelect(CertSelector cs) throws KeyStoreException { Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate cert = ks.getCertificate(alias); if (cert != null && cs.match(cert)) { return new SimpleKeySelectorResult(cert.getPublicKey()); } } return null; }
Example 13
Source File: PolicyTool.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
/** * Retrieve the public key mapped to a particular name. * If the key has expired, a KeyException is thrown. */ PublicKey getPublicKeyAlias(String name) throws KeyStoreException { if (keyStore == null) { return null; } Certificate cert = keyStore.getCertificate(name); if (cert == null) { return null; } PublicKey pubKey = cert.getPublicKey(); return pubKey; }
Example 14
Source File: Main.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
/** * Establishes a certificate chain (using trusted certificates in the * keystore and cacerts), starting with the reply (certToVerify) * and ending at a self-signed certificate found in the keystore. * * @param userCert optional existing certificate, mostly likely be the * original self-signed cert created by -genkeypair. * It must have the same public key as certToVerify * but cannot be the same cert. * @param certToVerify the starting certificate to build the chain * @returns the established chain, might be null if user decides not */ private Certificate[] establishCertChain(Certificate userCert, Certificate certToVerify) throws Exception { if (userCert != null) { // Make sure that the public key of the certificate reply matches // the original public key in the keystore PublicKey origPubKey = userCert.getPublicKey(); PublicKey replyPubKey = certToVerify.getPublicKey(); if (!origPubKey.equals(replyPubKey)) { throw new Exception(rb.getString ("Public.keys.in.reply.and.keystore.don.t.match")); } // If the two certs are identical, we're done: no need to import // anything if (certToVerify.equals(userCert)) { throw new Exception(rb.getString ("Certificate.reply.and.certificate.in.keystore.are.identical")); } } // Build a hash table of all certificates in the keystore. // Use the subject distinguished name as the key into the hash table. // All certificates associated with the same subject distinguished // name are stored in the same hash table entry as a vector. Hashtable<Principal, Vector<Pair<String,X509Certificate>>> certs = null; if (keyStore.size() > 0) { certs = new Hashtable<>(11); keystorecerts2Hashtable(keyStore, certs); } if (trustcacerts) { if (caks!=null && caks.size()>0) { if (certs == null) { certs = new Hashtable<>(11); } keystorecerts2Hashtable(caks, certs); } } // start building chain Vector<Pair<String,X509Certificate>> chain = new Vector<>(2); if (buildChain( new Pair<>(rb.getString("the.input"), (X509Certificate) certToVerify), chain, certs)) { for (Pair<String,X509Certificate> p : chain) { checkWeak(p.fst, p.snd); } Certificate[] newChain = new Certificate[chain.size()]; // buildChain() returns chain with self-signed root-cert first and // user-cert last, so we need to invert the chain before we store // it int j=0; for (int i=chain.size()-1; i>=0; i--) { newChain[j] = chain.elementAt(i).snd; j++; } return newChain; } else { throw new Exception (rb.getString("Failed.to.establish.chain.from.reply")); } }
Example 15
Source File: Main.java From dragonwell8_jdk with GNU General Public License v2.0 | 4 votes |
/** * Creates a PKCS#10 cert signing request, corresponding to the * keys (and name) associated with a given alias. */ private void doCertReq(String alias, String sigAlgName, PrintStream out) throws Exception { if (alias == null) { alias = keyAlias; } Pair<Key,char[]> objs = recoverKey(alias, storePass, keyPass); PrivateKey privKey = (PrivateKey)objs.fst; if (keyPass == null) { keyPass = objs.snd; } Certificate cert = keyStore.getCertificate(alias); if (cert == null) { MessageFormat form = new MessageFormat (rb.getString("alias.has.no.public.key.certificate.")); Object[] source = {alias}; throw new Exception(form.format(source)); } PKCS10 request = new PKCS10(cert.getPublicKey()); CertificateExtensions ext = createV3Extensions(null, null, v3ext, cert.getPublicKey(), null); // Attribute name is not significant request.getAttributes().setAttribute(X509CertInfo.EXTENSIONS, new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, ext)); // Construct a Signature object, so that we can sign the request if (sigAlgName == null) { sigAlgName = getCompatibleSigAlgName(privKey.getAlgorithm()); } Signature signature = Signature.getInstance(sigAlgName); signature.initSign(privKey); X500Name subject = dname == null? new X500Name(((X509Certificate)cert).getSubjectDN().toString()): new X500Name(dname); // Sign the request and base-64 encode it request.encodeAndSign(subject, signature); request.print(out); checkWeak(rb.getString("the.generated.certificate.request"), request); }
Example 16
Source File: CertPathValidatorUtilities.java From ripple-lib-java with ISC License | 4 votes |
/** * Return the next working key inheriting DSA parameters if necessary. * <p> * This methods inherits DSA parameters from the indexed certificate or * previous certificates in the certificate chain to the returned * <code>PublicKey</code>. The list is searched upwards, meaning the end * certificate is at position 0 and previous certificates are following. * </p> * <p> * If the indexed certificate does not contain a DSA key this method simply * returns the public key. If the DSA key already contains DSA parameters * the key is also only returned. * </p> * * @param certs The certification path. * @param index The index of the certificate which contains the public key * which should be extended with DSA parameters. * @return The public key of the certificate in list position * <code>index</code> extended with DSA parameters if applicable. * @throws AnnotatedException if DSA parameters cannot be inherited. */ protected static PublicKey getNextWorkingKey(List certs, int index, JcaJceHelper helper) throws CertPathValidatorException { Certificate cert = (Certificate)certs.get(index); PublicKey pubKey = cert.getPublicKey(); if (!(pubKey instanceof DSAPublicKey)) { return pubKey; } DSAPublicKey dsaPubKey = (DSAPublicKey)pubKey; if (dsaPubKey.getParams() != null) { return dsaPubKey; } for (int i = index + 1; i < certs.size(); i++) { X509Certificate parentCert = (X509Certificate)certs.get(i); pubKey = parentCert.getPublicKey(); if (!(pubKey instanceof DSAPublicKey)) { throw new CertPathValidatorException( "DSA parameters cannot be inherited from previous certificate."); } DSAPublicKey prevDSAPubKey = (DSAPublicKey)pubKey; if (prevDSAPubKey.getParams() == null) { continue; } DSAParams dsaParams = prevDSAPubKey.getParams(); DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec( dsaPubKey.getY(), dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); try { KeyFactory keyFactory = helper.createKeyFactory("DSA"); return keyFactory.generatePublic(dsaPubKeySpec); } catch (Exception exception) { throw new RuntimeException(exception.getMessage()); } } throw new CertPathValidatorException("DSA parameters cannot be inherited from previous certificate."); }
Example 17
Source File: Main.java From Bytecoder with Apache License 2.0 | 4 votes |
/** * Creates a PKCS#10 cert signing request, corresponding to the * keys (and name) associated with a given alias. */ private void doCertReq(String alias, String sigAlgName, PrintStream out) throws Exception { if (alias == null) { alias = keyAlias; } Pair<Key,char[]> objs = recoverKey(alias, storePass, keyPass); PrivateKey privKey = (PrivateKey)objs.fst; if (keyPass == null) { keyPass = objs.snd; } Certificate cert = keyStore.getCertificate(alias); if (cert == null) { MessageFormat form = new MessageFormat (rb.getString("alias.has.no.public.key.certificate.")); Object[] source = {alias}; throw new Exception(form.format(source)); } PKCS10 request = new PKCS10(cert.getPublicKey()); CertificateExtensions ext = createV3Extensions(null, null, v3ext, cert.getPublicKey(), null); // Attribute name is not significant request.getAttributes().setAttribute(X509CertInfo.EXTENSIONS, new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, ext)); // Construct a Signature object, so that we can sign the request if (sigAlgName == null) { sigAlgName = getCompatibleSigAlgName(privKey); } Signature signature = Signature.getInstance(sigAlgName); AlgorithmParameterSpec params = AlgorithmId .getDefaultAlgorithmParameterSpec(sigAlgName, privKey); SignatureUtil.initSignWithParam(signature, privKey, params, null); X500Name subject = dname == null? new X500Name(((X509Certificate)cert).getSubjectDN().toString()): new X500Name(dname); // Sign the request and base-64 encode it request.encodeAndSign(subject, signature); request.print(out); checkWeak(rb.getString("the.generated.certificate.request"), request); }
Example 18
Source File: Signature.java From android_9.0.0_r45 with Apache License 2.0 | 3 votes |
/** * Returns the public key for this signature. * * @throws CertificateException when Signature isn't a valid X.509 * certificate; shouldn't happen. * @hide */ public PublicKey getPublicKey() throws CertificateException { final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); final ByteArrayInputStream bais = new ByteArrayInputStream(mSignature); final Certificate cert = certFactory.generateCertificate(bais); return cert.getPublicKey(); }
Example 19
Source File: KeyStoreUtil.java From MaxKey with Apache License 2.0 | 2 votes |
/** * <p> * 根据证书获得公钥 * </p> * * @return * @throws Exception */ public static PublicKey getPublicKey(Certificate certificate) throws Exception { PublicKey publicKey = certificate.getPublicKey(); return publicKey; }
Example 20
Source File: ToolCertificate.java From protools with Apache License 2.0 | 1 votes |
/** * 由Certificate获得公钥 * * @param certificatePath * 证书路径 * * @return PublicKey 公钥 * * @throws Exception */ private static PublicKey getPublicKeyByCertificate(String certificatePath) throws CertificateException, IOException { // 获得证书 Certificate certificate = getCertificate(certificatePath); // 获得公钥 return certificate.getPublicKey(); }