List of usage examples for java.security.cert X509Certificate getEncoded
public abstract byte[] getEncoded() throws CertificateEncodingException;
From source file:be.fedict.eid.applet.service.signer.facets.XAdESSignatureFacet.java
/** * Gives back the JAXB CertID data structure. * /*from w ww. j a v a 2s. c o m*/ * @param certificate * @param xadesObjectFactory * @param xmldsigObjectFactory * @param digestAlgorithm * @return */ public static CertIDType getCertID(X509Certificate certificate, ObjectFactory xadesObjectFactory, be.fedict.eid.applet.service.signer.jaxb.xmldsig.ObjectFactory xmldsigObjectFactory, DigestAlgo digestAlgorithm, boolean issuerNameNoReverseOrder) { CertIDType certId = xadesObjectFactory.createCertIDType(); X509IssuerSerialType issuerSerial = xmldsigObjectFactory.createX509IssuerSerialType(); certId.setIssuerSerial(issuerSerial); String issuerName; if (issuerNameNoReverseOrder) { try { /* * Make sure the DN is encoded using the same order as present * within the certificate. This is an Office2010 work-around. * Should be reverted back. * * XXX: not correct according to RFC 4514. */ issuerName = PrincipalUtil.getIssuerX509Principal(certificate).getName().replace(",", ", "); } catch (CertificateEncodingException e) { throw new RuntimeException("cert encoding error: " + e.getMessage(), e); } } else { issuerName = certificate.getIssuerX500Principal().toString(); } issuerSerial.setX509IssuerName(issuerName); issuerSerial.setX509SerialNumber(certificate.getSerialNumber()); byte[] encodedCertificate; try { encodedCertificate = certificate.getEncoded(); } catch (CertificateEncodingException e) { throw new RuntimeException("certificate encoding error: " + e.getMessage(), e); } DigestAlgAndValueType certDigest = getDigestAlgAndValue(encodedCertificate, xadesObjectFactory, xmldsigObjectFactory, digestAlgorithm); certId.setCertDigest(certDigest); return certId; }
From source file:be.fedict.eid.dss.webapp.ProtocolEntryServlet.java
private boolean isValid(RPEntity rp, DSSRequest dssRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { LOG.debug("found RP: " + rp.getName()); if (rp.isRequestSigningRequired()) { if (null == dssRequest.getServiceCertificateChain()) { error(request, response, "Request was not signed, which is required for this SP!"); return false; }/*from w w w. j a v a 2 s.c o m*/ } if (null != dssRequest.getServiceCertificateChain()) { X509Certificate serviceCertificate = dssRequest.getServiceCertificateChain().get(0); if (null != serviceCertificate && null != rp.getEncodedCertificate()) { LOG.debug("verify service signature certificate fingerprint against " + "RP's configuration..."); // verify fingerprint // TODO: for now first using fingerprint of value of leaf // certificate, expand later for service key rollover scenarios. try { String rpFingerprint = DigestUtils.shaHex(rp.getEncodedCertificate()); String requestFingerPrint = DigestUtils.shaHex(serviceCertificate.getEncoded()); if (!rpFingerprint.equals(requestFingerPrint)) { error(request, response, "Request was not signed with the correct keystore!"); return false; } } catch (CertificateEncodingException e) { return false; } } } else { LOG.debug("No signature and signature is not required, valid..."); } request.getSession().setAttribute(View.RP_SESSION_ATTRIBUTE, rp); return true; }
From source file:com.sun.identity.security.cert.AMCRLStore.java
/** * It checks whether the certificate has CRLDistributionPointsExtension * or not. If there is, it returns the extension. * @param X509Certificate certificate/*from w ww .j a v a2 s. com*/ */ private CRLDistributionPointsExtension getCRLDPExt(X509Certificate certificate) { CRLDistributionPointsExtension dpExt = null; CertificateExtensions exts = null; try { X509CertImpl certImpl = new X509CertImpl(certificate.getEncoded()); dpExt = certImpl.getCRLDistributionPointsExtension(); } catch (Exception e) { debug.error("Error finding CRL distribution Point configured: ", e); } return dpExt; }
From source file:ee.sk.digidoc.SignedDoc.java
/** * Writes the cert from a file// w ww . ja v a 2 s . com * @param cert certificate * @param certFile certificates file name * @return true for success */ public static boolean writeCertificate(X509Certificate cert, File certFile) throws DigiDocException { FileOutputStream fos = null; try { fos = new FileOutputStream(certFile); fos.write(PEM_HDR1.getBytes()); fos.write(Base64Util.encode(cert.getEncoded()).getBytes()); fos.write(PEM_HDR2.getBytes()); fos.close(); fos = null; //byte[] data = readFile(certFile); //cert = readCertificate(data); } catch (Exception ex) { DigiDocException.handleException(ex, DigiDocException.ERR_READ_FILE); } finally { if (fos != null) { try { fos.close(); } catch (Exception ex2) { m_logger.error("Error closing streams: " + ex2); } } } return false; }
From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java
/** * Returns a {@code Certificate} with the received data. * * @param keypair//from w ww .j a v a 2 s . c o m * key pair for the certificate * @param issuer * issuer for the certificate * @return a {@code Certificate} with the received data * @throws IOException * if there is an I/O or format problem with the certificate * data * @throws OperatorCreationException * if there was a problem creation a bouncy castle operator * @throws CertificateException * if any of the certificates in the keystore could not be * loaded * @throws InvalidKeyException * if there was a problem with the key * @throws NoSuchAlgorithmException * if an algorithm required to create the key store could not be * found * @throws NoSuchProviderException * if a required provider is missing * @throws SignatureException * if any problem occurs while signing the certificate */ private final Certificate getCertificate(final KeyPair keypair, final String issuer) throws IOException, OperatorCreationException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException { final X509v3CertificateBuilder builder; // Certificate builder final X509Certificate certificate; // Certificate // Generates the certificate builder builder = getCertificateBuilder(keypair.getPublic(), issuer); // Generates the signed certificate certificate = getSignedCertificate(builder, keypair.getPrivate()); // Verifies the certificate certificate.checkValidity(getCurrentDate()); certificate.verify(keypair.getPublic()); LOGGER.debug("Created certificate of type {} with encoded value {}", certificate.getType(), Arrays.asList(certificate.getEncoded())); LOGGER.debug("Created certificate with public key:{}", certificate.getPublicKey()); return certificate; }
From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.wstep.impl.CertificateEnrollmentServiceImpl.java
/** * This method prepares the wap-provisioning file by including relevant certificates etc * * @param binarySecurityToken - CSR from device * @param certPropertyList - property list for signed certificate * @param wapProvisioningFilePath - File path of wap-provisioning file * @return - base64 encoded final wap-provisioning file * @throws CertificateGenerationException * @throws XMLFileOperationException/* w ww .j av a2s .c o m*/ */ public String prepareWapProvisioningXML(String binarySecurityToken, List certPropertyList, String wapProvisioningFilePath) throws CertificateGenerationException, XMLFileOperationException { byte[] DERByteArray = javax.xml.bind.DatatypeConverter.parseBase64Binary(binarySecurityToken); PKCS10CertificationRequest certificationRequest; try { certificationRequest = new PKCS10CertificationRequest(DERByteArray); } catch (IOException e) { throw new CertificateGenerationException("CSR cannot be recovered.", e); } JcaPKCS10CertificationRequest CSRRequest = new JcaPKCS10CertificationRequest(certificationRequest); X509Certificate signedCertificate = CertificateSigningService.signCSR(CSRRequest, privateKey, rootCACertificate, certPropertyList); BASE64Encoder base64Encoder = new BASE64Encoder(); String rootCertEncodedString; try { rootCertEncodedString = base64Encoder.encode(rootCACertificate.getEncoded()); } catch (CertificateEncodingException e) { throw new CertificateGenerationException("CA certificate cannot be encoded.", e); } String signedCertEncodedString; try { signedCertEncodedString = base64Encoder.encode(signedCertificate.getEncoded()); } catch (CertificateEncodingException e) { throw new CertificateGenerationException("Singed certificate cannot be encoded.", e); } DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; String wapProvisioningString; try { builder = domFactory.newDocumentBuilder(); Document document = builder.parse(wapProvisioningFilePath); NodeList wapParm = document.getElementsByTagName(Constants.CertificateEnrollment.PARM); Node CACertificatePosition = wapParm.item(CA_CERTIFICATE_POSITION); //Adding SHA1 CA certificate finger print to wap-provisioning xml. CACertificatePosition.getParentNode().getAttributes().getNamedItem(Constants.CertificateEnrollment.TYPE) .setTextContent( String.valueOf(DigestUtils.sha1Hex(rootCACertificate.getEncoded())).toUpperCase()); //Adding encoded CA certificate to wap-provisioning file after removing new line // characters. NamedNodeMap rootCertAttributes = CACertificatePosition.getAttributes(); Node rootCertNode = rootCertAttributes.getNamedItem(Constants.CertificateEnrollment.VALUE); rootCertEncodedString = rootCertEncodedString.replaceAll("\n", ""); rootCertNode.setTextContent(rootCertEncodedString); if (logger.isDebugEnabled()) { logger.debug("Root certificate:" + rootCertEncodedString); } Node signedCertificatePosition = wapParm.item(SIGNED_CERTIFICATE_POSITION); //Adding SHA1 signed certificate finger print to wap-provisioning xml. signedCertificatePosition.getParentNode().getAttributes() .getNamedItem(Constants.CertificateEnrollment.TYPE).setTextContent( String.valueOf(DigestUtils.sha1Hex(signedCertificate.getEncoded())).toUpperCase()); //Adding encoded signed certificate to wap-provisioning file after removing new line // characters. NamedNodeMap clientCertAttributes = signedCertificatePosition.getAttributes(); Node clientEncodedNode = clientCertAttributes.getNamedItem(Constants.CertificateEnrollment.VALUE); signedCertEncodedString = signedCertEncodedString.replaceAll("\n", ""); clientEncodedNode.setTextContent(signedCertEncodedString); if (logger.isDebugEnabled()) { logger.debug("Signed certificate:" + signedCertEncodedString); } wapProvisioningString = convertDocumentToString(document); //Generic exception is caught here as there is no need of taking different actions for // different exceptions. } catch (Exception e) { throw new XMLFileOperationException("Problem occurred with wap-provisioning.xml file.", e); } String encodedWap = base64Encoder.encode(wapProvisioningString.getBytes()); return encodedWap; }
From source file:org.apache.stratos.keystore.mgt.KeyStoreGenerator.java
/** * Persist the keystore in the gov.registry * * @param keyStore created Keystore of the tenant * @param PKCertificate pub. key of the tenant * @throws KeyStoreMgtException Exception when storing the keystore in the registry *///from w ww.ja va 2 s. c om private void persistKeyStore(KeyStore keyStore, X509Certificate PKCertificate) throws KeyStoreMgtException { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); keyStore.store(outputStream, password.toCharArray()); outputStream.flush(); outputStream.close(); String keyStoreName = generateKSNameFromDomainName(); // Use the keystore using the keystore admin KeyStoreAdmin keystoreAdmin = new KeyStoreAdmin(tenantId, govRegistry); keystoreAdmin.addKeyStore(outputStream.toByteArray(), keyStoreName, password, " ", "JKS", password); //Create the pub. key resource Resource pubKeyResource = govRegistry.newResource(); pubKeyResource.setContent(PKCertificate.getEncoded()); pubKeyResource.addProperty(SecurityConstants.PROP_TENANT_PUB_KEY_FILE_NAME_APPENDER, generatePubKeyFileNameAppender()); govRegistry.put(RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE, pubKeyResource); //associate the public key with the keystore govRegistry.addAssociation(RegistryResources.SecurityManagement.KEY_STORES + "/" + keyStoreName, RegistryResources.SecurityManagement.TENANT_PUBKEY_RESOURCE, SecurityConstants.ASSOCIATION_TENANT_KS_PUB_KEY); } catch (RegistryException e) { String msg = "Error when writing the keystore/pub.cert to registry"; log.error(msg, e); throw new KeyStoreMgtException(msg, e); } catch (Exception e) { String msg = "Error when processing keystore/pub. cert to be stored in registry"; log.error(msg, e); throw new KeyStoreMgtException(msg, e); } }
From source file:org.signserver.module.mrtdsodsigner.MRTDSODSigner.java
private void verifySignatureAndChain(final SODFile sod, final Collection<Certificate> chain) throws TigerSignerException { try {// www .j a v a 2 s . c o m if (log.isDebugEnabled()) { final StringBuilder buff = new StringBuilder(); buff.append("Verifying SOD signed by DS with issuer: "); buff.append(sod.toString()); log.debug(buff.toString()); } // Get Signer certificate from SOD final X509Certificate sodCert = sod.getDocSigningCertificate(); // We need a Bouncy Castle certificate so reconstruct it final CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC"); final X509Certificate signerCert = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(sodCert.getEncoded())); // Verify the SOD signature using certificate from SOD final boolean consistent = sod.checkDocSignature(signerCert); if (!consistent) { log.error("Failed to verify the SOD we signed ourselves."); log.error("Cert: " + signerCert); log.error("SOD: " + sod); throw new TigerSignerException("GeneralSecurityException : Signature not consistent"); } // Find the issuer certificate from the configured chain final X509Certificate issuerCert = (chain == null ? null : findIssuerCert(chain, signerCert)); if (issuerCert == null) { log.error("Failed to verify certificate chain"); log.error("Cert: " + signerCert); log.error("SOD Cert: " + signerCert); log.error("Chain: " + chain); throw new TigerSignerException("GeneralSecurityException :Issuer of cert not in chain."); } // Verify the signer certificate using the issuer from the chain signerCert.verify(issuerCert.getPublicKey()); } catch (IOException e) { log.error("Getting signer certificate from SOD failed", e); throw new TigerSignerException("GeneralSecurityException : Getting signer certificate from SOD failed", e); } catch (CertificateEncodingException e) { throw new TigerSignerException("CertificateEncodingException : ", e); } catch (CertificateException e) { throw new TigerSignerException("CertificateException : ", e); } catch (NoSuchAlgorithmException e) { throw new TigerSignerException("NoSuchAlgorithmException : ", e); } catch (InvalidKeyException e) { throw new TigerSignerException("InvalidKeyException : ", e); } catch (SignatureException e) { throw new TigerSignerException("SignatureException : ", e); } catch (NoSuchProviderException e) { throw new TigerSignerException("NoSuchProviderException : ", e); } catch (GeneralSecurityException e) { throw new TigerSignerException("GeneralSecurityException : ", e); } }
From source file:org.aselect.server.request.handler.xsaml20.Saml20_Metadata.java
/** * Read meta data public key cert./*ww w. jav a 2 s. c o m*/ * * @param sWorkingDir * the s working dir * @throws ASelectException * the a select exception */ private void readMetaDataPublicKeyCert(String sWorkingDir) throws ASelectException { String sMethod = "readMetaDataPublicKeyCert"; try { StringBuffer sbKeystoreLocation = new StringBuffer(sWorkingDir); sbKeystoreLocation.append(File.separator); sbKeystoreLocation.append("aselectserver"); sbKeystoreLocation.append(File.separator); sbKeystoreLocation.append("keystores"); sbKeystoreLocation.append(File.separator); sbKeystoreLocation.append(PUBLIC_KEYSTORE_NAME); _systemLogger.log(Level.INFO, MODULE, sMethod, "Read:" + sbKeystoreLocation); File fKeystore = new File(sbKeystoreLocation.toString()); if (!fKeystore.exists()) { StringBuffer sbError = new StringBuffer("Keystore cannot be found: "); sbError.append(sbKeystoreLocation.toString()); _systemLogger.log(Level.WARNING, MODULE, sMethod, sbError.toString()); throw new ASelectException(Errors.ERROR_ASELECT_NOT_FOUND); } KeyStore ksASelect = KeyStore.getInstance("JKS"); ksASelect.load(new FileInputStream(sbKeystoreLocation.toString()), null); Enumeration<?> enumAliases = ksASelect.aliases(); while (enumAliases.hasMoreElements()) { String sAlias = (String) enumAliases.nextElement(); sAlias = sAlias.toLowerCase(); if (sAlias.equals(getPublicKeyAlias())) { // server_id A-Select IdP java.security.cert.X509Certificate x509Cert = (java.security.cert.X509Certificate) ksASelect .getCertificate(sAlias); String encodedCert = new String(Base64.encodeBase64(x509Cert.getEncoded())); _systemLogger.log(Level.INFO, MODULE, sMethod, "Found public key alias for : " + getPublicKeyAlias() + " retrieved encoded signing certificate"); setSigningCertificate(encodedCert); } } if (getSigningCertificate() == null) { _systemLogger.log(Level.WARNING, MODULE, sMethod, "No alias found for idp public key with name : " + getPublicKeyAlias()); throw new ASelectException(Errors.ERROR_ASELECT_CONFIG_ERROR); } } catch (Exception e) { StringBuffer sbError = new StringBuffer(" Error loading public keys from directory: '"); sbError.append(sWorkingDir); sbError.append("'"); _systemLogger.log(Level.WARNING, MODULE, sMethod, sbError.toString(), e); throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e); } }
From source file:org.texai.x509.X509Utils.java
/** Makes a canonical X.509 certificate by serializing it to bytes and reconsituting it. This ensures * that all issuer and subject names have no space following the commas. // ww w. ja v a 2s . co m * @param x509Certificate the input certificate * @return the canonical certificate */ public static X509Certificate makeCanonicalX509Certificate(final X509Certificate x509Certificate) { //Preconditions assert x509Certificate != null : "x509Certificate must not be null"; X509Certificate canonicalX509Certificate; try { final byte[] certificateBytes = x509Certificate.getEncoded(); final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(certificateBytes); canonicalX509Certificate = readX509Certificate(byteArrayInputStream); } catch (CertificateException | NoSuchProviderException ex) { throw new TexaiException(ex); } LOGGER.debug("x509Certificate (" + x509Certificate.getClass().getName() + ")...\n" + x509Certificate + "\ncanonicalX509Certificate(" + canonicalX509Certificate.getClass().getName() + ")...\n" + canonicalX509Certificate); //Postconditions assert canonicalX509Certificate.equals( x509Certificate) : "canonicalX509Certificate must equal x509Certificate,\ncanonicalX509Certificate...\n" + canonicalX509Certificate + "\nx509Certificate...\n" + x509Certificate; return canonicalX509Certificate; }