List of usage examples for java.security PublicKey getEncoded
public byte[] getEncoded();
From source file:be.fedict.eid.applet.beta.admin.AdministratorServiceBean.java
public void validateCertificateChain(List<X509Certificate> certificateChain) throws SecurityException { /*//from w ww. ja v a 2 s . c om * We're not using the entire PKI infrastructure here since we are in * control of the admin token ourselves. */ X509Certificate adminCert = certificateChain.get(0); PublicKey adminPublicKey = adminCert.getPublicKey(); String userId = getUserId(adminCert); if (isRegistered()) { LOG.debug("admin login"); } else { LOG.debug("admin registration"); register(adminPublicKey, userId); } String adminPassword = new String(Hex.encodeHex(adminPublicKey.getEncoded())); HttpServletRequest httpServletRequest; try { httpServletRequest = (HttpServletRequest) PolicyContext .getContext("javax.servlet.http.HttpServletRequest"); } catch (PolicyContextException e) { throw new RuntimeException("JACC error: " + e.getMessage()); } HttpSession httpSession = httpServletRequest.getSession(); Credentials credentials = (Credentials) httpSession.getAttribute("org.jboss.seam.security.credentials"); LOG.debug("username: " + userId); /* * Pass the eID credentials to the JBoss Seam security framework. */ credentials.setUsername(userId); credentials.setPassword(adminPassword); }
From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java
public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair) throws Exception { SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo(); RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo); RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent()); KeyFactory kf = KeyFactory.getInstance(ALG_RSA); PublicKey publicKey = kf.generatePublic(rsaSpec); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis() - DateConstant.ONE_DAY), new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo); ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER) .build(pKeyPair.getPrivate()); X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER) .getCertificate(certBuilder.build(signer)); signedCert.verify(pKeyPair.getPublic()); return signedCert; }
From source file:org.cesecore.keys.util.KeyTools.java
/** * create the subject key identifier.//www . j a v a 2 s . c o m * * @param pubKey * the public key * * @return SubjectKeyIdentifer asn.1 structure */ public static SubjectKeyIdentifier createSubjectKeyId(final PublicKey pubKey) { try { final ASN1Sequence keyASN1Sequence; ASN1InputStream pubKeyAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(pubKey.getEncoded())); try { final Object keyObject = pubKeyAsn1InputStream.readObject(); if (keyObject instanceof ASN1Sequence) { keyASN1Sequence = (ASN1Sequence) keyObject; } else { // PublicKey key that don't encode to a ASN1Sequence. Fix this by creating a BC object instead. final PublicKey altKey = (PublicKey) KeyFactory.getInstance(pubKey.getAlgorithm(), "BC") .translateKey(pubKey); ASN1InputStream altKeyAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(altKey.getEncoded())); try { keyASN1Sequence = (ASN1Sequence) altKeyAsn1InputStream.readObject(); } finally { altKeyAsn1InputStream.close(); } } X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); return x509ExtensionUtils.createSubjectKeyIdentifier(new SubjectPublicKeyInfo(keyASN1Sequence)); } finally { pubKeyAsn1InputStream.close(); } } catch (Exception e) { final RuntimeException e2 = new RuntimeException("error creating key"); // NOPMD e2.initCause(e); throw e2; } }
From source file:jenkins.bouncycastle.EncodignDecodingTest.java
@Test public void testReadCertificatePEM() throws Exception { PEMEncodable pemEncCer = PEMEncodable.read(CERTIFICATE_PEM); PEMEncodable pemEncKey = PEMEncodable.read(CERTIFICATE_PUBLIC_KEY_PEM); Certificate certificate = pemEncCer.toCertificate(); PublicKey publicKey = pemEncKey.toPublicKey(); assertNotNull(certificate);//from w w w.ja v a 2 s. c o m assertNotNull(publicKey); assertEquals(new String(Base64.encode(certificate.getPublicKey().getEncoded()), StandardCharsets.UTF_8), new String(Base64.encode(publicKey.getEncoded()), StandardCharsets.UTF_8)); }
From source file:jenkins.bouncycastle.EncodignDecodingTest.java
@Test public void testReadCertificateWithPasswordPEM() throws Exception { PEMEncodable pemEncCer = PEMEncodable.read(CERTIFICATE_PW_PEM); PEMEncodable pemEncKey = PEMEncodable.read(CERTIFICATE_PUBLIC_KEY_PW_PEM); Certificate certificate = pemEncCer.toCertificate(); PublicKey publicKey = pemEncKey.toPublicKey(); assertNotNull(certificate);//from w w w.j a v a 2 s.c o m assertNotNull(publicKey); assertEquals(new String(Base64.encode(certificate.getPublicKey().getEncoded()), StandardCharsets.UTF_8), new String(Base64.encode(publicKey.getEncoded()), StandardCharsets.UTF_8)); }
From source file:hudson.cli.Connection.java
/** * Verifies that we are talking to a peer that actually owns the private key corresponding to the public key we get. */// w w w .j a v a 2 s.c om public PublicKey verifyIdentity(byte[] sharedSecret) throws IOException, GeneralSecurityException { try { String serverKeyAlgorithm = readUTF(); PublicKey spk = KeyFactory.getInstance(serverKeyAlgorithm).generatePublic(readKey()); // verify the identity of the server Signature sig = Signature.getInstance("SHA1with" + serverKeyAlgorithm); sig.initVerify(spk); sig.update(spk.getEncoded()); sig.update(sharedSecret); sig.verify((byte[]) readObject()); return spk; } catch (ClassNotFoundException e) { throw new Error(e); // impossible } }
From source file:com.vmware.demo.SamlService.java
public String validateSAMLResponse(String samlResponse, String samlCert) throws Exception { String decodedString = ""; try {//from w w w . j ava 2 s .c o m decodedString = decodeSAMLResponse(samlResponse); InputStream inputStream = new ByteArrayInputStream(decodedString.getBytes("UTF-8")); // Parse XML BasicParserPool parserPoolManager = new BasicParserPool(); parserPoolManager.setNamespaceAware(true); parserPoolManager.setIgnoreElementContentWhitespace(true); Document document = parserPoolManager.parse(inputStream); Element metadataRoot = document.getDocumentElement(); QName qName = new QName(metadataRoot.getNamespaceURI(), metadataRoot.getLocalName(), metadataRoot.getPrefix()); // Unmarshall document Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(qName); Response response = (Response) unmarshaller.unmarshall(metadataRoot); Issuer issuer = response.getIssuer(); logger.info("Parsed response. Issued:" + response.getIssueInstant().toString() + ", issuer: " + issuer.getValue()); java.security.cert.X509Certificate jX509Cert = SamlUtils.parsePemCertificate(samlCert); if (null == jX509Cert) { logger.info("Failed to parse cert. " + samlCert); return ""; } PublicKey publicCert = jX509Cert.getPublicKey(); logger.info("Extracted cert. Cert:" + publicCert); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicCert.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); logger.debug("Key created by provider: " + keyFactory.getProvider().toString()); // Setup validation BasicX509Credential publicCredential = new BasicX509Credential(); publicCredential.setPublicKey(publicKey); SignatureValidator signatureValidator = new SignatureValidator(publicCredential); Signature signature = response.getSignature(); // Validate try { signatureValidator.validate(signature); logger.info("Assertion signature validated."); } catch (ValidationException e) { logger.error("Failed to validate signature of assertion", e); throw e; } // Get decryption key RSAPrivateKey privateKey = null; BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(privateKey); StaticKeyInfoCredentialResolver skicr = new StaticKeyInfoCredentialResolver(decryptionCredential); // Decrypt assertion Decrypter decrypter = new Decrypter(null, skicr, new InlineEncryptedKeyResolver()); if (response.getEncryptedAssertions().isEmpty()) { logger.info("Nothing to decrypt in assertion."); } else { Assertion decryptedAssertion; try { decryptedAssertion = decrypter.decrypt(response.getEncryptedAssertions().get(0)); logger.info("Assertion decryption succeeded."); } catch (DecryptionException e) { logger.error("Failed to decrypt assertion", e); throw e; } // Extract attributes, log in output List<AttributeStatement> attributeStatements = decryptedAssertion.getAttributeStatements(); for (int i = 0; i < attributeStatements.size(); i++) { List<Attribute> attributes = attributeStatements.get(i).getAttributes(); for (int x = 0; x < attributes.size(); x++) { String strAttributeName = attributes.get(x).getDOM().getAttribute("Name"); List<XMLObject> attributeValues = attributes.get(x).getAttributeValues(); for (int y = 0; y < attributeValues.size(); y++) { String strAttributeValue = attributeValues.get(y).getDOM().getTextContent(); logger.info(strAttributeName + " = " + strAttributeValue); } } } } } catch (Exception ex) { logger.error("Failed to validate assertion", ex); throw ex; } return decodedString; }
From source file:org.oscarehr.sharingcenter.actions.SecurityInfrastructureServlet.java
private String createNewInfrastructure(String alias, String commonName, String organizationalUnit, String organization, String locality, String state, String country) { InfrastructureDao dao = SpringUtils.getBean(InfrastructureDao.class); if (alias == null) { return "error"; }// w ww .j ava2 s . c o m if (dao.aliasExists(alias)) { return "exists"; } else { InfrastructureDataObject infrastructure = new InfrastructureDataObject(); infrastructure.setAlias(alias); infrastructure.setCommonName(commonName); infrastructure.setOrganizationalUnit(organizationalUnit); infrastructure.setOrganization(organization); infrastructure.setLocality(locality); infrastructure.setState(state); infrastructure.setCountry(country); //Generate, encode, and set the public and private keys try { KeyPair keyPair = SslUtility.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); Base64 base64 = new Base64(); String encodedPubKey = new String(base64.encode(publicKey.getEncoded()), MiscUtils.DEFAULT_UTF8_ENCODING); String encodedPrivKey = new String(base64.encode(privateKey.getEncoded()), MiscUtils.DEFAULT_UTF8_ENCODING); infrastructure.setBase64EncodedPublicKey(encodedPubKey); infrastructure.setBase64EncodedPrivateKey(encodedPrivKey); dao.persist(infrastructure); } catch (SslException e) { return "sslerror"; } catch (UnsupportedEncodingException e) { return "encodingerror"; } } return "success"; }
From source file:org.cesecore.keys.util.KeyStoreTools.java
/** * Install certificate chain to key in keystore. * @param file name of the file with chain. Starting with the certificate of the key. Ending with the root certificate. * @throws Exception// w ww. j a v a 2 s .co m */ public void installCertificate(final String fileName) throws Exception { final X509Certificate chain[] = ((Collection<?>) CertTools.getCertsFromPEM(new FileInputStream(fileName))) .toArray(new X509Certificate[0]); final PublicKey importPublicKey = chain[0].getPublicKey(); final String importKeyHash = CertTools.getFingerprintAsString(importPublicKey.getEncoded()); final Enumeration<String> eAlias = getKeyStore().aliases(); boolean notFound = true; while (eAlias.hasMoreElements() && notFound) { final String alias = eAlias.nextElement(); final PublicKey hsmPublicKey = getCertificate(alias).getPublicKey(); if (log.isDebugEnabled()) { log.debug("alias: " + alias + " SHA1 of public hsm key: " + CertTools.getFingerprintAsString(hsmPublicKey.getEncoded()) + " SHA1 of first public key in chain: " + importKeyHash + (chain.length == 1 ? "" : ("SHA1 of last public key in chain: " + CertTools.getFingerprintAsString( chain[chain.length - 1].getPublicKey().getEncoded())))); } if (hsmPublicKey.equals(importPublicKey)) { log.info("Found a matching public key for alias \"" + alias + "\"."); getKeyStore().setKeyEntry(alias, getPrivateKey(alias), null, chain); notFound = false; } } if (notFound) { final String msg = intres.getLocalizedMessage("token.errorkeynottoken", importKeyHash); throw new Exception(msg); } }
From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java
private X509Certificate getSelfCertificate(String myname, long validity, String sigAlg, KeyPair keyPair) throws Exception { final long currentTime = new Date().getTime(); final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000); final Date lastDate = new Date(currentTime + validity * 1000); // Add all mandatory attributes log.debug("keystore signing algorithm " + sigAlg); final PublicKey publicKey = keyPair.getPublic(); if (publicKey == null) { throw new Exception("Public key is null"); }//from w w w . ja va 2 s . co m final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(new X500Name(myname), BigInteger.valueOf(firstDate.getTime()), firstDate, lastDate, new X500Name(myname), pkinfo); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(this.providerName).build(keyPair.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); return (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); }