List of usage examples for java.security.cert X509Certificate getEncoded
public abstract byte[] getEncoded() throws CertificateEncodingException;
From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java
/** * Initiate the delegation of a credential. * * This function drives the initiating side of the credential * delegation process. It is expected to be called in tandem with the * {@link #acceptDelegation(int, byte[], int, int) acceptDelegation} * function./* w ww . j a va2 s . c o m*/ * <BR> * The behavior of this function can be modified by * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE} * and * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} context * options. * The {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE} * option controls delegation type to be performed. The * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE} * option if set to * {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL} * results in tokens that are not wrapped. * * @param credential * The credential to be delegated. May be null * in which case the credential associated with the security * context is used. * @param mechanism * The desired security mechanism. May be null. * @param lifetime * The requested period of validity (seconds) of the delegated * credential. * @return A token that should be passed to <code>acceptDelegation</code> if * <code>isDelegationFinished</code> returns false. May be null. * @exception GSSException containing the following major error codes: * <code>GSSException.FAILURE</code> */ public byte[] initDelegation(GSSCredential credential, Oid mechanism, int lifetime, byte[] buf, int off, int len) throws GSSException { logger.debug("Enter initDelegation: " + delegationState); if (mechanism != null && !mechanism.equals(getMech())) { throw new GSSException(GSSException.BAD_MECH); } if (this.gssMode != GSIConstants.MODE_SSL && buf != null && len > 0) { buf = unwrap(buf, off, len); off = 0; len = buf.length; } byte[] token = null; switch (delegationState) { case DELEGATION_START: this.delegationFinished = false; token = DELEGATION_TOKEN; this.delegationState = DELEGATION_SIGN_CERT; break; case DELEGATION_SIGN_CERT: if (credential == null) { // get default credential GSSManager manager = new GlobusGSSManagerImpl(); credential = manager.createCredential(GSSCredential.INITIATE_AND_ACCEPT); } if (!(credential instanceof GlobusGSSCredentialImpl)) { throw new GSSException(GSSException.DEFECTIVE_CREDENTIAL); } X509Credential cred = ((GlobusGSSCredentialImpl) credential).getX509Credential(); X509Certificate[] chain = cred.getCertificateChain(); int time = (lifetime == GSSCredential.DEFAULT_LIFETIME) ? -1 : lifetime; ByteArrayInputStream inData = null; ByteArrayOutputStream out = null; try { inData = new ByteArrayInputStream(buf, off, len); X509Certificate cert = this.certFactory.createCertificate(inData, chain[0], cred.getPrivateKey(), time, /*DEL getDelegationType(chain[0])); */ BouncyCastleCertProcessingFactory.decideProxyType(chain[0], this.delegationType)); out = new ByteArrayOutputStream(); out.write(cert.getEncoded()); for (int i = 0; i < chain.length; i++) { out.write(chain[i].getEncoded()); } token = out.toByteArray(); } catch (Exception e) { throw new GlobusGSSException(GSSException.FAILURE, e); } finally { if (inData != null) { try { inData.close(); } catch (Exception e) { logger.warn("Unable to close stream."); } } if (out != null) { try { out.close(); } catch (Exception e) { logger.warn("Unable to close stream."); } } } this.delegationState = DELEGATION_START; this.delegationFinished = true; break; default: throw new GSSException(GSSException.FAILURE); } logger.debug("Exit initDelegation"); if (this.gssMode != GSIConstants.MODE_SSL && token != null) { // XXX: Why wrap() only when not in MODE_SSL? return wrap(token, 0, token.length); } else { return token; } }
From source file:org.gluu.oxtrust.action.UpdateTrustRelationshipAction.java
/** * If there is no certificate selected, or certificate is invalid - * generates one.//from w w w.j ava 2 s . com * * @author Oleksiy Tataryn * @return certificate for generated SP * @throws CertificateEncodingException */ private String getCertForGeneratedSP() { X509Certificate cert = SSLService.instance().getCertificate(certWrapper.getStream()); if (cert == null) { facesMessages.add(Severity.INFO, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate."); if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); } try { JDKKeyPairGenerator.RSA keyPairGen = new JDKKeyPairGenerator.RSA(); keyPairGen.initialize(2048); KeyPair pair = keyPairGen.generateKeyPair(); StringWriter keyWriter = new StringWriter(); PEMWriter pemFormatWriter = new PEMWriter(keyWriter); pemFormatWriter.writeObject(pair.getPrivate()); pemFormatWriter.close(); String url = trustRelationship.getUrl().replaceFirst(".*//", ""); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder( new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), BigInteger.valueOf(new SecureRandom().nextInt()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)), new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic()); cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build( new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate()))); org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64); byte[] derCert = cert.getEncoded(); String pemCertPre = new String(encoder.encode(derCert)); log.debug(Shibboleth2ConfService.PUBLIC_CERTIFICATE_START_LINE); log.debug(pemCertPre); log.debug(Shibboleth2ConfService.PUBLIC_CERTIFICATE_END_LINE); saveCert(trustRelationship, pemCertPre); saveKey(trustRelationship, keyWriter.toString()); } catch (Exception e) { e.printStackTrace(); } // String certName = applicationConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(applicationConfiguration.getOrgInum()) // + "-shib.crt"; // File certFile = new File(certName); // if (certFile.exists()) { // cert = SSLService.instance().getCertificate(certName); // } } String certificate = null; if (cert != null) { try { certificate = new String(Base64.encode(cert.getEncoded())); } catch (CertificateEncodingException e) { certificate = null; facesMessages.add(Severity.ERROR, "Failed to encode provided certificate. Please notify Gluu support about this."); log.error("Failed to encode certificate to DER", e); } } else { facesMessages.add(Severity.INFO, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate."); } return certificate; }
From source file:be.fedict.trust.ocsp.OcspTrustLinker.java
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData) { URI ocspUri = getOcspUri(childCertificate); if (null == ocspUri) { return null; }// w w w . j a v a 2 s . co m LOG.debug("OCSP URI: " + ocspUri); OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate); if (null == ocspResp) { LOG.debug("OCSP response not found"); return null; } int ocspRespStatus = ocspResp.getStatus(); if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) { LOG.debug("OCSP response status: " + ocspRespStatus); return null; } Object responseObject; try { responseObject = ocspResp.getResponseObject(); } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject; try { X509Certificate[] responseCertificates = basicOCSPResp.getCerts(BouncyCastleProvider.PROVIDER_NAME); for (X509Certificate responseCertificate : responseCertificates) { LOG.debug("OCSP response cert: " + responseCertificate.getSubjectX500Principal()); LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuerX500Principal()); } TrustLinkerResult trustResult = TrustValidator .checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgName()); if (!trustResult.isValid()) return trustResult; if (0 == responseCertificates.length) { /* * This means that the OCSP response has been signed by the * issuing CA itself. */ boolean verificationResult = basicOCSPResp.verify(certificate.getPublicKey(), BouncyCastleProvider.PROVIDER_NAME); if (false == verificationResult) { LOG.debug("OCSP response signature invalid"); return null; } } else { /* * We're dealing with a dedicated authorized OCSP Responder * certificate, or of course with a CA that issues the OCSP * Responses itself. */ X509Certificate ocspResponderCertificate = responseCertificates[0]; boolean verificationResult = basicOCSPResp.verify(ocspResponderCertificate.getPublicKey(), BouncyCastleProvider.PROVIDER_NAME); if (false == verificationResult) { LOG.debug("OCSP Responser response signature invalid"); return null; } if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) { // check certificate signature trustResult = TrustValidator.checkSignatureAlgorithm(ocspResponderCertificate.getSigAlgName()); if (!trustResult.isValid()) { return trustResult; } X509Certificate issuingCaCertificate; if (responseCertificates.length < 2) { LOG.debug("OCSP responder complete certificate chain missing"); /* * Here we assume that the OCSP Responder is directly * signed by the CA. */ issuingCaCertificate = certificate; } else { issuingCaCertificate = responseCertificates[1]; /* * Is next check really required? */ if (false == certificate.equals(issuingCaCertificate)) { LOG.debug("OCSP responder certificate not issued by CA"); return null; } } // check certificate signature trustResult = TrustValidator.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgName()); if (!trustResult.isValid()) { return trustResult; } PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker(); trustResult = publicKeyTrustLinker.hasTrustLink(ocspResponderCertificate, issuingCaCertificate, validationDate, revocationData); if (null != trustResult) { if (!trustResult.isValid()) { LOG.debug("OCSP responder not trusted"); return null; } } if (null == ocspResponderCertificate .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) { LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck"); /* * TODO: perform CRL validation on the OCSP Responder * certificate. On the other hand, do we really want to * check the checker? */ return null; } List<String> extendedKeyUsage; try { extendedKeyUsage = ocspResponderCertificate.getExtendedKeyUsage(); } catch (CertificateParsingException e) { LOG.debug("OCSP Responder parsing error: " + e.getMessage(), e); return null; } if (null == extendedKeyUsage) { LOG.debug("OCSP Responder certificate has no extended key usage extension"); return null; } if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) { LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage"); return null; } } else { LOG.debug("OCSP Responder certificate equals the CA certificate"); } } } catch (NoSuchProviderException e) { LOG.debug("JCA provider exception: " + e.getMessage(), e); return null; } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } catch (CertificateEncodingException e) { LOG.debug("certificate encoding error: " + e.getMessage(), e); return null; } CertificateID certificateId; try { certificateId = new CertificateID(CertificateID.HASH_SHA1, certificate, childCertificate.getSerialNumber()); } catch (OCSPException e) { LOG.debug("OCSP exception: " + e.getMessage(), e); return null; } SingleResp[] singleResps = basicOCSPResp.getResponses(); for (SingleResp singleResp : singleResps) { CertificateID responseCertificateId = singleResp.getCertID(); if (false == certificateId.equals(responseCertificateId)) { continue; } Date thisUpdate = singleResp.getThisUpdate(); LOG.debug("OCSP thisUpdate: " + thisUpdate); LOG.debug("OCSP nextUpdate: " + singleResp.getNextUpdate()); long dt = Math.abs(thisUpdate.getTime() - validationDate.getTime()); if (dt > this.freshnessInterval) { LOG.warn("freshness interval exceeded: " + dt + " milliseconds"); continue; } if (null == singleResp.getCertStatus()) { LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal()); addRevocationData(revocationData, ocspResp); return new TrustLinkerResult(true); } else { LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName()); if (singleResp.getCertStatus() instanceof RevokedStatus) { LOG.debug("OCSP status revoked"); } addRevocationData(revocationData, ocspResp); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS, "certificate revoked by OCSP"); } } LOG.debug("no matching OCSP response entry"); return null; }
From source file:be.fedict.eid.tsl.TrustServiceList.java
public void addXadesBes(XMLSignatureFactory signatureFactory, Document document, String signatureId, X509Certificate signingCertificate, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { LOG.debug("preSign"); // QualifyingProperties QualifyingPropertiesType qualifyingProperties = this.xadesObjectFactory.createQualifyingPropertiesType(); qualifyingProperties.setTarget("#" + signatureId); // SignedProperties SignedPropertiesType signedProperties = this.xadesObjectFactory.createSignedPropertiesType(); String signedPropertiesId = signatureId + "-xades"; signedProperties.setId(signedPropertiesId); qualifyingProperties.setSignedProperties(signedProperties); // SignedSignatureProperties SignedSignaturePropertiesType signedSignatureProperties = this.xadesObjectFactory .createSignedSignaturePropertiesType(); signedProperties.setSignedSignatureProperties(signedSignatureProperties); // SigningTime GregorianCalendar signingTime = new GregorianCalendar(); signingTime.setTimeZone(TimeZone.getTimeZone("Z")); XMLGregorianCalendar xmlSigningTime = this.datatypeFactory.newXMLGregorianCalendar(signingTime); xmlSigningTime.setMillisecond(DatatypeConstants.FIELD_UNDEFINED); signedSignatureProperties.setSigningTime(xmlSigningTime); // SigningCertificate CertIDListType signingCertificates = this.xadesObjectFactory.createCertIDListType(); CertIDType signingCertificateId = this.xadesObjectFactory.createCertIDType(); X509IssuerSerialType issuerSerial = this.xmldsigObjectFactory.createX509IssuerSerialType(); issuerSerial.setX509IssuerName(signingCertificate.getIssuerX500Principal().toString()); issuerSerial.setX509SerialNumber(signingCertificate.getSerialNumber()); signingCertificateId.setIssuerSerial(issuerSerial); DigestAlgAndValueType certDigest = this.xadesObjectFactory.createDigestAlgAndValueType(); DigestMethodType jaxbDigestMethod = this.xmldsigObjectFactory.createDigestMethodType(); jaxbDigestMethod.setAlgorithm(DigestMethod.SHA256); certDigest.setDigestMethod(jaxbDigestMethod); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] digestValue; try {/* w ww.ja va2 s.co m*/ digestValue = messageDigest.digest(signingCertificate.getEncoded()); } catch (CertificateEncodingException e) { throw new RuntimeException("certificate encoding error: " + e.getMessage(), e); } certDigest.setDigestValue(digestValue); signingCertificateId.setCertDigest(certDigest); signingCertificates.getCert().add(signingCertificateId); signedSignatureProperties.setSigningCertificate(signingCertificates); // marshall XAdES QualifyingProperties Node qualifyingPropertiesNode = marshallQualifyingProperties(document, qualifyingProperties); // add XAdES ds:Object List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>(); xadesObjectContent.add(new DOMStructure(qualifyingPropertiesNode)); XMLObject xadesObject = signatureFactory.newXMLObject(xadesObjectContent, null, null, null); objects.add(xadesObject); // add XAdES ds:Reference DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null); List<Transform> transforms = new LinkedList<Transform>(); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("#" + signedPropertiesId, digestMethod, transforms, XADES_TYPE, null); references.add(reference); }
From source file:org.apache.juddi.webconsole.hub.UddiHub.java
/** * converts a UDDI Signature Type element into a base64 string * containing the raw data for the signing certificate, if present * * @param sig/*from w w w.j a v a2 s .com*/ * @return x509 cert */ public String SignatureToBase64(SignatureType sig) { if (sig == null) { return "Error, the signature was nullavailable"; } for (int i = 0; i < sig.getKeyInfo().getContent().size(); i++) { JAXBElement get = (JAXBElement) sig.getKeyInfo().getContent().get(i); if (get.getValue() instanceof org.w3._2000._09.xmldsig_.X509DataType) { X509DataType xd = (X509DataType) get.getValue(); for (int k = 0; k < xd.getX509IssuerSerialOrX509SKIOrX509SubjectName().size(); k++) { if (xd.getX509IssuerSerialOrX509SKIOrX509SubjectName().get(k) instanceof JAXBElement) { JAXBElement element = (JAXBElement) xd.getX509IssuerSerialOrX509SKIOrX509SubjectName() .get(k); if (element.getValue() instanceof byte[]) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream is = new ByteArrayInputStream((byte[]) element.getValue()); X509Certificate cert = (X509Certificate) cf.generateCertificate(is); is.close(); //this is the most supportable way to do this return org.apache.commons.codec.binary.Base64.encodeBase64String(cert.getEncoded()); //BASE64Encoder encoder = new BASE64Encoder(); //return encoder.encodeBuffer(cert.getEncoded()); } catch (Exception ex) { return HandleException(ex); } } else if (element.getValue() instanceof String) { } } } } } return ResourceLoader.GetResource(session, "errors.nocertavaiable"); }
From source file:be.fedict.eid.tsl.TrustServiceList.java
public void addOtherTSLPointer(String location, String mimeType, String tslType, String schemeTerritory, String schemeOperatorName, String schemeTypeCommunityRuleUri, Locale schemeTypeCommunityRuleUriLocale, X509Certificate digitalIdentityCertificate) { TSLSchemeInformationType schemeInformation = getSchemeInformation(); OtherTSLPointersType otherTSLPointers = schemeInformation.getPointersToOtherTSL(); if (null == otherTSLPointers) { otherTSLPointers = this.objectFactory.createOtherTSLPointersType(); schemeInformation.setPointersToOtherTSL(otherTSLPointers); }// w w w .j ava 2s . c o m List<OtherTSLPointerType> pointerList = otherTSLPointers.getOtherTSLPointer(); OtherTSLPointerType otherTSLPointer = this.objectFactory.createOtherTSLPointerType(); pointerList.add(otherTSLPointer); otherTSLPointer.setTSLLocation(location); AdditionalInformationType additionalInformation = this.objectFactory.createAdditionalInformationType(); otherTSLPointer.setAdditionalInformation(additionalInformation); List<Object> objects = additionalInformation.getTextualInformationOrOtherInformation(); { JAXBElement<String> mimeTypeElement = this.tslxObjectFactory.createMimeType(mimeType); AnyType anyType = this.objectFactory.createAnyType(); anyType.getContent().add(mimeTypeElement); objects.add(anyType); } { JAXBElement<String> tslTypeElement = this.objectFactory.createTSLType(tslType); AnyType anyType = this.objectFactory.createAnyType(); anyType.getContent().add(tslTypeElement); objects.add(anyType); } { JAXBElement<String> schemeTerritoryElement = this.objectFactory.createSchemeTerritory(schemeTerritory); AnyType anyType = this.objectFactory.createAnyType(); anyType.getContent().add(schemeTerritoryElement); objects.add(anyType); } { InternationalNamesType i18nNames = this.objectFactory.createInternationalNamesType(); MultiLangNormStringType i18nName = this.objectFactory.createMultiLangNormStringType(); i18nName.setLang("en"); i18nName.setValue(schemeOperatorName); i18nNames.getName().add(i18nName); JAXBElement<InternationalNamesType> schemeOperatorNameElement = this.objectFactory .createSchemeOperatorName(i18nNames); AnyType anyType = this.objectFactory.createAnyType(); anyType.getContent().add(schemeOperatorNameElement); objects.add(anyType); } { NonEmptyMultiLangURIListType uriList = this.objectFactory.createNonEmptyMultiLangURIListType(); NonEmptyMultiLangURIType uri = this.objectFactory.createNonEmptyMultiLangURIType(); uri.setLang(schemeTypeCommunityRuleUriLocale.getLanguage()); uri.setValue(schemeTypeCommunityRuleUri); uriList.getURI().add(uri); JAXBElement<NonEmptyMultiLangURIListType> schemeTypeCommunityRulesElement = this.objectFactory .createSchemeTypeCommunityRules(uriList); AnyType anyType = this.objectFactory.createAnyType(); anyType.getContent().add(schemeTypeCommunityRulesElement); objects.add(anyType); } if (null != digitalIdentityCertificate) { ServiceDigitalIdentityListType serviceDigitalIdentityList = this.objectFactory .createServiceDigitalIdentityListType(); DigitalIdentityListType digitalIdentityList = this.objectFactory.createDigitalIdentityListType(); List<DigitalIdentityType> digitalIdentities = digitalIdentityList.getDigitalId(); DigitalIdentityType digitalIdentity = this.objectFactory.createDigitalIdentityType(); try { digitalIdentity.setX509Certificate(digitalIdentityCertificate.getEncoded()); } catch (CertificateEncodingException e) { throw new RuntimeException("X509 encoding error: " + e.getMessage(), e); } digitalIdentities.add(digitalIdentity); digitalIdentity = this.objectFactory.createDigitalIdentityType(); digitalIdentity.setX509SubjectName(digitalIdentityCertificate.getSubjectX500Principal().getName()); digitalIdentities.add(digitalIdentity); byte[] skiValue = digitalIdentityCertificate .getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId()); if (null != skiValue) { digitalIdentity = this.objectFactory.createDigitalIdentityType(); SubjectKeyIdentifierStructure subjectKeyIdentifierStructure; try { subjectKeyIdentifierStructure = new SubjectKeyIdentifierStructure(skiValue); } catch (IOException e) { throw new RuntimeException("X509 SKI decoding error: " + e.getMessage(), e); } digitalIdentity.setX509SKI(subjectKeyIdentifierStructure.getKeyIdentifier()); digitalIdentities.add(digitalIdentity); } List<DigitalIdentityListType> digitalIdentityListList = serviceDigitalIdentityList .getServiceDigitalIdentity(); digitalIdentityListList.add(digitalIdentityList); otherTSLPointer.setServiceDigitalIdentities(serviceDigitalIdentityList); } }
From source file:com.vmware.identity.idm.server.provider.vmwdirectory.VMwareDirectoryProvider.java
private PrincipalId updateServicePrincipalDetailInContainer(String userName, SolutionDetail detail, String containerDn) throws Exception { ILdapConnectionEx connection = getConnection(); ArrayList<LdapMod> attributeList = new ArrayList<LdapMod>(); ILdapMessage message = null;//from w w w . ja v a 2 s . com String userDn = null; try { ValidateUtil.validateNotEmpty(containerDn, "container Dn"); String domainName = getDomain(); String[] attrNames = { ATTR_NAME_ACCOUNT }; String filter = buildQueryBySrvFilter(new PrincipalId(userName, this.getDomain())); message = connection.search(containerDn, LdapScope.SCOPE_SUBTREE, filter, attrNames, false); ILdapEntry[] entries = message.getEntries(); if (entries != null && entries.length == 1) { // found the user userDn = entries[0].getDN(); } else { // The user doesn't exist. // There shouldn't be the case that there will be two users // with same account name in lotus, this should be prevented // when adding a user. throw new InvalidPrincipalException(String.format("user %s already exists", userName), String.format("%s@%s", userName, getDomain())); } // We might need to delete that attribute for such case? // For now just use REPLACE. String desc = detail.getDescription(); if (null != desc && !desc.isEmpty()) { LdapMod attrDescription = new LdapMod(LdapModOperation.REPLACE, ATTR_SVC_DESCRIPTION, new LdapValue[] { LdapValue.fromString(desc) }); attributeList.add(attrDescription); } X509Certificate cert = detail.getCertificate(); if (cert != null) { Principal subjectDN = cert.getSubjectX500Principal(); // vmwSTSSubjectDn is a MUST attribute ValidateUtil.validateNotNull(subjectDN, "Solution userCertificate subjectDn"); ValidateUtil.validateNotEmpty(subjectDN.getName(), "Solution userCertificate subjectDn"); LdapMod attrSubjectDN = new LdapMod(LdapModOperation.REPLACE, ATTR_NAME_SUBJECTDN, new LdapValue[] { LdapValue.fromString(subjectDN.getName()) }); attributeList.add(attrSubjectDN); byte[] certBytes = cert.getEncoded(); assert (certBytes != null); LdapMod attrCert = new LdapMod(LdapModOperation.REPLACE, ATTR_NAME_CERT, new LdapValue[] { new LdapValue(certBytes) }); attributeList.add(attrCert); } else { throw new InvalidArgumentException(String.format( "updateServicePrincipal for user %s fails: solution must have certificate", userName)); } if (attributeList.size() > 0) { // Only update when necessary connection.modifyObject(userDn, attributeList.toArray(new LdapMod[attributeList.size()])); } return new PrincipalId(userName, domainName); } finally { if (null != message) { message.close(); } connection.close(); } }
From source file:be.fedict.eid.dss.ws.DSSUtil.java
/** * Adds a DSS Verification Report to specified optional output element from * the specified list of {@link SignatureInfo}'s * /*from www . j a va2 s .c o m*/ * @param optionalOutput * optional output to add verification report to * @param signatureInfos * signature infos to use in verification report. */ public static void addVerificationReport(AnyType optionalOutput, List<SignatureInfo> signatureInfos) { LOG.debug("return verification report"); VerificationReportType verificationReport = vrObjectFactory.createVerificationReportType(); List<IndividualReportType> individualReports = verificationReport.getIndividualReport(); for (SignatureInfo signatureInfo : signatureInfos) { X509Certificate signerCertificate = signatureInfo.getSigner(); IndividualReportType individualReport = vrObjectFactory.createIndividualReportType(); individualReports.add(individualReport); SignedObjectIdentifierType signedObjectIdentifier = vrObjectFactory.createSignedObjectIdentifierType(); individualReport.setSignedObjectIdentifier(signedObjectIdentifier); SignedPropertiesType signedProperties = vrObjectFactory.createSignedPropertiesType(); signedObjectIdentifier.setSignedProperties(signedProperties); SignedSignaturePropertiesType signedSignatureProperties = vrObjectFactory .createSignedSignaturePropertiesType(); signedProperties.setSignedSignatureProperties(signedSignatureProperties); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(signatureInfo.getSigningTime()); signedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar)); be.fedict.eid.dss.ws.profile.vr.jaxb.dss.Result individualResult = vrDssObjectFactory.createResult(); individualReport.setResult(individualResult); individualResult.setResultMajor(DSSConstants.RESULT_MAJOR_SUCCESS); individualResult.setResultMinor(DSSConstants.RESULT_MINOR_VALID_SIGNATURE); be.fedict.eid.dss.ws.profile.vr.jaxb.dss.AnyType details = vrDssObjectFactory.createAnyType(); individualReport.setDetails(details); DetailedSignatureReportType detailedSignatureReport = vrObjectFactory .createDetailedSignatureReportType(); details.getAny().add(vrObjectFactory.createDetailedSignatureReport(detailedSignatureReport)); VerificationResultType formatOKVerificationResult = vrObjectFactory.createVerificationResultType(); formatOKVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); detailedSignatureReport.setFormatOK(formatOKVerificationResult); SignatureValidityType signatureOkSignatureValidity = vrObjectFactory.createSignatureValidityType(); detailedSignatureReport.setSignatureOK(signatureOkSignatureValidity); VerificationResultType sigMathOkVerificationResult = vrObjectFactory.createVerificationResultType(); signatureOkSignatureValidity.setSigMathOK(sigMathOkVerificationResult); sigMathOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); if (null != signatureInfo.getRole()) { PropertiesType properties = vrObjectFactory.createPropertiesType(); detailedSignatureReport.setProperties(properties); SignedPropertiesType vrSignedProperties = vrObjectFactory.createSignedPropertiesType(); properties.setSignedProperties(vrSignedProperties); SignedSignaturePropertiesType vrSignedSignatureProperties = vrObjectFactory .createSignedSignaturePropertiesType(); vrSignedProperties.setSignedSignatureProperties(vrSignedSignatureProperties); vrSignedSignatureProperties.setSigningTime(datatypeFactory.newXMLGregorianCalendar(calendar)); SignerRoleType signerRole = vrObjectFactory.createSignerRoleType(); vrSignedSignatureProperties.setSignerRole(signerRole); ClaimedRolesListType claimedRolesList = vrXadesObjectFactory.createClaimedRolesListType(); signerRole.setClaimedRoles(claimedRolesList); be.fedict.eid.dss.ws.profile.vr.jaxb.xades.AnyType claimedRoleAny = vrXadesObjectFactory .createAnyType(); claimedRolesList.getClaimedRole().add(claimedRoleAny); claimedRoleAny.getContent().add(signatureInfo.getRole()); } CertificatePathValidityType certificatePathValidity = vrObjectFactory .createCertificatePathValidityType(); detailedSignatureReport.setCertificatePathValidity(certificatePathValidity); VerificationResultType certPathVerificationResult = vrObjectFactory.createVerificationResultType(); certPathVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); certificatePathValidity.setPathValiditySummary(certPathVerificationResult); X509IssuerSerialType certificateIdentifier = vrXmldsigObjectFactory.createX509IssuerSerialType(); certificatePathValidity.setCertificateIdentifier(certificateIdentifier); certificateIdentifier.setX509IssuerName(signerCertificate.getIssuerX500Principal().toString()); certificateIdentifier.setX509SerialNumber(signerCertificate.getSerialNumber()); CertificatePathValidityVerificationDetailType certificatePathValidityVerificationDetail = vrObjectFactory .createCertificatePathValidityVerificationDetailType(); certificatePathValidity.setPathValidityDetail(certificatePathValidityVerificationDetail); CertificateValidityType certificateValidity = vrObjectFactory.createCertificateValidityType(); certificatePathValidityVerificationDetail.getCertificateValidity().add(certificateValidity); certificateValidity.setCertificateIdentifier(certificateIdentifier); certificateValidity.setSubject(signerCertificate.getSubjectX500Principal().toString()); VerificationResultType chainingOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateValidity.setChainingOK(chainingOkVerificationResult); chainingOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); VerificationResultType validityPeriodOkVerificationResult = vrObjectFactory .createVerificationResultType(); certificateValidity.setValidityPeriodOK(validityPeriodOkVerificationResult); validityPeriodOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); VerificationResultType extensionsOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateValidity.setExtensionsOK(extensionsOkVerificationResult); extensionsOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); try { certificateValidity.setCertificateValue(signerCertificate.getEncoded()); } catch (CertificateEncodingException e) { throw new RuntimeException("X509 encoding error: " + e.getMessage(), e); } certificateValidity.setSignatureOK(signatureOkSignatureValidity); CertificateStatusType certificateStatus = vrObjectFactory.createCertificateStatusType(); certificateValidity.setCertificateStatus(certificateStatus); VerificationResultType certStatusOkVerificationResult = vrObjectFactory.createVerificationResultType(); certificateStatus.setCertStatusOK(certStatusOkVerificationResult); certStatusOkVerificationResult.setResultMajor(DSSConstants.VR_RESULT_MAJOR_VALID); } Document newDocument = documentBuilder.newDocument(); Element newElement = newDocument.createElement("newNode"); try { vrMarshaller.marshal(vrObjectFactory.createVerificationReport(verificationReport), newElement); } catch (JAXBException e) { throw new RuntimeException("JAXB error: " + e.getMessage(), e); } Element verificationReportElement = (Element) newElement.getFirstChild(); optionalOutput.getAny().add(verificationReportElement); }
From source file:com.vmware.identity.idm.server.provider.vmwdirectory.VMwareDirectoryProvider.java
private PrincipalId addServicePrincipalInternal(String accountName, SolutionDetail detail) throws Exception { ILdapConnectionEx connection = getConnection(); ILdapMessage message = null;// www . jav a2 s . co m ArrayList<LdapMod> attributeList = new ArrayList<LdapMod>(); final String domainName = getDomain(); final PrincipalId newSolutionUserId = new PrincipalId(accountName, domainName); try { if (existsPrincipal(accountName, newSolutionUserId, connection)) { // There exists a user or group already with the same name // Due to limitation on SSO1 interface, this is forbidden. // In another word, we can not have a user, solution user or group // with the same name. throw new InvalidPrincipalException(String.format( "Another user or group already exists with the same name: accountName=%s, domain=%s", accountName, domainName), newSolutionUserId.getUPN()); } // Detect duplicate certificate that has the same subject DN String[] attrNames = { ATTR_NAME_ACCOUNT, ATTR_NAME_CERT }; X509Certificate cert = detail.getCertificate(); if (cert == null) { throw new InvalidArgumentException(String.format( "addServicePrincipal for user %s fails: solution user must have certificate", accountName)); } Principal subjectDN = cert.getSubjectX500Principal(); ValidateUtil.validateNotNull(subjectDN, "Solution userCertificate subjectDn"); ValidateUtil.validateNotEmpty(subjectDN.getName(), "Solution userCertificate subjectDn"); String filter = String.format(SVC_PRINC_QUERY_BY_SUBJECT_DN, LdapFilterString.encode(subjectDN.getName())); String solutionUsersContainerDn = getServicePrincipalsDN(domainName); message = connection.search(solutionUsersContainerDn, LdapScope.SCOPE_SUBTREE, filter, attrNames, false); ILdapEntry[] entries = message.getEntries(); if (entries != null && entries.length > 0) { throw new DuplicateCertificateException("Same subjectDN already exists for another solution user"); } String dn = String.format("CN=%s,%s", accountName, solutionUsersContainerDn); LdapMod objectClass = null; // Mandatory LdapMod attrName = null; // Mandatory LdapMod attrAccount = null; // Mandatory LdapMod attrSubjectDN = null; // Mandatory // (this should be mandatory, subjectDn is a MUST which is derived from cert) LdapMod attrCert = null; // Mandatory LdapMod attrDescription = null; // Optional objectClass = new LdapMod(LdapModOperation.ADD, ATTR_NAME_OBJECTCLASS, new LdapValue[] { LdapValue.fromString("user"), LdapValue.fromString("vmwServicePrincipal") }); attributeList.add(objectClass); attrName = new LdapMod(LdapModOperation.ADD, ATTR_NAME_CN, new LdapValue[] { LdapValue.fromString(accountName) }); attributeList.add(attrName); attrAccount = new LdapMod(LdapModOperation.ADD, ATTR_NAME_ACCOUNT, new LdapValue[] { LdapValue.fromString(accountName) }); attributeList.add(attrAccount); String desc = detail.getDescription(); if (null != desc && !desc.isEmpty()) { attrDescription = new LdapMod(LdapModOperation.ADD, ATTR_SVC_DESCRIPTION, new LdapValue[] { LdapValue.fromString(desc) }); attributeList.add(attrDescription); } // vmwSTSSubjectDn is a MUST attribute attrSubjectDN = new LdapMod(LdapModOperation.ADD, ATTR_NAME_SUBJECTDN, new LdapValue[] { LdapValue.fromString(subjectDN.getName()) }); attributeList.add(attrSubjectDN); byte[] certBytes = cert.getEncoded(); assert (certBytes != null); attrCert = new LdapMod(LdapModOperation.ADD, ATTR_NAME_CERT, new LdapValue[] { new LdapValue(certBytes) }); attributeList.add(attrCert); connection.addObject(dn, attributeList.toArray(new LdapMod[attributeList.size()])); if (this.addUserToGroup(newSolutionUserId, IdentityManager.WELLKNOWN_SOLUTIONUSERS_GROUP_NAME) == false) { logger.info(String.format("Failed to add user %s to well-known SolutionUsers group", accountName)); } return newSolutionUserId; } catch (AlreadyExistsLdapException e) { // The solution user already exists. throw new InvalidPrincipalException(String.format("solution user %s already exists", accountName), ServerUtils.getUpn(newSolutionUserId), e); } finally { if (null != message) { message.close(); } connection.close(); } }
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 ava 2s . c om*/ * 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; }