List of usage examples for java.security.cert X509Certificate getSerialNumber
public abstract BigInteger getSerialNumber();
From source file:org.ejbca.core.protocol.cmp.CrmfRARequestTest.java
/** * @param userDN// w w w. jav a2 s. c om * for new certificate. * @param keys * key of the new certificate. * @param sFailMessage * if !=null then EJBCA is expected to fail. The failure response * message string is checked against this parameter. * @throws Exception */ private void crmfHttpUserTest(String userDN, KeyPair keys, String sFailMessage, BigInteger customCertSerno) throws Exception { // Create a new good user final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); final int reqId; { final PKIMessage one = genCertReq(issuerDN, userDN, keys, cacert, nonce, transid, true, null, null, null, customCertSerno); final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567); reqId = req.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue(); assertNotNull(req); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, sFailMessage == null, null); if (sFailMessage == null) { X509Certificate cert = checkCmpCertRepMessage(userDN, cacert, resp, reqId); // verify if custom cert serial number was used if (customCertSerno != null) { assertTrue(cert.getSerialNumber().toString(16) + " is not same as expected " + customCertSerno.toString(16), cert.getSerialNumber().equals(customCertSerno)); } } else { checkCmpFailMessage(resp, sFailMessage, CmpPKIBodyConstants.ERRORMESSAGE, reqId, FailInfo.BAD_REQUEST.hashCode()); } } { // Send a confirm message to the CA final String hash = "foo123"; final PKIMessage con = genCertConfirm(userDN, cacert, nonce, transid, hash, reqId); assertNotNull(con); PKIMessage confirm = protectPKIMessage(con, false, PBEPASSWORD, 567); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(confirm); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200); checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, null); checkCmpPKIConfirmMessage(userDN, cacert, resp); } }
From source file:com.mhise.util.MHISEUtil.java
public static boolean verifyP12StorePassword(String keyStorePath, String password, String serialNumber, Context ctx) {/*from w w w . j ava2 s . c om*/ boolean isInstalledCertificateValid = false; KeyStore trustStore = null; FileInputStream fin = null; try { trustStore = KeyStore.getInstance("PKCS12"); } catch (KeyStoreException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } File file = new File(keyStorePath); if (file.exists()) { try { fin = new FileInputStream(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { trustStore.load(fin, password.toCharArray()); fin.close(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); MHISEUtil.displayDialog(ctx, "Invalid Password", null); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); MHISEUtil.displayDialog(ctx, "Invalid Password", null); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); MHISEUtil.displayDialog(ctx, "Invalid Password", null); } Enumeration<String> aliases = null; try { aliases = trustStore.aliases(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); java.security.cert.X509Certificate cert = null; try { cert = (X509Certificate) trustStore.getCertificate(alias); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (cert.getSerialNumber().toString().equals(serialNumber)) { // isInstalledCertificateValid = true; SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(Constants.KEY_SERIAL_NUMBER, "" + cert.getSerialNumber().toString(16)); editor.commit(); return true; } } } catch (NullPointerException e) { // TODO: handle exception Logger.debug("password invalid", "" + e); } } return isInstalledCertificateValid; }
From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java
/** * Runs the command//from w w w . j a v a 2 s. c o m * * @throws IllegalAdminCommandException Error in command args * @throws ErrorAdminCommandException Error running command */ public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException { try { CertRequest certReq = genCertReq(userDN, null); PKIMessage certMsg = genPKIMessage(false, certReq); if (certMsg == null) { getPrintStream().println("No certificate request."); System.exit(-1); } AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption); certMsg.getHeader().setProtectionAlg(pAlg); certMsg.getHeader().setSenderKID(new DEROctetString("CMPEnduser".getBytes())); PKIMessage signedMsg = signPKIMessage(certMsg, innerSignKey); addExtraCert(signedMsg, innerCertificate); if (signedMsg == null) { getPrintStream().println("No protected message."); System.exit(-1); } PKIHeader myPKIHeader = new PKIHeader(new DERInteger(2), new GeneralName(new X509Name("CN=CMSSender,C=SE")), new GeneralName(new X509Name(((X509Certificate) cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(nonce)); //myPKIHeader.addGeneralInfo(new InfoTypeAndValue(ASN1Sequence.getInstance(crmfMsg))); PKIBody myPKIBody = new PKIBody(signedMsg, 20); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader, myPKIBody); PKIMessage cmsMessage = signPKIMessage(myPKIMessage, outerSignKey); reqId = signedMsg.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue(); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(cmsMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmp(ba); if (resp == null || resp.length <= 0) { getPrintStream().println("No response message."); System.exit(-1); } /* if ( !checkCmpResponseGeneral(resp, true) ) { System.exit(-1); } */ final X509Certificate cert = checkCmpCertRepMessage(resp, reqId); if (cert == null) { getPrintStream().println("No certificate was created."); System.exit(-1); } getPrintStream().println("Certificate for " + userDN + " was created with the serialnumber: " + cert.getSerialNumber().toString()); if (createsCertsPath != null) { String filename = CertTools.getPartFromDN(cert.getSubjectDN().toString(), "CN") + ".pem"; writeCertificate(cert, createsCertsPath, filename); getPrintStream().println("Certificate was written to: " + createsCertsPath + "/" + filename); } } catch (IOException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (InvalidKeyException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (NoSuchAlgorithmException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (SignatureException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (NoSuchProviderException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (CertificateEncodingException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } catch (Exception e) { e.printStackTrace(getPrintStream()); System.exit(-1); } getPrintStream().println("Test successfull"); }
From source file:com.netscape.cms.publish.publishers.FileBasedPublisher.java
/** * Publishes a object to the ldap directory. * * @param conn a Ldap connection/*from w w w .j ava 2 s . c o m*/ * (null if LDAP publishing is not enabled) * @param dn dn of the ldap entry to publish cert * (null if LDAP publishing is not enabled) * @param object object to publish * (java.security.cert.X509Certificate or, * java.security.cert.X509CRL) */ public void publish(LDAPConnection conn, String dn, Object object) throws ELdapException { CMS.debug("FileBasedPublisher: publish"); try { if (object instanceof X509Certificate) { X509Certificate cert = (X509Certificate) object; BigInteger sno = cert.getSerialNumber(); String name = mDir + File.separator + "cert-" + sno.toString(); if (mDerAttr) { FileOutputStream fos = null; try { String fileName = name + ".der"; fos = new FileOutputStream(fileName); fos.write(cert.getEncoded()); } finally { if (fos != null) fos.close(); } } if (mB64Attr) { String fileName = name + ".b64"; PrintStream ps = null; Base64OutputStream b64 = null; FileOutputStream fos = null; try { fos = new FileOutputStream(fileName); ByteArrayOutputStream output = new ByteArrayOutputStream(); b64 = new Base64OutputStream(new PrintStream(new FilterOutputStream(output))); b64.write(cert.getEncoded()); b64.flush(); ps = new PrintStream(fos); ps.print(output.toString("8859_1")); } finally { if (ps != null) { ps.close(); } if (b64 != null) { b64.close(); } if (fos != null) fos.close(); } } } else if (object instanceof X509CRL) { X509CRL crl = (X509CRL) object; String[] namePrefix = getCrlNamePrefix(crl, mTimeStamp.equals("GMT")); String baseName = mDir + File.separator + namePrefix[0]; String tempFile = baseName + ".temp"; ZipOutputStream zos = null; byte[] encodedArray = null; File destFile = null; String destName = null; File renameFile = null; if (mDerAttr) { FileOutputStream fos = null; try { fos = new FileOutputStream(tempFile); encodedArray = crl.getEncoded(); fos.write(encodedArray); } finally { if (fos != null) fos.close(); } if (mZipCRL) { try { zos = new ZipOutputStream(new FileOutputStream(baseName + ".zip")); zos.setLevel(mZipLevel); zos.putNextEntry(new ZipEntry(baseName + ".der")); zos.write(encodedArray, 0, encodedArray.length); zos.closeEntry(); } finally { if (zos != null) zos.close(); } } destName = baseName + ".der"; destFile = new File(destName); if (destFile.exists()) { destFile.delete(); } renameFile = new File(tempFile); renameFile.renameTo(destFile); if (mLatestCRL) { String linkExt = "."; if (mLinkExt != null && mLinkExt.length() > 0) { linkExt += mLinkExt; } else { linkExt += "der"; } String linkName = mDir + File.separator + namePrefix[1] + linkExt; createLink(linkName, destName); if (mZipCRL) { linkName = mDir + File.separator + namePrefix[1] + ".zip"; createLink(linkName, baseName + ".zip"); } } } // output base64 file if (mB64Attr == true) { if (encodedArray == null) encodedArray = crl.getEncoded(); FileOutputStream fos = null; try { fos = new FileOutputStream(tempFile); fos.write(Utils.base64encode(encodedArray, true).getBytes()); } finally { if (fos != null) fos.close(); } destName = baseName + ".b64"; destFile = new File(destName); if (destFile.exists()) { destFile.delete(); } renameFile = new File(tempFile); renameFile.renameTo(destFile); } purgeExpiredFiles(); purgeExcessFiles(); } } catch (IOException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } catch (CertificateEncodingException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } catch (CRLException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } }
From source file:org.jasig.cas.adaptors.x509.authentication.handler.support.X509CredentialsAuthenticationHandler.java
protected final boolean doAuthentication(final Credentials credentials) throws AuthenticationException { final X509CertificateCredentials x509Credentials = (X509CertificateCredentials) credentials; final X509Certificate[] certificates = x509Credentials.getCertificates(); /*/*from www . j a v a 2 s. com*/ * the certificate that was fully authenticated succesfully will be set * as the user credentials for CAS last certificate that can be set is * the end-user certificate */ X509Certificate certificateCredentialsCandidate = null; // flag to check whether a trusted issuer is in the certificate chain boolean hasTrustedIssuerInChain = false; /* * reverse transversal of certificates (should be from root to end-user * cert) */ for (int i = (certificates.length - 1); i >= 0; i--) { final X509Certificate certificate = certificates[i]; try { final Principal issuerPrincipal = certificate.getIssuerDN(); // flag that is set when this cert is an end user cert (no CA // cert) boolean isEndUserCertificate = false; if (log.isDebugEnabled()) { log.debug("--examining cert[" + certificate.getSerialNumber().toString() + "] " + certificate.getSubjectDN() + "\"" + " from issuer \"" + issuerPrincipal.getName() + "\""); } // check basic validity of the current certificate certificate.checkValidity(); log.debug("certificate is valid"); // initial check for trusted issuer in certificate chain // final check is done outside for loop if (isCertificateFromTrustedIssuer(issuerPrincipal)) { hasTrustedIssuerInChain = true; log.debug("certificate was issued by trusted issuer"); } // getBasicConstraints returns pathLenContraint which is // >=0 when this is a CA cert and -1 when it's not int pathLength = certificate.getBasicConstraints(); if (pathLength != -1) { log.debug("this is a CA certificate"); // check pathLength when CA cert //if unlimited/unspecified and unlimited/unspecified not allowed: warn+stop if (pathLength == Integer.MAX_VALUE && this.maxPathLength_allowUnspecified != true) { if (log.isWarnEnabled()) { log.warn("authentication failed; cert pathLength not specified" + " and unlimited/unspecified not allowed by config [see maxPathLength_allow_unlimited]"); } return false; //else if more than allowed length but not unlimited/unspecified: warn+stop } else if (pathLength > this.maxPathLength && pathLength < Integer.MAX_VALUE) { if (log.isWarnEnabled()) { log.warn("authentication failed; cert pathLength [" + pathLength + "] is more than allowed by config [" + this.maxPathLength + "]"); } return false; } } else { isEndUserCertificate = true; log.debug("this is an end-user certificate"); } /* * set this certificate as the user credentials if there is an * issuer in the cert (always so if valid cert) and this is an * end-user or CA certificate (so not a CA cert) and optional * KeyUsage check */ if (issuerPrincipal != null && isEndUserCertificate && this.doesCertificateSubjectDnMatchPattern(certificate.getSubjectDN()) && (!this.checkKeyUsage || (this.checkKeyUsage && this.doesCertificateKeyUsageMatch(certificate)))) { if (log.isDebugEnabled()) { log.debug("cert[" + certificate.getSerialNumber().toString() + "] ok, setting as credentials candidate"); } certificateCredentialsCandidate = certificate; } } catch (final CertificateExpiredException e) { log.warn("authentication failed; certficiate expired [" + certificate.toString() + "]"); certificateCredentialsCandidate = null; } catch (final CertificateNotYetValidException e) { log.warn("authentication failed; certficate not yet valid [" + certificate.toString() + "]"); certificateCredentialsCandidate = null; } } // check whether one of the certificates in the chain was // from the trusted issuer; else => fail auth if (certificateCredentialsCandidate != null && hasTrustedIssuerInChain) { if (log.isInfoEnabled()) { log.info("authentication OK; SSL client authentication data meets criteria for cert[" + certificateCredentialsCandidate.getSerialNumber().toString() + "]"); } x509Credentials.setCertificate(certificateCredentialsCandidate); return true; } if (log.isInfoEnabled()) { if (!hasTrustedIssuerInChain) { log.info("client cert did not have trusted issuer pattern \"" + this.regExTrustedIssuerDnPattern.pattern() + "\" in chain; authentication failed"); } else { log.info("authentication failed; SSL client authentication data doesn't meet criteria"); } } return false; }
From source file:org.apache.xml.security.test.encryption.BaltimoreEncTest.java
/** * Method findKey/*from w w w .j a v a2 s . c o m*/ * * Given an encryptedData structure, return the key that will decrypt * it * * @param encryptedData EncryptedData to get key for */ public Key findKey(EncryptedData encryptedData) throws Exception { KeyInfo ki = encryptedData.getKeyInfo(); Key key = null; Key kek = null; if (ki == null) return null; // First check for a known key name KeyName keyName = ki.itemKeyName(0); if (keyName != null) { return (mapKeyName(keyName.getKeyName())); } // Decrypt any encryptedKey structures EncryptedKey encryptedKey = ki.itemEncryptedKey(0); if (encryptedKey == null) return null; KeyInfo kiek = encryptedKey.getKeyInfo(); if (kiek == null) { return null; } KeyName kekKeyName = kiek.itemKeyName(0); if (kekKeyName != null) { kek = mapKeyName(kekKeyName.getKeyName()); } else { X509Data certData = kiek.itemX509Data(0); XMLX509Certificate xcert = certData.itemCertificate(0); X509Certificate cert = xcert.getX509Certificate(); if (cert != null) { if (cert.getSerialNumber().toString().equals(rsaCertSerialNumber)) { kek = rsaKey; } } } if (kek != null) { XMLCipher cipher = XMLCipher.getInstance(); cipher.init(XMLCipher.UNWRAP_MODE, kek); key = cipher.decryptKey(encryptedKey, encryptedData.getEncryptionMethod().getAlgorithm()); } return key; }
From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateAuthenticator.java
/** * Allow user login into system.//w ww . java2s . c o m * * @param userName username of the user. * @param claims claim map. * @param cert x509 certificate. * @param authenticationContext authentication context. */ private void allowUser(String userName, Map claims, X509Certificate cert, AuthenticationContext authenticationContext) { AuthenticatedUser authenticatedUserObj; authenticatedUserObj = AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(userName); authenticatedUserObj.setAuthenticatedSubjectIdentifier(String.valueOf(cert.getSerialNumber())); authenticatedUserObj.setUserAttributes(claims); authenticationContext.setSubject(authenticatedUserObj); }
From source file:net.maritimecloud.identityregistry.security.x509.X509HeaderUserDetailsService.java
@Override public UserDetails loadUserByUsername(String certificateHeader) throws UsernameNotFoundException { if (certificateHeader == null || certificateHeader.length() < 10) { logger.warn("No certificate header found"); throw new UsernameNotFoundException("No certificate header found"); }/*www . j ava 2s .c o m*/ X509Certificate userCertificate = certUtil.getCertFromString(certificateHeader); if (userCertificate == null) { logger.error("Extracting certificate from header failed"); throw new UsernameNotFoundException("Extracting certificate from header failed"); } // Actually authenticate certificate against root cert. if (!certUtil.verifyCertificate(userCertificate)) { logger.warn("Certificate could not be verified"); throw new UsernameNotFoundException("Certificate could not be verified"); } // Check that the certificate has not been revoked long certId = userCertificate.getSerialNumber().longValue(); Certificate cert = certificateService.getCertificateById(certId); if (cert.isRevoked()) { Calendar cal = Calendar.getInstance(); Date now = cal.getTime(); if (cert.getRevokedAt() == null || cert.getRevokedAt().before(now)) { logger.warn("The certificate has been revoked! Cert #" + certId); throw new UsernameNotFoundException("The certificate has been revoked! Cert #" + certId); } } // Get user details from the certificate UserDetails user = certUtil.getUserFromCert(userCertificate); if (user == null) { logger.warn("Extraction of data from the certificate failed"); throw new UsernameNotFoundException("Extraction of data from the client certificate failed"); } // Convert the permissions extracted from the certificate to authorities in this API InetOrgPerson person = ((InetOrgPerson) user); String certOrg = person.getO(); Organization org = organizationService.getOrganizationByMrn(certOrg); if (org == null) { logger.warn("Unknown Organization '" + certOrg + "' in client certificate"); throw new UsernameNotFoundException("Unknown Organization in client certificate"); } Collection<GrantedAuthority> newRoles = new ArrayList<>(); logger.debug("Looking up roles"); for (GrantedAuthority role : user.getAuthorities()) { logger.debug("Looking up roles"); String auth = role.getAuthority(); String[] auths = auth.split(","); for (String auth2 : auths) { logger.debug("Looking up role: " + auth2); List<Role> foundRoles = roleService.getRolesByIdOrganizationAndPermission(org.getId(), auth2); if (foundRoles != null) { for (Role foundRole : foundRoles) { newRoles.add(new SimpleGrantedAuthority(foundRole.getRoleName())); } } } } // Add ROLE_USER as standard for authenticated users with no other role. if (newRoles.isEmpty()) { newRoles.add(new SimpleGrantedAuthority("ROLE_USER")); } InetOrgPerson.Essence essence = new InetOrgPerson.Essence((InetOrgPerson) user); essence.setAuthorities(newRoles); return essence.createUserDetails(); }
From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileC.java
/** * Gives back the JAXB CertID data structure. * /*w w w . j a va 2 s . co m*/ * @param certificate * @param xadesObjectFactory * @param xmldsigObjectFactory * @param digestAlgorithm * @return */ private CertIDType getCertID(X509Certificate certificate, DigestAlgorithm digestAlgorithm) { CertIDType certId = xadesObjectFactory.createCertIDType(); X509IssuerSerialType issuerSerial = getXmldsigObjectFactory().createX509IssuerSerialType(); certId.setIssuerSerial(issuerSerial); String 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, digestAlgorithm); certId.setCertDigest(certDigest); return certId; }