public DEPExportFormat exportDEP() { try { // prepare data structures for DEP export // DEP exports are grouped according to the used signature certificate (CURRENTLY NOT USED IN // THE DEMO) HashMap<String, List<ReceiptPackage>> certificateToReceiptMap = new HashMap<>(); for (ReceiptPackage receiptPackage : receiptPackages) { X509Certificate signingCertificate = receiptPackage.getSigningCertificate(); List<ReceiptPackage> receiptPackagesForSignatureCertificate = certificateToReceiptMap.get(signingCertificate.getSerialNumber() + ""); if (receiptPackagesForSignatureCertificate == null) { receiptPackagesForSignatureCertificate = new ArrayList<>(); certificateToReceiptMap.put( signingCertificate.getSerialNumber() + "", receiptPackagesForSignatureCertificate); } receiptPackagesForSignatureCertificate.add(receiptPackage); } // create data structure for export format DEPExportFormat depExportFormat = new DEPExportFormat(); DEPBelegDump[] belegDump = new DEPBelegDump[certificateToReceiptMap.keySet().size()]; // store receipts in export format int dumpIndex = 0; for (List<ReceiptPackage> signedReceipts : certificateToReceiptMap.values()) { belegDump[dumpIndex] = new DEPBelegDump(); depExportFormat.setBelegPackage(belegDump); List<String> receiptsInJWSCompactRepresentation = new ArrayList<>(); for (ReceiptPackage receiptPackage : signedReceipts) { receiptsInJWSCompactRepresentation.add(receiptPackage.getJwsCompactRepresentation()); } belegDump[dumpIndex].setBelegeDaten( receiptsInJWSCompactRepresentation.toArray( new String[receiptsInJWSCompactRepresentation.size()])); String base64EncodedSignatureCertificate = CashBoxUtils.base64Encode( signedReceipts.get(0).getSigningCertificate().getEncoded(), false); belegDump[dumpIndex].setSignatureCertificate(base64EncodedSignatureCertificate); List<X509Certificate> base64EncodedCertificateChain = signedReceipts.get(0).getCertificateChain(); String[] certificateChain = new String[base64EncodedCertificateChain.size()]; for (int i = 0; i < base64EncodedCertificateChain.size(); i++) { X509Certificate base64EncodedChainCertificate = base64EncodedCertificateChain.get(i); certificateChain[i] = CashBoxUtils.base64Encode(base64EncodedChainCertificate.getEncoded(), false); } belegDump[dumpIndex].setCertificateChain(certificateChain); dumpIndex++; } return depExportFormat; } catch (CertificateEncodingException e) { e.printStackTrace(); } return null; }
public int compare(Object o1, Object o2) { X509Certificate c1 = (X509Certificate) o1; X509Certificate c2 = (X509Certificate) o2; if (c1 == c2) // this deals with case where both are null { return 0; } if (c1 == null) // non-null is always bigger than null { return -1; } if (c2 == null) { return 1; } if (c1.equals(c2)) { return 0; } Date d1 = c1.getNotAfter(); Date d2 = c2.getNotAfter(); int c = d1.compareTo(d2); if (c == 0) { String s1 = JavaImpl.getSubjectX500(c1); String s2 = JavaImpl.getSubjectX500(c2); c = s1.compareTo(s2); if (c == 0) { s1 = JavaImpl.getIssuerX500(c1); s2 = JavaImpl.getIssuerX500(c2); c = s1.compareTo(s2); if (c == 0) { BigInteger big1 = c1.getSerialNumber(); BigInteger big2 = c2.getSerialNumber(); c = big1.compareTo(big2); if (c == 0) { try { byte[] b1 = c1.getEncoded(); byte[] b2 = c2.getEncoded(); int len1 = b1.length; int len2 = b2.length; int i = 0; for (; i < len1 && i < len2; i++) { c = ((int) b1[i]) - ((int) b2[i]); if (c != 0) { break; } } if (c == 0) { c = b1.length - b2.length; } } catch (CertificateEncodingException cee) { // I give up. They can be equal if they // really want to be this badly. c = 0; } } } } } return c; }
/** check that client's cert is listed in the user certs file */ private boolean checkUser(String userID, X509Certificate cert) { Set<BigInteger> numSet = certsMap.get(userID); if (numSet == null) { LOG.info("User " + userID + " is not configured in the user certs file"); return false; } if (!numSet.contains(cert.getSerialNumber())) { LOG.info( "Cert with serial number " + cert.getSerialNumber() + " is not listed for user " + userID); return false; } return true; }
public boolean match(Certificate cert) { if (!(cert instanceof X509Certificate)) { return false; } X509Certificate x509Cert = (X509Certificate) cert; if (form instanceof V2Form) { V2Form issuer = (V2Form) form; if (issuer.getBaseCertificateID() != null) { return issuer .getBaseCertificateID() .getSerial() .getValue() .equals(x509Cert.getSerialNumber()) && matchesDN( x509Cert.getIssuerX500Principal(), issuer.getBaseCertificateID().getIssuer()); } GeneralNames name = issuer.getIssuerName(); if (matchesDN(x509Cert.getSubjectX500Principal(), name)) { return true; } } else { GeneralNames name = (GeneralNames) form; if (matchesDN(x509Cert.getSubjectX500Principal(), name)) { return true; } } return false; }
private void parseCert() { try { FileInputStream fis = new FileInputStream("e:\\rongyifu.der"); CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate c = (X509Certificate) cf.generateCertificate(fis); System.out.println("Certficate for " + c.getSubjectDN().getName()); System.out.println("Generated with " + c.getSigAlgName()); System.out.println("== " + c.getSubjectDN().toString()); String publicKey = Base64.encode(c.getPublicKey().getEncoded()); System.out.println("publicKey=" + publicKey); // Map<String, String> map = parseSubjectDN(c.getSubjectDN().toString()); // System.out.println("map: "+map); // String notBefore =c.getNotBefore().toString();//得到开始有效日期 // String notAfter = c.getNotAfter().toString();//得到截止日期 String serialNumber = c.getSerialNumber().toString(16); // 得到序列号 String dn = c.getIssuerDN().getName(); // 得到发行者名 String sigAlgName = c.getSigAlgName(); // 得到签名算法 String algorithm = c.getPublicKey().getAlgorithm(); // 得到公钥算法 SimpleDateFormat intSDF = new SimpleDateFormat("yyyyMMdd"); System.out.println("notBefore=" + intSDF.format(c.getNotBefore())); System.out.println("notAfter=" + intSDF.format(c.getNotAfter())); System.out.println("serialNumber=" + serialNumber); System.out.println("dn=" + dn); System.out.println("sigAlgName=" + sigAlgName); System.out.println("algorithm=" + algorithm); fis.close(); } catch (Exception ex) { ex.printStackTrace(); } }
/** @see de.willuhn.datasource.GenericObject#getAttribute(java.lang.String) */ public Object getAttribute(String arg0) throws RemoteException { if ("name".equals(arg0)) { String s = myCert.getSubject().getAttribute(Principal.COMMON_NAME); if (s == null || s.length() == 0) { s = this.cert.getSubjectDN().getName(); if (s != null && s.length() > 40) s = s.substring(0, 39) + "..."; return s; } return s; } if ("issuer".equals(arg0)) { String s = myCert.getIssuer().getAttribute(Principal.COMMON_NAME); if (s == null || s.length() == 0) s = myCert.getIssuer().getAttribute(Principal.ORGANIZATION); if (s == null || s.length() == 0) { s = this.cert.getIssuerDN().getName(); if (s != null && s.length() > 40) s = s.substring(0, 39) + "..."; } return s; } if ("serial".equals(arg0)) return cert.getSerialNumber().toString(); if ("organization".equals(arg0)) return myCert.getSubject().getAttribute(Principal.ORGANIZATION); if ("ou".equals(arg0)) return myCert.getSubject().getAttribute(Principal.ORGANIZATIONAL_UNIT); if ("datefrom".equals(arg0)) return cert.getNotBefore(); if ("dateto".equals(arg0)) return cert.getNotAfter(); return null; }
protected PropertyDataObject generate( Collection<X509Certificate> certs, BaseCertRefsData certRefsData, QualifyingProperty prop) throws PropertyDataGenerationException { if (null == certs) { throw new PropertyDataGenerationException(prop, "certificates not provided"); } try { String digestAlgUri = this.algorithmsProvider.getDigestAlgorithmForReferenceProperties(); MessageDigest messageDigest = this.messageDigestProvider.getEngine(digestAlgUri); for (X509Certificate cert : certs) { // "DigestValue contains the base-64 encoded value of the digest // computed on the DER-encoded certificate." // The base-64 encoding is done by JAXB with the configured // adapter (Base64XmlAdapter). // For X509 certificates the encoded form return by getEncoded is DER. byte[] digestValue = messageDigest.digest(cert.getEncoded()); certRefsData.addCertRef( new CertRef( cert.getIssuerX500Principal().getName(), cert.getSerialNumber(), digestAlgUri, digestValue)); } return certRefsData; } catch (UnsupportedAlgorithmException ex) { throw new PropertyDataGenerationException(prop, ex.getMessage(), ex); } catch (CertificateEncodingException ex) { throw new PropertyDataGenerationException(prop, "cannot get encoded certificate", ex); } }
public String getAliasFromCertificate(Certificate cer) throws KeyStoreException { X509Certificate xcer = (X509Certificate) cer, auxCer = null; String auxAlias = null; Enumeration<String> e = _mscapi.aliases(); while (e.hasMoreElements()) { auxAlias = (String) e.nextElement(); auxCer = (X509Certificate) _mscapi.getCertificate(auxAlias); if ((auxCer.getIssuerDN().equals(xcer.getIssuerDN())) && (auxCer.getSerialNumber().equals(xcer.getSerialNumber()))) { return auxAlias; } } return null; }
private static ASN1Sequence fromCertificate(X509Certificate certificate) throws CertificateParsingException { try { if (certificate.getVersion() != 3) { GeneralName genName = new GeneralName(PrincipalUtil.getIssuerX509Principal(certificate)); SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(certificate.getPublicKey().getEncoded()).readObject()); return (ASN1Sequence) new AuthorityKeyIdentifier( info, new GeneralNames(genName), certificate.getSerialNumber()) .toASN1Object(); } else { GeneralName genName = new GeneralName(PrincipalUtil.getIssuerX509Principal(certificate)); byte[] ext = certificate.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId()); if (ext != null) { ASN1OctetString str = (ASN1OctetString) X509ExtensionUtil.fromExtensionValue(ext); return (ASN1Sequence) new AuthorityKeyIdentifier( str.getOctets(), new GeneralNames(genName), certificate.getSerialNumber()) .toASN1Object(); } else { SubjectPublicKeyInfo info = new SubjectPublicKeyInfo( (ASN1Sequence) new ASN1InputStream(certificate.getPublicKey().getEncoded()).readObject()); return (ASN1Sequence) new AuthorityKeyIdentifier( info, new GeneralNames(genName), certificate.getSerialNumber()) .toASN1Object(); } } } catch (Exception e) { throw new CertificateParsingException( "Exception extracting certificate details: " + e.toString()); } }
/** * Retrieves displayable information about the certificate with the specified index in the chain. * * @param index The index of the certificate to request information on * @return A list of lists of {@link CertificateInformationEntry}s. */ public List<List<CertificateInformationEntry>> getCertificateInfo(final int index) { final List<List<CertificateInformationEntry>> res = new ArrayList<List<CertificateInformationEntry>>(); final X509Certificate cert = chain[index]; List<CertificateInformationEntry> group; boolean tooOld = false, tooNew = false; try { cert.checkValidity(); } catch (CertificateExpiredException ex) { tooOld = true; } catch (CertificateNotYetValidException ex) { tooNew = true; } group = new ArrayList<CertificateInformationEntry>(); group.add( new CertificateInformationEntry( "Valid from", cert.getNotBefore().toString(), tooNew, false)); group.add( new CertificateInformationEntry("Valid to", cert.getNotAfter().toString(), tooOld, false)); res.add(group); final boolean wrongName = index == 0 && !manager.isValidHost(cert); final String names = getAlternateNames(cert); final Map<String, String> fields = CertificateManager.getDNFieldsFromCert(cert); group = new ArrayList<CertificateInformationEntry>(); addCertField(fields, group, "Common name", "CN", wrongName); group.add( new CertificateInformationEntry( "Alternate names", names == null ? NOTPRESENT : names, wrongName, names == null)); addCertField(fields, group, "Organisation", "O", false); addCertField(fields, group, "Unit", "OU", false); addCertField(fields, group, "Locality", "L", false); addCertField(fields, group, "State", "ST", false); addCertField(fields, group, "Country", "C", false); res.add(group); group = new ArrayList<CertificateInformationEntry>(); group.add( new CertificateInformationEntry( "Serial number", cert.getSerialNumber().toString(), false, false)); group.add(new CertificateInformationEntry("Algorithm", cert.getSigAlgName(), false, false)); group.add( new CertificateInformationEntry( "SSL version", String.valueOf(cert.getVersion()), false, false)); res.add(group); return res; }
public AttributeCertificateHolder(X509Certificate cert) throws CertificateParsingException { X509Principal name; try { name = PrincipalUtil.getIssuerX509Principal(cert); } catch (Exception e) { throw new CertificateParsingException(e.getMessage()); } holder = new Holder( new IssuerSerial(generateGeneralNames(name), new DERInteger(cert.getSerialNumber()))); }
public boolean match(Certificate cert) { if (!(cert instanceof X509Certificate)) { return false; } X509Certificate x509Cert = (X509Certificate) cert; try { if (holder.getBaseCertificateID() != null) { return holder .getBaseCertificateID() .getSerial() .getValue() .equals(x509Cert.getSerialNumber()) && matchesDN( PrincipalUtil.getIssuerX509Principal(x509Cert), holder.getBaseCertificateID().getIssuer()); } if (holder.getEntityName() != null) { if (matchesDN(PrincipalUtil.getSubjectX509Principal(x509Cert), holder.getEntityName())) { return true; } } if (holder.getObjectDigestInfo() != null) { MessageDigest md = null; try { md = MessageDigest.getInstance(getDigestAlgorithm(), "DFBC"); } catch (Exception e) { return false; } switch (getDigestedObjectType()) { case ObjectDigestInfo.publicKey: // TODO: DSA Dss-parms md.update(cert.getPublicKey().getEncoded()); break; case ObjectDigestInfo.publicKeyCert: md.update(cert.getEncoded()); break; } if (!Arrays.areEqual(md.digest(), getObjectDigest())) { return false; } } } catch (CertificateEncodingException e) { return false; } return false; }
private void preload() throws ApduConnectionException, Iso7816FourCardException, IOException, CertificateException, Asn1Exception, TlvException { // Nos vamos al raiz antes de nada selectMasterFile(); // Cargamos el CDF final CeresCdf cdf = new CeresCdf(); final byte[] cdfBytes = selectFileByLocationAndRead(CDF_LOCATION); cdf.setDerValue(cdfBytes); // Leemos los certificados segun las rutas del CDF final CertificateFactory cf = CertificateFactory.getInstance("X.509"); // $NON-NLS-1$ this.certs = new LinkedHashMap<String, X509Certificate>(cdf.getCertificateCount()); this.aliasByCertAndKeyId = new LinkedHashMap<String, String>(cdf.getCertificateCount()); for (int i = 0; i < cdf.getCertificateCount(); i++) { final Location l = new Location( cdf.getCertificatePath(i).replace("\\", "").trim()); // $NON-NLS-1$ //$NON-NLS-2$ final X509Certificate cert = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(deflate(selectFileByLocationAndRead(l)))); final String alias = i + " " + cert.getSerialNumber(); // $NON-NLS-1$ this.aliasByCertAndKeyId.put(HexUtils.hexify(cdf.getCertificateId(i), false), alias); this.certs.put(alias, cert); } final CeresPrKdf prkdf = new CeresPrKdf(); final byte[] prkdfValue = selectFileByLocationAndRead(PRKDF_LOCATION); prkdf.setDerValue(prkdfValue); this.keys = new LinkedHashMap<String, Byte>(); for (int i = 0; i < prkdf.getKeyCount(); i++) { final String alias = this.aliasByCertAndKeyId.get(HexUtils.hexify(prkdf.getKeyId(i), false)); if (alias != null) { this.keys.put(alias, Byte.valueOf(prkdf.getKeyReference(i))); } } // Sincronizamos claves y certificados hideCertsWithoutKey(); }
public static String prettyPrint(X509Certificate x509) { if (x509 == null) throw new IllegalArgumentException("x509 cannot be null"); return String.format( FORMAT, x509.getVersion(), x509.getSerialNumber(), x509.getSigAlgName(), x509.getIssuerX500Principal().getName(), x509.getNotBefore(), x509.getNotAfter(), x509.getSubjectX500Principal().getName(), x509.getPublicKey().getAlgorithm(), x509.getBasicConstraints(), x509.getSigAlgName()); }
private static void writeSignatureBlock( Signature signature, X509Certificate publicKey, OutputStream out) throws IOException, GeneralSecurityException { SignerInfo signerInfo = new SignerInfo( new X500Name(publicKey.getIssuerX500Principal().getName()), publicKey.getSerialNumber(), AlgorithmId.get("SHA1"), AlgorithmId.get("RSA"), signature.sign()); PKCS7 pkcs7 = new PKCS7( new AlgorithmId[] {AlgorithmId.get("SHA1")}, new ContentInfo(ContentInfo.DATA_OID, null), new X509Certificate[] {publicKey}, new SignerInfo[] {signerInfo}); pkcs7.encodeSignedData(out); }
@Override public String getMessage() { StringBuilder sb = new StringBuilder(150); sb.append(super.getMessage()); if (x509Certificates != null && x509Certificates.length > 0) { sb.append( "\n\nFollow certificates (in PEM format) presented by the peer. Content between being/end certificate (including) can be stored in a file and imported using keytool, e.g. 'keytool -importcert -file cert.cer -alias certAlias -keystore keystore.jks'). Make sure the presented certificates are issued by your trusted CA before adding them to the keystore.\n\n"); for (X509Certificate cert : x509Certificates) { sb.append("Subject: ").append(cert.getSubjectDN()).append("\n"); sb.append("Serial number: ").append(cert.getSerialNumber()).append("\n"); appendThumbPrint(cert, sb); sb.append("\n"); appendCertificate(cert, sb); sb.append("\n"); } } return sb.toString(); }
/* * Construct an RecipientId. Added private function to support multiple versions of BC libraries. */ private RecipientId generateRecipientSelector(X509Certificate decryptCert) { RecipientId retVal = null; Class<RecipientId> loadClass = null; try { // support for bcmail-jdk15-146 loadClass = (Class<RecipientId>) getClass() .getClassLoader() .loadClass("org.bouncycastle.cms.jcajce.JceKeyTransRecipientId"); Constructor<RecipientId> constructor = loadClass.getConstructor(X509Certificate.class); retVal = constructor.newInstance(decryptCert); } catch (Throwable e) { if (LOGGER.isDebugEnabled()) { StringBuilder builder = new StringBuilder( "bcmail-jdk15-146 org.bouncycastle.cms.jcajce.JceKeyTransRecipientId class not found."); builder.append( "\r\n\tAttempt to fall back to bcmail-jdk15-140 org.bouncycastle.cms.RecipientId"); LOGGER.debug(builder.toString()); } } if (retVal == null) { try { // fall back to bcmail-jdk15-140 interfaces loadClass = (Class<RecipientId>) getClass().getClassLoader().loadClass("org.bouncycastle.cms.RecipientId"); retVal = loadClass.newInstance(); retVal.setSerialNumber(decryptCert.getSerialNumber()); retVal.setIssuer(decryptCert.getIssuerX500Principal().getEncoded()); } catch (Throwable e) { LOGGER.error( "Attempt to fall back to bcmail-jdk15-140 org.bouncycastle.cms.RecipientId failed.", e); } } return retVal; }
/* * (non-Javadoc) * * @see javax.swing.DefaultListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, * boolean, boolean) */ @Override public Component getListCellRendererComponent( final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { final X509Certificate cert = ((DSSPrivateKeyEntry) value).getCertificate(); String subjectDN = cert.getSubjectDN().getName(); final int dnStartIndex = subjectDN.indexOf("CN=") + 3; if (dnStartIndex > 0 && subjectDN.indexOf(",", dnStartIndex) > 0) { subjectDN = subjectDN.substring(dnStartIndex, subjectDN.indexOf(",", dnStartIndex)) + " (SN:" + cert.getSerialNumber() + ")"; } return super.getListCellRendererComponent(list, subjectDN, index, isSelected, cellHasFocus); }
public String handleCertificateCheckFailure( String hostname, X509Certificate cert, boolean isMismatch) { hostname = hostname.toLowerCase(); String alias = hostname + ":" + cert.getSerialNumber().toString(16).toUpperCase(); if (LC.ssl_allow_accept_untrusted_certs.booleanValue()) cachePendingCertificate(alias, cert); String certInfo = ""; try { certInfo = new SSLCertInfo( alias, hostname, cert, LC.ssl_allow_accept_untrusted_certs.booleanValue(), isMismatch) .serialize(); } catch (Exception ex) { } return certInfo; }
/** * @return a byte array * @see com.lowagie.text.pdf.OcspClient#getEncoded() */ public byte[] getEncoded() { try { OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber()); byte[] array = request.getEncoded(); URL urlt = new URL(url); HttpURLConnection con = (HttpURLConnection) urlt.openConnection(); con.setRequestProperty("Content-Type", "application/ocsp-request"); con.setRequestProperty("Accept", "application/ocsp-response"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out)); dataOut.write(array); dataOut.flush(); dataOut.close(); if (con.getResponseCode() / 100 != 2) { throw new IOException("Invalid HTTP response"); } // Get Response InputStream in = (InputStream) con.getContent(); OCSPResp ocspResponse = new OCSPResp(in); if (ocspResponse.getStatus() != 0) throw new IOException("Invalid status: " + ocspResponse.getStatus()); BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); if (basicResponse != null) { SingleResp[] responses = basicResponse.getResponses(); if (responses.length == 1) { SingleResp resp = responses[0]; Object status = resp.getCertStatus(); if (status == CertificateStatus.GOOD) { return basicResponse.getEncoded(); } else if (status instanceof repack.org.bouncycastle.ocsp.RevokedStatus) { throw new IOException("OCSP Status is revoked!"); } else { throw new IOException("OCSP Status is unknown!"); } } } } catch (Exception ex) { throw new ExceptionConverter(ex); } return null; }
private X509Certificate readCertificate(String certPath) { try { FileInputStream fr = new FileInputStream(certPath); CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate crt = (X509Certificate) cf.generateCertificate(fr); logger.info("Read certificate:"); logger.info("\tCertificate for: " + crt.getSubjectDN()); logger.info("\tCertificate issued by: " + crt.getIssuerDN()); logger.info("\tCertificate is valid from " + crt.getNotBefore() + " to " + crt.getNotAfter()); logger.info("\tCertificate SN# " + crt.getSerialNumber()); logger.info("\tGenerated with " + crt.getSigAlgName()); return crt; } catch (Exception e) { e.printStackTrace(); } return null; }
private void createCertificate(int certificateProfileId) throws Exception { KeyPair keys = KeyTools.genKeys("1024", "RSA"); cert = (X509Certificate) signSession.createCertificate( admin, USERNAME, PASSWORD, new PublicKeyWrapper(keys.getPublic()), -1, null, null, certificateProfileId, SecConst.CAID_USEUSERDEFINED); certificatesToRemove.add(cert); fingerprint = CertTools.getFingerprintAsString(cert); X509Certificate ce = (X509Certificate) certificateStoreSession.findCertificateByFingerprint(fingerprint); if (ce == null) { throw new Exception("Cannot find certificate with fp=" + fingerprint); } info = certificateStoreSession.getCertificateInfo(fingerprint); if (!fingerprint.equals(info.getFingerprint())) { throw new Exception("fingerprint does not match."); } if (!cert.getSerialNumber().equals(info.getSerialNumber())) { throw new Exception("serialnumber does not match."); } if (!CertTools.getIssuerDN(cert).equals(info.getIssuerDN())) { throw new Exception("issuerdn does not match."); } if (!CertTools.getSubjectDN(cert).equals(info.getSubjectDN())) { throw new Exception("subjectdn does not match."); } // The cert was just stored above with status INACTIVE if (!(CertificateConstants.CERT_ACTIVE == info.getStatus())) { throw new Exception("status does not match."); } }
/** * Create the Master Certificate for the GridTalk. * * @param certFile The file that contains the Certificate. * @return the UID of the created certificate. */ private Long createMasterCertificate(File certFile) throws Throwable { Long certUID = null; X509Certificate cert = GridCertUtilities.loadX509Certificate(certFile.getAbsolutePath()); ICertificateManagerObj mgr = ServiceLookupHelper.getCertificateManager(); // retrieve existing master cert Certificate existCert = mgr.findCertificateByIDAndName(_ctx.getGridNodeID().intValue(), _ctx.getMasterCertName()); // revoke Logger.log( "[ConnectionSetupRequestDelegate.createMasterCertificate] Revoking cert " + existCert.getUId()); mgr.revokeCertificateByUId((Long) existCert.getKey()); // insert new cert mgr.insertCertificate(_ctx.getGridNodeID(), _ctx.getMasterCertName(), cert); /*NSL20051115 Somehow this method still returns the revoked cert... so alternative is to * use issuername & serialnumber to retrieve -- guarantee to be unique Certificate newCert = mgr.findCertificateByIDAndName( _ctx.getGridNodeID().intValue(), _ctx.getMasterCertName()); */ String issuerName = GridCertUtilities.writeIssuerNameToString(cert.getIssuerX500Principal()); String serialNum = GridCertUtilities.writeByteArrayToString(cert.getSerialNumber().toByteArray()); Certificate newCert = mgr.findCertificateByIssureAndSerialNum(issuerName, serialNum); certUID = (Long) newCert.getKey(); Logger.log("[ConnectionSetupRequestDelegate.createMasterCertificate] New cert UID=" + certUID); // update private key mgr.updatePrivateKeyByCertificate(existCert.getPrivateKey(), newCert.getCertificate()); // update IsMaster mgr.updateMasterAndPartnerByUId(certUID, true, false); return certUID; }
private static boolean certHasPolicy(X509Certificate cert, String sOid) { try { if (m_logger.isDebugEnabled()) m_logger.debug("Read cert policies: " + cert.getSerialNumber().toString()); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1Sequence seq = (ASN1Sequence) aIn.readObject(); X509CertificateStructure obj = new X509CertificateStructure(seq); TBSCertificateStructure tbsCert = obj.getTBSCertificate(); if (tbsCert.getVersion() == 3) { X509Extensions ext = tbsCert.getExtensions(); if (ext != null) { Enumeration en = ext.oids(); while (en.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement(); X509Extension extVal = ext.getExtension(oid); ASN1OctetString oct = extVal.getValue(); ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())); // if (oid.equals(X509Extensions.CertificatePolicies)) { // bc 146 ja jdk 1.6 puhul - // X509Extension.certificatePolicies if (oid.equals(X509Extension.certificatePolicies)) { // bc 146 ja jdk 1.6 puhul - // X509Extension.certificatePolicies ASN1Sequence cp = (ASN1Sequence) extIn.readObject(); for (int i = 0; i != cp.size(); i++) { PolicyInformation pol = PolicyInformation.getInstance(cp.getObjectAt(i)); DERObjectIdentifier dOid = pol.getPolicyIdentifier(); String soid2 = dOid.getId(); if (m_logger.isDebugEnabled()) m_logger.debug("Policy: " + soid2); if (soid2.startsWith(sOid)) return true; } } } } } } catch (Exception ex) { m_logger.error("Error reading cert policies: " + ex); } return false; }
private void storeCertificateInCache(X509Certificate certificate, String key, boolean validated) { // Store in the cache if (certificate != null && xkmsClientCache != null) { XKMSCacheToken cacheToken = new XKMSCacheToken(certificate); cacheToken.setXkmsValidated(validated); // Store using a custom key (if any) if (key != null) { xkmsClientCache.put(key, cacheToken); } // Store it using IssuerSerial as well String issuerSerialKey = getKeyForIssuerSerial( certificate.getIssuerX500Principal().getName(), certificate.getSerialNumber()); if (!issuerSerialKey.equals(key)) { xkmsClientCache.put(issuerSerialKey, cacheToken); } // Store it using the Subject DN as well String subjectDNKey = certificate.getSubjectX500Principal().getName(); if (!subjectDNKey.equals(key)) { xkmsClientCache.put(subjectDNKey, cacheToken); } } }
/** * Encodes the provided <tt>PkiMessage</tt> into a PKCS #7 <tt>signedData</tt>. * * @param message the <tt>PkiMessage</tt> to encode. * @return the encoded <tt>signedData</tt> * @throws MessageEncodingException if there is a problem encoding the <tt>PkiMessage</tt> */ public CMSSignedData encode(PkiMessage<?> message) throws MessageEncodingException { LOGGER.debug("Encoding pkiMessage"); LOGGER.debug("Encoding message: {}", message); CMSProcessable content = getContent(message); LOGGER.debug( "Signing pkiMessage using key belonging to [issuer={}; serial={}]", signerId.getIssuerDN(), signerId.getSerialNumber()); try { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); generator.addSignerInfoGenerator(getSignerInfo(message)); generator.addCertificates(getCertificates()); LOGGER.debug("Signing {} content", content); CMSSignedData pkiMessage = generator.generate(DATA, content, true, (Provider) null, true); LOGGER.debug("Finished encoding pkiMessage"); return pkiMessage; } catch (CMSException e) { throw new MessageEncodingException(e); } catch (Exception e) { throw new MessageEncodingException(e); } }
/** {@inheritDoc} */ @Override public String[] matches(final String[] aliases, final KeyStoreManager ksm) { final X509Certificate[] certs = new X509Certificate[aliases.length]; for (int i = 0; i < aliases.length; i++) { certs[i] = ksm.getCertificate(aliases[i]); } X509Certificate cert; final List<String> filteredCerts = new ArrayList<String>(); for (int i = 0; i < aliases.length; i++) { cert = ksm.getCertificate(aliases[i]); try { if (this.matches(cert)) { if (this.isAuthenticationDnieCert(cert)) { final String alias = getAssociatedCertAlias(ksm, cert, aliases, i); if (alias != null) { filteredCerts.add(aliases[i]); } } else { filteredCerts.add(aliases[i]); } } } catch (final Exception e) { Logger.getLogger("es.gob.afirma") .warning( //$NON-NLS-1$ "Error en la verificacion del certificado '" + //$NON-NLS-1$ cert.getSerialNumber() + "': " + e //$NON-NLS-1$ ); } } return filteredCerts.toArray(new String[filteredCerts.size()]); }
/** * Returns the SerialNumber of certificate on String format<br> * * @return String */ public String getSerialNumber() { return toString(certificate.getSerialNumber()); }
/** Read an existing PKCS#7 object from a DER encoded byte array */ public PKCS7SignedData(byte[] in, String provider) throws SecurityException, CRLException, InvalidKeyException, NoSuchProviderException, NoSuchAlgorithmException { ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(in)); // // Basic checks to make sure it's a PKCS#7 SignedData Object // DERObject pkcs; try { pkcs = din.readObject(); } catch (IOException e) { throw new SecurityException("can't decode PKCS7SignedData object"); } if (!(pkcs instanceof ASN1Sequence)) { throw new SecurityException("Not a valid PKCS#7 object - not a sequence"); } ContentInfo content = ContentInfo.getInstance(pkcs); if (!content.getContentType().equals(signedData)) { throw new SecurityException( "Not a valid PKCS#7 signed-data object - wrong header " + content.getContentType().getId()); } SignedData data = SignedData.getInstance(content.getContent()); certs = new ArrayList(); if (data.getCertificates() != null) { Enumeration ec = ASN1Set.getInstance(data.getCertificates()).getObjects(); while (ec.hasMoreElements()) { try { certs.add( new X509CertificateObject(X509CertificateStructure.getInstance(ec.nextElement()))); } catch (CertificateParsingException e) { throw new SecurityException(e.toString()); } } } crls = new ArrayList(); if (data.getCRLs() != null) { Enumeration ec = ASN1Set.getInstance(data.getCRLs()).getObjects(); while (ec.hasMoreElements()) { crls.add(new X509CRLObject(CertificateList.getInstance(ec.nextElement()))); } } version = data.getVersion().getValue().intValue(); // // Get the digest algorithm // digestalgos = new HashSet(); Enumeration e = data.getDigestAlgorithms().getObjects(); while (e.hasMoreElements()) { ASN1Sequence s = (ASN1Sequence) e.nextElement(); DERObjectIdentifier o = (DERObjectIdentifier) s.getObjectAt(0); digestalgos.add(o.getId()); } // // Get the SignerInfo // ASN1Set signerinfos = data.getSignerInfos(); if (signerinfos.size() != 1) { throw new SecurityException( "This PKCS#7 object has multiple SignerInfos - only one is supported at this time"); } SignerInfo signerInfo = SignerInfo.getInstance(signerinfos.getObjectAt(0)); signerversion = signerInfo.getVersion().getValue().intValue(); IssuerAndSerialNumber isAnds = signerInfo.getIssuerAndSerialNumber(); // // Get the signing certificate // BigInteger serialNumber = isAnds.getCertificateSerialNumber().getValue(); X509Principal issuer = new X509Principal(isAnds.getName()); for (Iterator i = certs.iterator(); i.hasNext(); ) { X509Certificate cert = (X509Certificate) i.next(); if (serialNumber.equals(cert.getSerialNumber()) && issuer.equals(cert.getIssuerDN())) { signCert = cert; break; } } if (signCert == null) { throw new SecurityException( "Can't find signing certificate with serial " + serialNumber.toString(16)); } digestAlgorithm = signerInfo.getDigestAlgorithm().getObjectId().getId(); digest = signerInfo.getEncryptedDigest().getOctets(); digestEncryptionAlgorithm = signerInfo.getDigestEncryptionAlgorithm().getObjectId().getId(); sig = Signature.getInstance(getDigestAlgorithm(), provider); sig.initVerify(signCert.getPublicKey()); }
/** return the bytes for the PKCS7SignedData object. */ public byte[] getEncoded() { try { digest = sig.sign(); // Create the set of Hash algorithms. I've assumed this is the // set of all hash agorithms used to created the digest in the // "signerInfo" structure. I may be wrong. // ASN1EncodableVector v = new ASN1EncodableVector(); for (Iterator i = digestalgos.iterator(); i.hasNext(); ) { AlgorithmIdentifier a = new AlgorithmIdentifier(new DERObjectIdentifier((String) i.next()), null); v.add(a); } DERSet algos = new DERSet(v); // Create the contentInfo. Empty, I didn't implement this bit // DERSequence contentinfo = new DERSequence(new DERObjectIdentifier(ID_PKCS7_DATA)); // Get all the certificates // v = new ASN1EncodableVector(); for (Iterator i = certs.iterator(); i.hasNext(); ) { ASN1InputStream tempstream = new ASN1InputStream( new ByteArrayInputStream(((X509Certificate) i.next()).getEncoded())); v.add(tempstream.readObject()); } DERSet dercertificates = new DERSet(v); // Create signerinfo structure. // ASN1EncodableVector signerinfo = new ASN1EncodableVector(); // Add the signerInfo version // signerinfo.add(new DERInteger(signerversion)); IssuerAndSerialNumber isAnds = new IssuerAndSerialNumber( new X509Name((ASN1Sequence) getIssuer(signCert.getTBSCertificate())), new DERInteger(signCert.getSerialNumber())); signerinfo.add(isAnds); // Add the digestAlgorithm // signerinfo.add( new AlgorithmIdentifier(new DERObjectIdentifier(digestAlgorithm), new DERNull())); // // Add the digestEncryptionAlgorithm // signerinfo.add( new AlgorithmIdentifier( new DERObjectIdentifier(digestEncryptionAlgorithm), new DERNull())); // // Add the digest // signerinfo.add(new DEROctetString(digest)); // // Finally build the body out of all the components above // ASN1EncodableVector body = new ASN1EncodableVector(); body.add(new DERInteger(version)); body.add(algos); body.add(contentinfo); body.add(new DERTaggedObject(false, 0, dercertificates)); if (crls.size() > 0) { v = new ASN1EncodableVector(); for (Iterator i = crls.iterator(); i.hasNext(); ) { ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(((X509CRL) i.next()).getEncoded())); v.add(t.readObject()); } DERSet dercrls = new DERSet(v); body.add(new DERTaggedObject(false, 1, dercrls)); } // Only allow one signerInfo // body.add(new DERSet(new DERSequence(signerinfo))); // Now we have the body, wrap it in it's PKCS7Signed shell // and return it // ASN1EncodableVector whole = new ASN1EncodableVector(); whole.add(new DERObjectIdentifier(ID_PKCS7_SIGNED_DATA)); whole.add(new DERTaggedObject(0, new DERSequence(body))); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dout = new DEROutputStream(bOut); dout.writeObject(new DERSequence(whole)); dout.close(); return bOut.toByteArray(); } catch (Exception e) { throw new RuntimeException(e.toString()); } }