List of usage examples for java.security.cert Certificate getEncoded
public abstract byte[] getEncoded() throws CertificateEncodingException;
From source file:org.ejbca.util.CertTools.java
/** Converts a regular array of certificates into an ArrayList, using the provided provided. * /*from w w w . ja v a 2 s . co m*/ * @param certs Certificate[] of certificates to convert * @param provider provider for example "SUN" or "BC", use null for the default provider (BC) * @return An ArrayList of certificates in the same order as the passed in array * @throws NoSuchProviderException * @throws CertificateException */ public static ArrayList<Certificate> getCertCollectionFromArray(Certificate[] certs, String provider) throws CertificateException, NoSuchProviderException { if (log.isTraceEnabled()) { log.trace(">getCertCollectionFromArray: " + provider); } ArrayList<Certificate> ret = new ArrayList<Certificate>(); String prov = provider; if (prov == null) { prov = "BC"; } for (int i = 0; i < certs.length; i++) { Certificate cert = certs[i]; Certificate newcert = getCertfromByteArray(cert.getEncoded(), prov); ret.add(newcert); } if (log.isTraceEnabled()) { log.trace("<getCertCollectionFromArray: " + ret.size()); } return ret; }
From source file:org.ejbca.util.CertTools.java
/** * Returns a certificate in PEM-format./*from www. j a va 2s. co m*/ * * @param certs Collection of Certificate to convert to PEM * @return byte array containing PEM certificate * @exception CertificateException if the stream does not contain a correct certificate. */ public static byte[] getPEMFromCerts(Collection<Certificate> certs) throws CertificateException { ByteArrayOutputStream ostr = new ByteArrayOutputStream(); PrintStream opstr = new PrintStream(ostr); Iterator<Certificate> iter = certs.iterator(); while (iter.hasNext()) { Certificate cert = (Certificate) iter.next(); byte[] certbuf = Base64.encode(cert.getEncoded()); opstr.println("Subject: " + CertTools.getSubjectDN(cert)); opstr.println("Issuer: " + CertTools.getIssuerDN(cert)); opstr.println(CertTools.BEGIN_CERTIFICATE); opstr.println(new String(certbuf)); opstr.println(CertTools.END_CERTIFICATE); } opstr.close(); byte[] ret = ostr.toByteArray(); return ret; }
From source file:cybervillains.ca.KeyStoreManager.java
/** * Creates, writes and loads a new keystore and CA root certificate. *///from ww w. j a va 2 s.co m protected void createKeystore() { Certificate signingCert = null; PrivateKey caPrivKey = null; if (_caCert == null || _caPrivKey == null) { try { log.debug("Keystore or signing cert & keypair not found. Generating..."); KeyPair caKeypair = getRSAKeyPair(); caPrivKey = caKeypair.getPrivate(); signingCert = CertificateCreator.createTypicalMasterCert(caKeypair); log.debug("Done generating signing cert"); log.debug(signingCert); _ks.load(null, _keystorepass); _ks.setCertificateEntry(_caCertAlias, signingCert); _ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new Certificate[] { signingCert }); File caKsFile = new File(root, _caPrivateKeystore); OutputStream os = new FileOutputStream(caKsFile); _ks.store(os, _keystorepass); log.debug("Wrote JKS keystore to: " + caKsFile.getAbsolutePath()); // also export a .cer that can be imported as a trusted root // to disable all warning dialogs for interception File signingCertFile = new File(root, EXPORTED_CERT_NAME); FileOutputStream cerOut = new FileOutputStream(signingCertFile); byte[] buf = signingCert.getEncoded(); log.debug("Wrote signing cert to: " + signingCertFile.getAbsolutePath()); cerOut.write(buf); cerOut.flush(); cerOut.close(); _caCert = (X509Certificate) signingCert; _caPrivKey = caPrivKey; } catch (Exception e) { log.error("Fatal error creating/storing keystore or signing cert.", e); throw new Error(e); } } else { log.debug("Successfully loaded keystore."); log.debug(_caCert); } }
From source file:org.wso2.carbon.appmgt.impl.token.JWTGenerator.java
/** * Helper method to add public certificate to JWT_HEADER to signature verification. *//from w ww . j a v a2 s . c o m * @param endUserName * @throws org.wso2.carbon.appmgt.api.AppManagementException */ private String addCertToHeader(String endUserName) throws AppManagementException { try { //get tenant domain String tenantDomain = MultitenantUtils.getTenantDomain(endUserName); //get tenantId int tenantId = getTenantId(endUserName); Certificate publicCert = null; if (!(publicCerts.containsKey(tenantId))) { //get tenant's key store manager AppManagerUtil.loadTenantRegistry(tenantId); KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); KeyStore keyStore = null; if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { //derive key store name String ksName = tenantDomain.trim().replace(".", "-"); String jksName = ksName + ".jks"; keyStore = tenantKSM.getKeyStore(jksName); publicCert = keyStore.getCertificate(tenantDomain); } else { keyStore = tenantKSM.getPrimaryKeyStore(); publicCert = tenantKSM.getDefaultPrimaryCertificate(); } if (publicCert != null) { publicCerts.put(tenantId, publicCert); } } else { publicCert = publicCerts.get(tenantId); } //generate the SHA-1 thumbprint of the certificate //TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization MessageDigest digestValue = MessageDigest.getInstance("SHA-1"); byte[] der = publicCert.getEncoded(); digestValue.update(der); byte[] digestInBytes = digestValue.digest(); String publicCertThumbprint = hexify(digestInBytes); String base64EncodedThumbPrint = Base64Utils.encode(publicCertThumbprint.getBytes()); //String headerWithCertThumb = JWT_HEADER.replaceAll("\\[1\\]", base64EncodedThumbPrint); //headerWithCertThumb = headerWithCertThumb.replaceAll("\\[2\\]", signatureAlgorithm); //return headerWithCertThumb; StringBuilder jwtHeader = new StringBuilder(); //Sample header //{"typ":"JWT", "alg":"SHA256withRSA", "x5t":"NmJmOGUxMzZlYjM2ZDRhNTZlYTA1YzdhZTRiOWE0NWI2M2JmOTc1ZA=="} //{"typ":"JWT", "alg":"[2]", "x5t":"[1]"} jwtHeader.append("{\"typ\":\"JWT\","); jwtHeader.append("\"alg\":\""); jwtHeader.append(signatureAlgorithm); jwtHeader.append("\","); jwtHeader.append("\"x5t\":\""); jwtHeader.append(base64EncodedThumbPrint); jwtHeader.append("\""); jwtHeader.append("}"); return jwtHeader.toString(); } catch (KeyStoreException e) { String error = "Error in obtaining tenant's keystore"; throw new AppManagementException(error); } catch (CertificateEncodingException e) { String error = "Error in generating public cert thumbprint"; throw new AppManagementException(error); } catch (NoSuchAlgorithmException e) { String error = "Error in generating public cert thumbprint"; throw new AppManagementException(error); } catch (Exception e) { String error = "Error in obtaining tenant's keystore"; throw new AppManagementException(error); } }
From source file:org.ejbca.util.CertTools.java
/** * Dumps a certificate (cvc or x.509) to string format, suitable for manual inspection/debugging. * * @param cert Certificate//from w w w . j a va 2 s . co m * * @return String with cvc or asn.1 dump. */ public static String dumpCertificateAsString(final Certificate cert) { String ret = null; if (cert instanceof X509Certificate) { try { final Certificate c = getCertfromByteArray(cert.getEncoded()); ret = c.toString(); // ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(cert.getEncoded())); // DERObject obj = ais.readObject(); // ret = ASN1Dump.dumpAsString(obj); } catch (CertificateException e) { ret = e.getMessage(); } } else if (StringUtils.equals(cert.getType(), "CVC")) { final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; final CVCObject obj = cvccert.getCVCertificate(); ret = obj.getAsText(""); } else { throw new IllegalArgumentException( "dumpCertificateAsString: Certificate of type " + cert.getType() + " is not implemented"); } return ret; }
From source file:org.cesecore.certificates.ca.X509CA.java
@Override public void createOrRemoveLinkCertificate(final CryptoToken cryptoToken, final boolean createLinkCertificate, final CertificateProfile certProfile) throws CryptoTokenOfflineException { byte[] ret = null; if (createLinkCertificate) { try {//from w ww. ja va 2 s .c o m final CAToken catoken = getCAToken(); // Check if the input was a CA certificate, which is the same CA as this. If all is true we should create a NewWithOld link-certificate final X509Certificate currentCaCert = (X509Certificate) getCACertificate(); if (log.isDebugEnabled()) { log.debug("We will create a link certificate."); } final X509CAInfo info = (X509CAInfo) getCAInfo(); final EndEntityInformation cadata = new EndEntityInformation("nobody", info.getSubjectDN(), info.getSubjectDN().hashCode(), info.getSubjectAltName(), null, 0, new EndEntityType(EndEntityTypes.INVALID), 0, info.getCertificateProfileId(), null, null, 0, 0, null); final PublicKey previousCaPublicKey = cryptoToken .getPublicKey(catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS)); final PrivateKey previousCaPrivateKey = cryptoToken.getPrivateKey( catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS)); final String provider = cryptoToken.getSignProviderName(); // The sequence is ignored later, but we fetch the same previous for now to do this the same way as for CVC.. final String ignoredKeySequence = catoken.getProperties() .getProperty(CATokenConstants.PREVIOUS_SEQUENCE_PROPERTY); final Certificate retcert = generateCertificate(cadata, null, currentCaCert.getPublicKey(), -1, currentCaCert.getNotBefore(), currentCaCert.getNotAfter(), certProfile, null, ignoredKeySequence, previousCaPublicKey, previousCaPrivateKey, provider, null); log.info(intres.getLocalizedMessage("cvc.info.createlinkcert", cadata.getDN(), cadata.getDN())); ret = retcert.getEncoded(); } catch (CryptoTokenOfflineException e) { throw e; } catch (Exception e) { throw new RuntimeException("Bad CV CA certificate.", e); } } updateLatestLinkCertificate(ret); }
From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java
License:asdf
@Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public boolean updateCertificateOnly(AuthenticationToken authenticationToken, Certificate certificate) { final String fingerprint = CertTools.getFingerprintAsString(certificate); final CertificateData certificateData = CertificateData.findByFingerprint(entityManager, fingerprint); if (certificateData == null || certificateData.getCertificate(entityManager) != null) { return false; }// w w w . j ava 2 s . c o m final boolean useBase64CertTable = CesecoreConfiguration.useBase64CertTable(); if (useBase64CertTable) { // use special table for encoded data if told so. entityManager.persist(new Base64CertData(certificate)); } else { try { certificateData.setBase64Cert(new String(Base64.encode(certificate.getEncoded()))); } catch (CertificateEncodingException e) { log.error("Failed to encode certificate for fingerprint " + fingerprint, e); return false; } } final String username = certificateData.getUsername(); final String serialNo = CertTools.getSerialNumberAsString(certificate); final String msg = INTRES.getLocalizedMessage("store.storecert", username, fingerprint, certificateData.getSubjectDN(), certificateData.getIssuerDN(), serialNo); Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("msg", msg); final String caId = String.valueOf(CertTools.getIssuerDN(certificate).hashCode()); logSession.log(EventTypes.CERT_STORED, EventStatus.SUCCESS, ModuleTypes.CERTIFICATE, ServiceTypes.CORE, authenticationToken.toString(), caId, serialNo, username, details); return true; }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
/** * Checks for an existing certificate to use for secure communication between the server and * client. If no certficate exists, this will generate a new one. * //from w w w . j ava2 s. c o m */ private void generateDefaultCertificate(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception { final String certificateAlias = "mirthconnect"; if (!keyStore.containsAlias(certificateAlias)) { // Common CA and SSL cert attributes Date startDate = new Date(); // time from which certificate is valid Date expiryDate = DateUtils.addYears(startDate, 50); // time after which certificate is not valid KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", provider); keyPairGenerator.initialize(2048); KeyPair caKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for CA cert using provider: " + provider.getName()); // Generate CA cert X500Name caSubjectName = new X500Name("CN=Mirth Connect Certificate Authority"); SubjectPublicKeyInfo caSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(caKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(caSubjectName, BigInteger.ONE, startDate, expiryDate, caSubjectName, caSubjectKey); certBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.basicConstraints, true, new BasicConstraints(0)); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate caCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(certBuilder.build(sigGen)); // Generate SSL cert KeyPair sslKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for SSL cert using provider: " + provider.getName()); X500Name sslSubjectName = new X500Name("CN=mirth-connect"); SubjectPublicKeyInfo sslSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(sslKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder sslCertBuilder = new X509v3CertificateBuilder(caSubjectName, new BigInteger(50, new SecureRandom()), startDate, expiryDate, sslSubjectName, sslSubjectKey); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(caCert.getEncoded())); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(sslKeyPair.getPublic().getEncoded())); sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate sslCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(sslCertBuilder.build(sigGen)); logger.debug("generated new certificate with serial number: " + ((X509Certificate) sslCert).getSerialNumber()); // add the generated SSL cert to the keystore using the key password keyStore.setKeyEntry(certificateAlias, sslKeyPair.getPrivate(), keyPassword, new Certificate[] { sslCert }); } else { logger.debug("found certificate in keystore"); } }
From source file:org.ejbca.util.CertTools.java
/** * Gets subject or issuer DN in the format we are sure about (BouncyCastle),supporting UTF8. * * @param cert X509Certificate/*w ww . j a v a 2s.co m*/ * @param which 1 = subjectDN, anything else = issuerDN * * @return String containing the DN. */ private static String getDN(Certificate cert, int which) { /*if (log.isTraceEnabled()) { log.trace(">getDN("+which+")"); }*/ String ret = null; if (cert == null) { return null; } if (cert instanceof X509Certificate) { // cert.getType=X.509 try { CertificateFactory cf = CertTools.getCertificateFactory(); X509Certificate x509cert = (X509Certificate) cf .generateCertificate(new ByteArrayInputStream(cert.getEncoded())); //log.debug("Created certificate of class: " + x509cert.getClass().getName()); String dn = null; if (which == 1) { dn = x509cert.getSubjectDN().toString(); } else { dn = x509cert.getIssuerDN().toString(); } ret = stringToBCDNString(dn); } catch (CertificateException ce) { log.info("Could not get DN from X509Certificate. " + ce.getMessage()); log.debug("", ce); return null; } } else if (StringUtils.equals(cert.getType(), "CVC")) { CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { ReferenceField rf = null; if (which == 1) { rf = cvccert.getCVCertificate().getCertificateBody().getHolderReference(); } else { rf = cvccert.getCVCertificate().getCertificateBody().getAuthorityReference(); } if (rf != null) { // Construct a "fake" DN which can be used in EJBCA // Use only mnemonic and country, since sequence is more of a serialnumber than a DN part String dn = ""; // if (rf.getSequence() != null) { // dn += "SERIALNUMBER="+rf.getSequence(); // } if (rf.getMnemonic() != null) { if (StringUtils.isNotEmpty(dn)) { dn += ", "; } dn += "CN=" + rf.getMnemonic(); } if (rf.getCountry() != null) { if (StringUtils.isNotEmpty(dn)) { dn += ", "; } dn += "C=" + rf.getCountry(); } ret = stringToBCDNString(dn); } } catch (NoSuchFieldException e) { log.error("NoSuchFieldException: ", e); return null; } } /*if (log.isTraceEnabled()) { log.trace("<getDN("+which+"):"+dn); }*/ return ret; }
From source file:org.cesecore.util.CertTools.java
/** * Converts a regular array of certificates into an ArrayList, using the provided provided. * //from w w w . j av a2s . c o m * @param certs Certificate[] of certificates to convert * @param provider provider for example "SUN" or "BC", use null for the default provider (BC) * @return An ArrayList of certificates in the same order as the passed in array * @throws NoSuchProviderException * @throws CertificateException */ public static Collection<Certificate> getCertCollectionFromArray(Certificate[] certs, String provider) throws CertificateException, NoSuchProviderException { if (log.isTraceEnabled()) { log.trace(">getCertCollectionFromArray: " + provider); } ArrayList<Certificate> ret = new ArrayList<Certificate>(); String prov = provider; if (prov == null) { prov = "BC"; } for (int i = 0; i < certs.length; i++) { Certificate cert = certs[i]; Certificate newcert = getCertfromByteArray(cert.getEncoded(), prov); ret.add(newcert); } if (log.isTraceEnabled()) { log.trace("<getCertCollectionFromArray: " + ret.size()); } return ret; }