List of usage examples for java.security.cert X509Certificate getNotAfter
public abstract Date getNotAfter();
From source file:org.brekka.pegasus.core.services.impl.CertificateAuthenticationServiceImpl.java
@Override @Transactional()/*from w w w . ja v a 2 s. com*/ public DigitalCertificate authenticate(X509Certificate certificate) throws BadCredentialsException, DisabledException { byte[] signature = certificate.getSignature(); String subjectDN = certificate.getSubjectDN().getName(); String commonName = null; Matcher matcher = matchAllowedSubjectDN(subjectDN, allowedSubjectDistinguishedNamePatterns); if (matcher.groupCount() > 0) { commonName = matcher.group(1); } byte[] subjectDNBytes = subjectDN.getBytes(Charset.forName("UTF-8")); SystemDerivedKeySpecType spec = config.getSubjectDerivedKeySpec(); DerivedKey derivedKey = derivedKeyCryptoService.apply(subjectDNBytes, spec.getSalt(), null, CryptoProfile.Static.of(spec.getCryptoProfile())); byte[] distinguishedNameDigest = derivedKey.getDerivedKey(); CertificateSubject certificateSubject = certificateSubjectDAO .retrieveByDistinguishedNameDigest(distinguishedNameDigest); if (certificateSubject == null) { // Create it certificateSubject = new CertificateSubject(); certificateSubject.setDistinguishedNameDigest(distinguishedNameDigest); certificateSubjectDAO.create(certificateSubject); } DigitalCertificate digitalCertificate = digitalCertificateDAO .retrieveBySubjectAndSignature(certificateSubject, signature); if (digitalCertificate == null) { digitalCertificate = new DigitalCertificate(); digitalCertificate.setActive(Boolean.TRUE); digitalCertificate.setCertificateSubject(certificateSubject); digitalCertificate.setCreated(certificate.getNotBefore()); digitalCertificate.setExpires(certificate.getNotAfter()); digitalCertificate.setSignature(signature); digitalCertificateDAO.create(digitalCertificate); } // Perform some checks if (BooleanUtils.isNotTrue(digitalCertificate.getActive())) { throw new DisabledException( String.format("The certficate with id '%s' has been disabled", digitalCertificate.getId())); } if (digitalCertificate.getExpires().before(new Date())) { throw new CredentialsExpiredException(String.format("The certficate with id '%s' expired %tF", digitalCertificate.getId(), digitalCertificate.getExpires())); } // Both of these are transient certificateSubject.setCommonName(commonName); certificateSubject.setDistinguishedName(subjectDN); return digitalCertificate; }
From source file:org.ejbca.util.CertTools.java
public static Date getNotAfter(Certificate cert) { Date ret = null;/*w ww. j a v a 2 s . c o m*/ if (cert == null) { throw new IllegalArgumentException("getNotAfter: cert is null"); } if (cert instanceof X509Certificate) { X509Certificate xcert = (X509Certificate) cert; ret = xcert.getNotAfter(); } else if (StringUtils.equals(cert.getType(), "CVC")) { CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { ret = cvccert.getCVCertificate().getCertificateBody().getValidTo(); } catch (NoSuchFieldException e) { // it is not uncommon that this field is missing in CVC certificate requests (it's not in the EAC standard so) log.debug("NoSuchFieldException: " + e.getMessage()); return null; } } return ret; }
From source file:org.apache.directory.studio.connection.ui.widgets.CertificateInfoComposite.java
private void populateCertificateTree() { certificateTree.removeAll();/*w ww . j a va2 s . c om*/ valueText.setText(StringUtils.EMPTY); IStructuredSelection selection = (IStructuredSelection) hierarchyTreeViewer.getSelection(); if (selection.size() != 1) { return; } CertificateChainItem certificateItem = (CertificateChainItem) selection.getFirstElement(); X509Certificate certificate = certificateItem.certificate; TreeItem rootItem = new TreeItem(certificateTree, SWT.NONE); Map<String, String> attributeMap = getAttributeMap(certificate.getSubjectX500Principal()); rootItem.setText(attributeMap.get("CN")); //$NON-NLS-1$ TreeItem certItem = createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Certificate"), //$NON-NLS-1$ StringUtils.EMPTY); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Version"), //$NON-NLS-1$ String.valueOf(certificate.getVersion())); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.SerialNumber"), //$NON-NLS-1$ certificate.getSerialNumber().toString(16)); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$ certificate.getSigAlgName()); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Issuer"), //$NON-NLS-1$ certificate.getIssuerX500Principal().getName()); TreeItem validityItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Validity"), //$NON-NLS-1$ StringUtils.EMPTY); createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotBefore"), //$NON-NLS-1$ certificate.getNotBefore().toString()); createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotAfter"), //$NON-NLS-1$ certificate.getNotAfter().toString()); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Subject"), //$NON-NLS-1$ certificate.getSubjectX500Principal().getName()); TreeItem pkiItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.SubjectPublicKeyInfo"), StringUtils.EMPTY); //$NON-NLS-1$ createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKeyAlgorithm"), //$NON-NLS-1$ certificate.getPublicKey().getAlgorithm()); createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKey"), //$NON-NLS-1$ new String(Hex.encodeHex(certificate.getPublicKey().getEncoded()))); TreeItem extItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Extensions"), //$NON-NLS-1$ StringUtils.EMPTY); populateExtensions(extItem, certificate, true); populateExtensions(extItem, certificate, false); createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.SignatureAlgorithm"), //$NON-NLS-1$ certificate.getSigAlgName()); createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$ new String(Hex.encodeHex(certificate.getSignature()))); rootItem.setExpanded(true); certItem.setExpanded(true); validityItem.setExpanded(true); pkiItem.setExpanded(true); extItem.setExpanded(true); }
From source file:mitm.common.security.certificate.impl.StandardX509CertificateBuilderTest.java
@Test public void testGenerateSelfSignedV3Certificate() throws Exception { X509CertificateBuilder certificateBuilder = new StandardX509CertificateBuilder("BC", "BC"); KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA"); keyPairGenerator.initialize(2048, randomSource); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder(); issuerBuilder.setCommonName("Martijn Brinkers"); issuerBuilder.setCountryCode("NL"); issuerBuilder.setEmail("test@example.com", "test2@example.com"); issuerBuilder.setGivenName("Martijn"); issuerBuilder.setSurname("Brinkers"); issuerBuilder.setLocality("Amsterdam"); issuerBuilder.setOrganisation("None"); issuerBuilder.setState("NH"); AltNamesBuilder altNamesBuider = new AltNamesBuilder(); altNamesBuider.setRFC822Names("m.brinkers@pobox.com"); altNamesBuider.setDNSNames("example.com"); X500Principal issuer = issuerBuilder.buildPrincipal(); GeneralNames altNames = altNamesBuider.buildAltNames(); Set<KeyUsageType> keyUsage = new HashSet<KeyUsageType>(); keyUsage.add(KeyUsageType.DIGITALSIGNATURE); keyUsage.add(KeyUsageType.KEYENCIPHERMENT); keyUsage.add(KeyUsageType.NONREPUDIATION); Set<ExtendedKeyUsageType> extendedKeyUsage = new HashSet<ExtendedKeyUsageType>(); extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH); extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION); Date notBefore = DateUtils.addHours(new Date(), -1); Date notAfter = DateUtils.addYears(new Date(), 10); certificateBuilder.setSubject(issuer); certificateBuilder.setIssuer(issuer); certificateBuilder.setAltNames(altNames, true); certificateBuilder.setKeyUsage(keyUsage, true); certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true); certificateBuilder.setNotBefore(notBefore); certificateBuilder.setNotAfter(notAfter); certificateBuilder.setPublicKey(keyPair.getPublic()); certificateBuilder.setSerialNumber(new BigInteger("1")); certificateBuilder.setSignatureAlgorithm("SHA256WithRSA"); certificateBuilder.setIsCA(true, true /* critical */); certificateBuilder.setPathLengthConstraint(5); Set<String> crlDistPoints = new HashSet<String>(); crlDistPoints.add("http://example.com"); crlDistPoints.add("123"); certificateBuilder.setCRLDistributionPoints(crlDistPoints); X509Certificate certificate = certificateBuilder.generateCertificate(keyPair.getPrivate(), null); assertNotNull(certificate);//from w w w .j a va 2 s . c o m File file = new File(tempDir, "testGenerateSelfSignedV3Certificate.cer"); CertificateUtils.writeCertificate(certificate, file); X509CertificateInspector certInspector = new X509CertificateInspector(certificate); assertEquals( "EMAILADDRESS=test2@example.com, EMAILADDRESS=test@example.com, GIVENNAME=Martijn, " + "SURNAME=Brinkers, CN=Martijn Brinkers, O=None, L=Amsterdam, ST=NH, C=NL", certInspector.getSubjectFriendly()); assertEquals(certInspector.getIssuerFriendly(), certInspector.getSubjectFriendly()); AltNamesInspector altNamesInspector = new AltNamesInspector(certificate.getSubjectAlternativeNames()); List<String> rFC822Names = altNamesInspector.getRFC822Names(); assertEquals(1, rFC822Names.size()); assertEquals("m.brinkers@pobox.com", rFC822Names.get(0)); List<String> dNSNames = altNamesInspector.getDNSNames(); assertEquals(1, dNSNames.size()); assertEquals("example.com", dNSNames.get(0)); assertEquals(3, certInspector.getKeyUsage().size()); assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.DIGITALSIGNATURE)); assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.KEYENCIPHERMENT)); assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.NONREPUDIATION)); assertEquals(2, certInspector.getExtendedKeyUsage().size()); assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.CLIENTAUTH)); assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.EMAILPROTECTION)); // we cannot compare the dates because of encoding we loose some detail so check if within 1 sec assertTrue(Math.abs(notAfter.getTime() - certificate.getNotAfter().getTime()) < 1000); assertTrue(Math.abs(notBefore.getTime() - certificate.getNotBefore().getTime()) < 1000); assertEquals("1", certInspector.getSerialNumberHex()); assertEquals("SHA256WITHRSA", certificate.getSigAlgName()); assertTrue(certInspector.isCA()); assertEquals(5, certInspector.getBasicConstraints().getPathLenConstraint().intValue()); Set<String> crlDistPointsCert = CRLDistributionPointsInspector .getURIDistributionPointNames(certInspector.getCRLDistibutionPoints()); assertTrue(crlDistPointsCert.contains("http://example.com")); assertTrue(crlDistPointsCert.contains("123")); }
From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java
/** * This function drives the accepting side of the context establishment * process. It is expected to be called in tandem with the * {@link #initSecContext(byte[], int, int) initSecContext} function. * <BR>/* w w w . j ava 2s . c om*/ * The behavior of context establishment process can be modified by * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * and {@link GSSConstants#REJECT_LIMITED_PROXY * GSSConstants.REJECT_LIMITED_PROXY} context options. If the * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * option is set to * {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL} * the context establishment process will be compatible with regular SSL * (no credential delegation support). If the option is set to * {@link GSIConstants#MODE_GSI GSIConstants.MODE_GSI} * credential delegation during context establishment process will be accepted. * If the {@link GSSConstants#REJECT_LIMITED_PROXY * GSSConstants.REJECT_LIMITED_PROXY} option is enabled, a peer * presenting limited proxy credential will be automatically * rejected and the context establishment process will be aborted. * * @return a byte[] containing the token to be sent to the peer. * null indicates that no token is generated (needs more data) */ public byte[] acceptSecContext(byte[] inBuff, int off, int len) throws GSSException { logger.debug("enter acceptSecContext"); if (!this.conn) { this.role = ACCEPT; logger.debug("enter initializing in acceptSecContext"); if (this.ctxCred.getName().isAnonymous()) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "acceptCtx00"); } if (this.ctxCred.getUsage() != GSSCredential.ACCEPT_ONLY && this.ctxCred.getUsage() != GSSCredential.INITIATE_AND_ACCEPT) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "badCredUsage"); } setCredential(); try { init(this.role); } catch (SSLException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.conn = true; logger.debug("done initializing in acceptSecContext"); } /*DEL this.out.reset(); this.in.putToken(inBuff, off, len); */ this.outByteBuff.clear(); ByteBuffer inByteBuff; if (savedInBytes != null) { if (len > 0) { byte[] allInBytes = new byte[savedInBytes.length + len]; logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n"); System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length); System.arraycopy(inBuff, off, allInBytes, savedInBytes.length, len); inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length); } else { inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length); } savedInBytes = null; } else { inByteBuff = ByteBuffer.wrap(inBuff, off, len); } switch (state) { case HANDSHAKE: try { logger.debug("STATUS BEFORE: " + this.sslEngine.getHandshakeStatus().toString()); SSLEngineResult.HandshakeStatus handshake_status = sslEngine.getHandshakeStatus(); if (handshake_status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // return null; throw new Exception("GSSAPI in HANDSHAKE state but " + "SSLEngine in NOT_HANDSHAKING state!"); } else { outByteBuff = this.sslProcessHandshake(inByteBuff, outByteBuff); } logger.debug("STATUS AFTER: " + this.sslEngine.getHandshakeStatus().toString()); outByteBuff.flip(); /*DEL if (this.conn.getHandshake().finishedP()) { */ if (this.sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // the wrap/unwrap above has resulted in handshaking // being complete on our end. logger.debug("acceptSecContext handshake finished"); handshakeFinished(); // acceptor for (X509Certificate cert : this.ctxCred.getCertificateChain()) { setGoodUntil(cert.getNotAfter()); } this.targetName = this.ctxCred.getName(); // initiator - peer /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain; try { chain = this.sslEngine.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { chain = null; } if (chain == null || chain.length == 0) { this.sourceName = new GlobusGSSName(); this.anonymity = true; } else { /*DEL X509Cert crt = (X509Cert)chain.elementAt(chain.size()-1); setGoodUntil(crt.getValidityNotAfter()); String identity = verifyChain(chain); */ for (X509Certificate cert : (X509Certificate[]) chain) { setGoodUntil(cert.getNotAfter()); } String identity = BouncyCastleUtil.getIdentity( bcConvert(BouncyCastleUtil.getIdentityCertificate((X509Certificate[]) chain))); this.sourceName = new GlobusGSSName(CertificateUtil.toGlobusID(identity, false)); this.peerLimited = Boolean.valueOf(ProxyCertificateUtil .isLimitedProxy(BouncyCastleUtil.getCertificateType((X509Certificate) chain[0]))); logger.debug("Peer Identity is: " + identity + " Target name is: " + this.targetName + " Limited Proxy: " + this.peerLimited.toString()); this.anonymity = false; } if (this.gssMode == GSIConstants.MODE_GSI) { this.state = SERVER_START_DEL; } else { setDone(); } } } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } break; case SERVER_START_DEL: try { if (inByteBuff.remaining() <= 0) { return null; } /*DEL int delChar = this.conn.getInStream().read(); */ outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); byte[] delChar = new byte[outByteBuff.remaining()]; outByteBuff.get(delChar, 0, delChar.length); /*DEL if (delChar != GSIConstants.DELEGATION_CHAR) { */ if (!Arrays.equals(delChar, DELEGATION_TOKEN)) { setDone(); break; } /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain; try { chain = this.sslEngine.getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { chain = null; } if (chain == null || chain.length == 0) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.DELEGATION_ERROR, "noClientCert"); } X509Certificate tmpCert = (X509Certificate) chain[0]; /*DEL PureTLSUtil.convertCert((X509Cert)chain.lastElement()); */ byte[] req = generateCertRequest(tmpCert); /*DEL this.conn.getOutStream().write(req, 0, req.length); */ inByteBuff = ByteBuffer.wrap(req, 0, req.length); outByteBuff.clear(); outByteBuff = sslDataWrap(inByteBuff, outByteBuff); outByteBuff.flip(); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.state = SERVER_END_DEL; break; case SERVER_END_DEL: try { if (inByteBuff.remaining() <= 0) { return null; } /*DEL X509Certificate certificate = CertUtil.loadCertificate(this.conn.getInStream()); */ outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); if (!outByteBuff.hasRemaining()) break; byte[] buf = new byte[outByteBuff.remaining()]; outByteBuff.get(buf, 0, buf.length); ByteArrayInputStream inStream = new ByteArrayInputStream(buf, 0, buf.length); CertificateFactory cf = null; X509Certificate certificate = null; try { cf = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) cf.generateCertificate(inStream); } finally { inStream.close(); } if (logger.isTraceEnabled()) { logger.trace("Received delegated cert: " + certificate.toString()); } verifyDelegatedCert(certificate); /*DEL Vector chain = this.conn.getCertificateChain(); */ Certificate[] chain = this.sslEngine.getSession().getPeerCertificates(); int chainLen = chain.length; X509Certificate[] newChain = new X509Certificate[chainLen + 1]; newChain[0] = bcConvert((X509Certificate) certificate); for (int i = 0; i < chainLen; i++) { /*DEL newChain[i+1] = PureTLSUtil.convertCert((X509Cert)chain.elementAt(chainLen - 1 - i)); */ newChain[i + 1] = bcConvert((X509Certificate) chain[i]); } X509Credential proxy = new X509Credential(this.keyPair.getPrivate(), newChain); this.delegCred = new GlobusGSSCredentialImpl(proxy, GSSCredential.INITIATE_AND_ACCEPT); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } setDone(); break; default: throw new GSSException(GSSException.FAILURE); } if (inByteBuff.hasRemaining()) { // Likely BUFFER_UNDERFLOW; save the // inByteBuff bytes here like in the unwrap() case logger.debug("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining() + " Handshaking status: " + sslEngine.getHandshakeStatus()); logger.debug("SAVING unprocessed " + inByteBuff.remaining() + "BYTES\n"); savedInBytes = new byte[inByteBuff.remaining()]; inByteBuff.get(savedInBytes, 0, savedInBytes.length); } logger.debug("exit acceptSecContext"); /*DEL return (this.out.size() > 0) ? this.out.toByteArray() : null; */ if (this.outByteBuff.hasRemaining()) { // TODO can we avoid this copy if the ByteBuffer is array based // and we return that array, each time allocating a new array // for outByteBuff? byte[] out = new byte[this.outByteBuff.remaining()]; this.outByteBuff.get(out, 0, out.length); return out; } else return null; }
From source file:org.cesecore.util.CertTools.java
public static Date getNotAfter(Certificate cert) { Date ret = null;// ww w. ja va2 s. c om if (cert == null) { throw new IllegalArgumentException("getNotAfter: cert is null"); } if (cert instanceof X509Certificate) { final X509Certificate xcert = (X509Certificate) cert; ret = xcert.getNotAfter(); } else if (StringUtils.equals(cert.getType(), "CVC")) { final CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { ret = cvccert.getCVCertificate().getCertificateBody().getValidTo(); } catch (NoSuchFieldException e) { // it is not uncommon that this field is missing in CVC certificate requests (it's not in the EAC standard so) if (log.isDebugEnabled()) { log.debug("NoSuchFieldException: " + e.getMessage()); } return null; } } return ret; }
From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java
/** * This function drives the initiating side of the context establishment * process. It is expected to be called in tandem with the * {@link #acceptSecContext(byte[], int, int) acceptSecContext} function. * <BR>//from w w w . j a va 2 s. c o m * The behavior of context establishment process can be modified by * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE}, * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE}, and * {@link GSSConstants#REJECT_LIMITED_PROXY GSSConstants.REJECT_LIMITED_PROXY} * context options. If the {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * option is set to {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL} * the context establishment process will be compatible with regular SSL * (no credential delegation support). If the option is set to * {@link GSIConstants#MODE_GSI GSIConstants.GSS_MODE_GSI} * credential delegation during context establishment process will performed. * The delegation type to be performed can be set using the * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE} * context option. If the {@link GSSConstants#REJECT_LIMITED_PROXY * GSSConstants.REJECT_LIMITED_PROXY} option is enabled, * a peer presenting limited proxy credential will be automatically * rejected and the context establishment process will be aborted. * * @return a byte[] containing the token to be sent to the peer. * null indicates that no token is generated (needs more data). */ public byte[] initSecContext(byte[] inBuff, int off, int len) throws GSSException { logger.debug("enter initSecContext"); if (!this.conn) { this.role = INITIATE; logger.debug("enter initializing in initSecContext"); if (this.anonymity || this.ctxCred.getName().isAnonymous()) { this.anonymity = true; } else { this.anonymity = false; setCredential(); if (this.ctxCred.getUsage() != GSSCredential.INITIATE_ONLY && this.ctxCred.getUsage() != GSSCredential.INITIATE_AND_ACCEPT) { throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN, "badCredUsage"); } } if (getCredDelegState()) { if (this.gssMode == GSIConstants.MODE_SSL) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "initCtx00"); } if (this.anonymity) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "initCtx01"); } } try { init(this.role); } catch (SSLException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } this.conn = true; logger.debug("done initializing in initSecContext"); } // Unless explicitly disabled, check if delegation is // requested and expected target is null logger.debug("Require authz with delegation: " + this.requireAuthzWithDelegation); if (!Boolean.FALSE.equals(this.requireAuthzWithDelegation)) { if (this.expectedTargetName == null && getCredDelegState()) { throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "initCtx02"); } } /*DEL this.out.reset(); this.in.putToken(inBuff, off, len); */ this.outByteBuff.clear(); ByteBuffer inByteBuff; if (savedInBytes != null) { if (len > 0) { byte[] allInBytes = new byte[savedInBytes.length + len]; logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n"); System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length); System.arraycopy(inBuff, off, allInBytes, savedInBytes.length, len); inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length); } else { inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length); } savedInBytes = null; } else { inByteBuff = ByteBuffer.wrap(inBuff, off, len); } switch (state) { case HANDSHAKE: try { logger.debug("STATUS BEFORE: " + this.sslEngine.getHandshakeStatus().toString()); SSLEngineResult.HandshakeStatus handshake_status = sslEngine.getHandshakeStatus(); if (handshake_status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // return null; throw new Exception("GSSAPI in HANDSHAKE state but " + "SSLEngine in NOT_HANDSHAKING state!"); } else { outByteBuff = this.sslProcessHandshake(inByteBuff, outByteBuff); } logger.debug("STATUS AFTER: " + this.sslEngine.getHandshakeStatus().toString()); outByteBuff.flip(); /*DEL this.conn.getHandshake().processHandshake(); if (this.conn.getHandshake().finishedP()) { */ if (this.sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { // the wrap/unwrap above has resulted in handshaking // being complete on our end. logger.debug("initSecContext handshake finished"); handshakeFinished(); /*DEL Vector chain = this.conn.getCertificateChain(); X509Cert crt = (X509Cert)chain.elementAt(chain.size()-1); setGoodUntil(crt.getValidityNotAfter()); */ Certificate[] chain = this.sslEngine.getSession().getPeerCertificates(); if (!(chain instanceof X509Certificate[])) { throw new Exception("Certificate chain not of type X509Certificate"); } for (X509Certificate cert : (X509Certificate[]) chain) { setGoodUntil(cert.getNotAfter()); } // acceptor - peer /*DEL String identity = verifyChain(chain); */ // chain verification would have already been done by // JSSE String identity = BouncyCastleUtil.getIdentity( bcConvert(BouncyCastleUtil.getIdentityCertificate((X509Certificate[]) chain))); this.targetName = new GlobusGSSName(CertificateUtil.toGlobusID(identity, false)); this.peerLimited = Boolean.valueOf(ProxyCertificateUtil .isLimitedProxy(BouncyCastleUtil.getCertificateType((X509Certificate) chain[0]))); logger.debug("Peer Identity is: " + identity + " Target name is: " + this.targetName + " Limited Proxy: " + this.peerLimited.toString()); // initiator if (this.anonymity) { this.sourceName = new GlobusGSSName(); } else { for (X509Certificate cert : this.ctxCred.getCertificateChain()) { setGoodUntil(cert.getNotAfter()); } this.sourceName = this.ctxCred.getName(); } // mutual authentication test if (this.expectedTargetName != null && !this.expectedTargetName.equals(this.targetName)) { throw new GlobusGSSException(GSSException.UNAUTHORIZED, GlobusGSSException.BAD_NAME, "authFailed00", new Object[] { this.expectedTargetName, this.targetName }); } if (this.gssMode == GSIConstants.MODE_GSI) { this.state = CLIENT_START_DEL; // if there is data to return then // break. otherwise we fall through!!! if (this.outByteBuff.remaining() > 0) { break; } } else { setDone(); break; } } else { break; } } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } case CLIENT_START_DEL: logger.debug("CLIENT_START_DEL"); // sanity check - might be invalid state if (this.state != CLIENT_START_DEL || this.outByteBuff.remaining() > 0) { throw new GSSException(GSSException.FAILURE); } if (inByteBuff.hasRemaining()) { throw new GlobusGSSException(GSSException.FAILURE, new Exception( "Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining() + " Handshaking status: " + sslEngine.getHandshakeStatus())); } this.outByteBuff.clear(); try { String deleg; if (getCredDelegState()) { deleg = Character.toString(GSIConstants.DELEGATION_CHAR); this.state = CLIENT_END_DEL; } else { deleg = Character.toString('0'); setDone(); } byte[] a = deleg.getBytes("US-ASCII"); inByteBuff = ByteBuffer.wrap(a, 0, a.length); outByteBuff = sslDataWrap(inByteBuff, outByteBuff); outByteBuff.flip(); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } break; case CLIENT_END_DEL: logger.debug("CLIENT_END_DEL"); if (!inByteBuff.hasRemaining()) { throw new GSSException(GSSException.DEFECTIVE_TOKEN); } ByteArrayInputStream byteArrayInputStream = null; try { /*DEL if (this.in.available() <= 0) { return null; } */ outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff); outByteBuff.flip(); if (!outByteBuff.hasRemaining()) break; byte[] certReq = new byte[outByteBuff.remaining()]; outByteBuff.get(certReq, 0, certReq.length); X509Certificate[] chain = this.ctxCred.getCertificateChain(); byteArrayInputStream = new ByteArrayInputStream(certReq); X509Certificate cert = this.certFactory.createCertificate(byteArrayInputStream, chain[0], this.ctxCred.getPrivateKey(), -1, /*DEL getDelegationType(chain[0])); */ BouncyCastleCertProcessingFactory.decideProxyType(chain[0], this.delegationType)); byte[] enc = cert.getEncoded(); /*DEL this.conn.getOutStream().write(enc, 0, enc.length); */ inByteBuff = ByteBuffer.wrap(enc, 0, enc.length); outByteBuff.clear(); outByteBuff = sslDataWrap(inByteBuff, outByteBuff); outByteBuff.flip(); setDone(); } catch (GeneralSecurityException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } catch (IOException e) { throw new GlobusGSSException(GSSException.FAILURE, e); } finally { if (byteArrayInputStream != null) { try { byteArrayInputStream.close(); } catch (Exception e) { logger.warn("Unable to close stream."); } } } break; default: throw new GSSException(GSSException.FAILURE); } if (inByteBuff.hasRemaining()) { // Likely BUFFER_UNDERFLOW; save the // inByteBuff bytes here like in the unwrap() case logger.debug("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining() + " Handshaking status: " + sslEngine.getHandshakeStatus()); logger.debug("SAVING unprocessed " + inByteBuff.remaining() + "BYTES\n"); savedInBytes = new byte[inByteBuff.remaining()]; inByteBuff.get(savedInBytes, 0, savedInBytes.length); } logger.debug("exit initSecContext"); //XXX: Why is here a check for CLIENT_START_DEL? // if (this.outByteBuff.hasRemaining() || this.state == CLIENT_START_DEL) { if (this.outByteBuff.hasRemaining()) { // TODO can we avoid this copy if the ByteBuffer is array based // and we return that array, each time allocating a new array // for outByteBuff? byte[] out = new byte[this.outByteBuff.remaining()]; this.outByteBuff.get(out, 0, out.length); return out; } else return null; }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
/** Checks the signature on an OCSP request and checks that it is signed by an allowed CA. * Does not check for revocation of the signer certificate * /*from w w w. j ava 2 s . c o m*/ * @param clientRemoteAddr The ip address or hostname of the remote client that sent the request, can be null. * @param req The signed OCSPReq * @param cacerts a CertificateCache of Certificates, the authorized CA-certificates. The signer certificate must be issued by one of these. * @return X509Certificate which is the certificate that signed the OCSP request * @throws SignRequestSignatureException if signature verification fail, or if the signing certificate is not authorized * @throws SignRequestException if there is no signature on the OCSPReq * @throws OCSPException if the request can not be parsed to retrieve certificates * @throws NoSuchProviderException if the BC provider is not installed * @throws CertificateException if the certificate can not be parsed * @throws NoSuchAlgorithmException if the certificate contains an unsupported algorithm * @throws InvalidKeyException if the certificate, or CA key is invalid * @throws OperatorCreationException */ public static X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req, CaCertificateCache cacerts) throws SignRequestException, OCSPException, NoSuchProviderException, CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignRequestSignatureException, OperatorCreationException { X509Certificate signercert = null; if (!req.isSigned()) { String infoMsg = intres.getLocalizedMessage("ocsp.errorunsignedreq", clientRemoteAddr); log.info(infoMsg); throw new SignRequestException(infoMsg); } // Get all certificates embedded in the request (probably a certificate chain) X509CertificateHolder[] certs = req.getCerts(); // Set, as a try, the signer to be the first certificate, so we have a name to log... String signer = null; JcaX509CertificateConverter converter = new JcaX509CertificateConverter(); if (certs.length > 0) { signer = CertTools.getSubjectDN(converter.getCertificate(certs[0])); } // We must find a cert to verify the signature with... boolean verifyOK = false; for (int i = 0; i < certs.length; i++) { if (req.isSignatureValid(new JcaContentVerifierProviderBuilder().build(certs[i])) == true) { signercert = converter.getCertificate(certs[i]); signer = CertTools.getSubjectDN(signercert); Date now = new Date(); String signerissuer = CertTools.getIssuerDN(signercert); String infoMsg = intres.getLocalizedMessage("ocsp.infosigner", signer); log.info(infoMsg); verifyOK = true; // Also check that the signer certificate can be verified by one of the CA-certificates // that we answer for X509Certificate signerca = cacerts.findLatestBySubjectDN(HashID.getFromIssuerDN(certs[i])); String subject = signer; String issuer = signerissuer; if (signerca != null) { try { signercert.verify(signerca.getPublicKey()); if (log.isDebugEnabled()) { log.debug("Checking validity. Now: " + now + ", signerNotAfter: " + signercert.getNotAfter()); } CertTools.checkValidity(signercert, now); // Move the error message string to the CA cert subject = CertTools.getSubjectDN(signerca); issuer = CertTools.getIssuerDN(signerca); CertTools.checkValidity(signerca, now); } catch (SignatureException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (InvalidKeyException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (CertificateNotYetValidException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (CertificateExpiredException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certexpired", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } } else { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.nocacert", signer, signerissuer); log.info(infoMsg); verifyOK = false; } break; } } if (!verifyOK) { String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signer); log.info(errMsg); throw new SignRequestSignatureException(errMsg); } return signercert; }
From source file:org.cesecore.certificates.ocsp.CanLogCache.java
/** * Checks the signature on an OCSP request and checks that it is signed by an allowed CA. Does not check for revocation of the signer certificate * /* w w w.j a v a 2 s.co m*/ * @param clientRemoteAddr The IP address or host name of the remote client that sent the request, can be null. * @param req The signed OCSPReq * @return X509Certificate which is the certificate that signed the OCSP request * @throws SignRequestSignatureException if signature verification fail, or if the signing certificate is not authorized * @throws SignRequestException if there is no signature on the OCSPReq * @throws OCSPException if the request can not be parsed to retrieve certificates * @throws NoSuchProviderException if the BC provider is not installed * @throws CertificateException if the certificate can not be parsed * @throws NoSuchAlgorithmException if the certificate contains an unsupported algorithm * @throws InvalidKeyException if the certificate, or CA key is invalid */ private X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req) throws SignRequestException, SignRequestSignatureException, CertificateException, NoSuchAlgorithmException { X509Certificate signercert = null; if (!req.isSigned()) { String infoMsg = intres.getLocalizedMessage("ocsp.errorunsignedreq", clientRemoteAddr); log.info(infoMsg); throw new SignRequestException(infoMsg); } // Get all certificates embedded in the request (probably a certificate chain) try { X509Certificate[] certs = req.getCerts("BC"); // Set, as a try, the signer to be the first certificate, so we have a name to log... String signer = null; if (certs.length > 0) { signer = CertTools.getSubjectDN(certs[0]); } // We must find a certificate to verify the signature with... boolean verifyOK = false; for (int i = 0; i < certs.length; i++) { if (req.verify(certs[i].getPublicKey(), "BC") == true) { signercert = certs[i]; signer = CertTools.getSubjectDN(signercert); Date now = new Date(); String signerissuer = CertTools.getIssuerDN(signercert); String infoMsg = intres.getLocalizedMessage("ocsp.infosigner", signer); log.info(infoMsg); verifyOK = true; /* * Also check that the signer certificate can be verified by one of the CA-certificates that we answer for */ X509Certificate signerca = certificateStoreSession .findLatestX509CertificateBySubject(CertTools.getIssuerDN(certs[i])); String subject = signer; String issuer = signerissuer; if (signerca != null) { try { signercert.verify(signerca.getPublicKey()); if (log.isDebugEnabled()) { log.debug("Checking validity. Now: " + now + ", signerNotAfter: " + signercert.getNotAfter()); } CertTools.checkValidity(signercert, now); // Move the error message string to the CA cert subject = CertTools.getSubjectDN(signerca); issuer = CertTools.getIssuerDN(signerca); CertTools.checkValidity(signerca, now); } catch (SignatureException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (InvalidKeyException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (CertificateNotYetValidException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (CertificateExpiredException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certexpired", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } } else { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.nocacert", signer, signerissuer); log.info(infoMsg); verifyOK = false; } break; } } if (!verifyOK) { String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signer); log.info(errMsg); throw new SignRequestSignatureException(errMsg); } } catch (OCSPException e) { throw new CryptoProviderException("BouncyCastle was not initialized properly.", e); } catch (NoSuchProviderException e) { throw new CryptoProviderException("BouncyCastle was not found as a provider.", e); } return signercert; }
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 www .j a va 2s .c om 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); }