List of usage examples for java.security.cert X509Certificate getEncoded
public abstract byte[] getEncoded() throws CertificateEncodingException;
From source file:com.adito.boot.KeyStoreManager.java
boolean doIsCertificateTrused(String alias, KeyStore keyStore) throws Exception { Certificate[] certs = keyStore.getCertificateChain(alias); // try { // ((CustomSSLSocketFactory)CustomSSLSocketFactory.getDefault()).checkServerTrusted((X509Certificate[])certs, ""); // return true; // } catch(CertificateException ex) { if (certs == null) { if (log.isInfoEnabled()) log.info("No certs for " + alias + ", untrusted."); } else if (certs.length > 1) { X509Certificate x509cert = (X509Certificate) certs[certs.length - 1]; TrustedCACertStore store = new TrustedCACertStore(); ByteArrayInputStream bin = new ByteArrayInputStream(x509cert.getEncoded()); DERInputStream der = null;/*w ww . ja v a 2s .c om*/ try { der = new DERInputStream(bin); ASN1Sequence certificate = (ASN1Sequence) der.readObject(); com.maverick.crypto.asn1.x509.X509Certificate x509 = new com.maverick.crypto.asn1.x509.X509Certificate( X509CertificateStructure.getInstance(certificate)); return store.isTrustedCertificate(x509, false, false); } finally { Util.closeStream(der); } } // } return false; }
From source file:org.texai.x509.X509Utils.java
/** Writes a DER encoded certificate to the given file path. * @param x509Certificate the X.509 certificate * @param filePath the given file path//from w w w . jav a2s .c o m * @throws CertificateEncodingException if the certificate cannot be encoded * @throws IOException when an input/output error occurs */ public static void writeX509Certificate(final X509Certificate x509Certificate, final String filePath) throws CertificateEncodingException, IOException { //Preconditions assert x509Certificate != null : "x509Certificate must not be null"; assert filePath != null : "filePath must not be null"; assert !filePath.isEmpty() : "filePath must not be empty"; try (OutputStream certificateOutputStream = new FileOutputStream(filePath)) { certificateOutputStream.write(x509Certificate.getEncoded()); certificateOutputStream.flush(); } }
From source file:org.codice.ddf.security.idp.client.AssertionConsumerService.java
@GET @Path("/metadata") @Produces("application/xml") public Response retrieveMetadata() throws WSSecurityException, CertificateEncodingException { X509Certificate issuerCert = findCertificate(systemCrypto.getSignatureAlias(), systemCrypto.getSignatureCrypto()); X509Certificate encryptionCert = findCertificate(systemCrypto.getEncryptionAlias(), systemCrypto.getEncryptionCrypto()); String hostname = SystemBaseUrl.getHost(); String port = SystemBaseUrl.getPort(); String rootContext = SystemBaseUrl.getRootContext(); String entityId = String.format("https://%s:%s%s/saml", hostname, port, rootContext); String logoutLocation = String.format("https://%s:%s%s/saml/logout", hostname, port, rootContext); String assertionConsumerServiceLocation = String.format("https://%s:%s%s/saml/sso", hostname, port, rootContext);//from www . j a va 2 s . co m EntityDescriptor entityDescriptor = SamlProtocol.createSpMetadata(entityId, Base64.getEncoder().encodeToString(issuerCert.getEncoded()), Base64.getEncoder().encodeToString(encryptionCert.getEncoded()), logoutLocation, assertionConsumerServiceLocation, assertionConsumerServiceLocation); Document doc = DOMUtils.createDocument(); doc.appendChild(doc.createElement("root")); return Response.ok(DOM2Writer.nodeToString(OpenSAMLUtil.toDom(entityDescriptor, doc, false))).build(); }
From source file:com.google.u2f.server.impl.U2FServerReferenceImpl.java
@Override public SecurityKeyData processRegistrationResponse(RegistrationResponse registrationResponse, long currentTimeInMillis) throws U2FException { Log.info(">> processRegistrationResponse"); String sessionId = registrationResponse.getSessionId(); String clientDataBase64 = registrationResponse.getClientData(); String rawRegistrationDataBase64 = registrationResponse.getRegistrationData(); Log.info(">> rawRegistrationDataBase64: " + rawRegistrationDataBase64); EnrollSessionData sessionData = dataStore.getEnrollSessionData(sessionId); if (sessionData == null) { throw new U2FException("Unknown session_id"); }//w w w. j av a 2s . c o m String appId = sessionData.getAppId(); String clientData = new String(Base64.decodeBase64(clientDataBase64)); byte[] rawRegistrationData = Base64.decodeBase64(rawRegistrationDataBase64); Log.info("-- Input --"); Log.info(" sessionId: " + sessionId); Log.info(" challenge: " + Hex.encodeHexString(sessionData.getChallenge())); Log.info(" accountName: " + sessionData.getAccountName()); Log.info(" clientData: " + clientData); Log.info(" rawRegistrationData: " + Hex.encodeHexString(rawRegistrationData)); RegisterResponse registerResponse = RawMessageCodec.decodeRegisterResponse(rawRegistrationData); byte[] userPublicKey = registerResponse.getUserPublicKey(); byte[] keyHandle = registerResponse.getKeyHandle(); X509Certificate attestationCertificate = registerResponse.getAttestationCertificate(); byte[] signature = registerResponse.getSignature(); List<Transports> transports = null; try { transports = U2fAttestation.Parse(attestationCertificate).getTransports(); } catch (CertificateParsingException e) { Log.warning("Could not parse transports extension " + e.getMessage()); } Log.info("-- Parsed rawRegistrationResponse --"); Log.info(" userPublicKey: " + Hex.encodeHexString(userPublicKey)); Log.info(" keyHandle: " + Hex.encodeHexString(keyHandle)); Log.info(" attestationCertificate: " + attestationCertificate.toString()); Log.info(" transports: " + transports); try { Log.info(" attestationCertificate bytes: " + Hex.encodeHexString(attestationCertificate.getEncoded())); } catch (CertificateEncodingException e) { throw new U2FException("Cannot encode certificate", e); } Log.info(" signature: " + Hex.encodeHexString(signature)); byte[] appIdSha256 = crypto.computeSha256(appId.getBytes()); byte[] clientDataSha256 = crypto.computeSha256(clientData.getBytes()); byte[] signedBytes = RawMessageCodec.encodeRegistrationSignedBytes(appIdSha256, clientDataSha256, keyHandle, userPublicKey); Set<X509Certificate> trustedCertificates = dataStore.getTrustedCertificates(); if (!trustedCertificates.contains(attestationCertificate)) { Log.warning("attestion cert is not trusted"); } verifyBrowserData(new JsonParser().parse(clientData), "navigator.id.finishEnrollment", sessionData); Log.info("Verifying signature of bytes " + Hex.encodeHexString(signedBytes)); if (!crypto.verifySignature(attestationCertificate, signedBytes, signature)) { throw new U2FException("Signature is invalid"); } // The first time we create the SecurityKeyData, we set the counter value to 0. // We don't actually know what the counter value of the real device is - but it will // be something bigger (or equal) to 0, so subsequent signatures will check out ok. SecurityKeyData securityKeyData = new SecurityKeyData(currentTimeInMillis, transports, keyHandle, userPublicKey, attestationCertificate, /* initial counter value */ 0); dataStore.addSecurityKeyData(sessionData.getAccountName(), securityKeyData); Log.info("<< processRegistrationResponse"); return securityKeyData; }
From source file:test.integ.be.agiv.security.IPSTSTest.java
private X509Certificate generateSelfSignedCertificate(KeyPair keyPair, String subjectDn, DateTime notBefore, DateTime notAfter) throws IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException { PublicKey subjectPublicKey = keyPair.getPublic(); PrivateKey issuerPrivateKey = keyPair.getPrivate(); String signatureAlgorithm = "SHA1WithRSAEncryption"; X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.reset();//ww w. j a v a 2 s. c om certificateGenerator.setPublicKey(subjectPublicKey); certificateGenerator.setSignatureAlgorithm(signatureAlgorithm); certificateGenerator.setNotBefore(notBefore.toDate()); certificateGenerator.setNotAfter(notAfter.toDate()); X509Principal issuerDN = new X509Principal(subjectDn); certificateGenerator.setIssuerDN(issuerDN); certificateGenerator.setSubjectDN(new X509Principal(subjectDn)); certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom())); certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey)); PublicKey issuerPublicKey; issuerPublicKey = subjectPublicKey; certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey)); certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true)); X509Certificate certificate; certificate = certificateGenerator.generate(issuerPrivateKey); /* * Next certificate factory trick is needed to make sure that the * certificate delivered to the caller is provided by the default * security provider instead of BouncyCastle. If we don't do this trick * we might run into trouble when trying to use the CertPath validator. */ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificate.getEncoded())); return certificate; }
From source file:org.wso2.carbon.identity.certificateauthority.dao.CertificateDAO.java
/** * adds a public certificate to the database * * @param serial serial number of the certificate * @param tenantID id of the tenant tenant who issued the certificate * @return// w w w . ja v a 2 s.com */ public void addCertificate(String serial, X509Certificate certificate, int tenantID, String username, String userStoreDomain) throws CaException { Connection connection = null; Date requestDate = new Date(); String sql = null; PreparedStatement prepStmt = null; try { Date expiryDate = certificate.getNotAfter(); log.debug("adding public certificate file to database"); connection = JDBCPersistenceManager.getInstance().getDBConnection(); sql = "INSERT INTO CA_CERTIFICATE_STORE (SERIAL_NO,PUBLIC_CERTIFICATE,STATUS,ISSUED_DATE,EXPIRY_DATE,TENANT_ID,USER_NAME,UM_DOMAIN_NAME) VALUES (?,?,?,?,?,?,?,?) "; prepStmt = connection.prepareStatement(sql); prepStmt.setString(1, serial); prepStmt.setBlob(2, new ByteArrayInputStream(certificate.getEncoded())); prepStmt.setString(3, CertificateStatus.ACTIVE.toString()); prepStmt.setTimestamp(4, new Timestamp(requestDate.getTime())); prepStmt.setTimestamp(5, new Timestamp(expiryDate.getTime())); prepStmt.setInt(6, tenantID); prepStmt.setString(7, username); prepStmt.setString(8, userStoreDomain); prepStmt.execute(); connection.commit(); } catch (IdentityException e) { String errorMsg = "Error when getting an Identity Persistence Store instance."; log.error(errorMsg, e); throw new CaException(errorMsg, e); } catch (SQLException e) { log.error("Error when executing the SQL : " + sql); log.error(e.getMessage(), e); } catch (CertificateEncodingException e) { log.error("Error encoding certificate"); } finally { IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt); } }
From source file:test.unit.test.be.fedict.eid.applet.model.XmlSignatureServiceBeanTest.java
private X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, DateTime notBefore, DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag, int pathLength, String ocspUri, KeyUsage keyUsage) throws IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException { String signatureAlgorithm = "SHA1withRSA"; X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.reset();/*from w ww .j a va 2s . co m*/ certificateGenerator.setPublicKey(subjectPublicKey); certificateGenerator.setSignatureAlgorithm(signatureAlgorithm); certificateGenerator.setNotBefore(notBefore.toDate()); certificateGenerator.setNotAfter(notAfter.toDate()); X509Principal issuerDN; if (null != issuerCertificate) { issuerDN = new X509Principal(issuerCertificate.getSubjectX500Principal().toString()); } else { issuerDN = new X509Principal(subjectDn); } certificateGenerator.setIssuerDN(issuerDN); certificateGenerator.setSubjectDN(new X509Principal(subjectDn)); certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom())); certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey)); PublicKey issuerPublicKey; issuerPublicKey = subjectPublicKey; certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey)); if (caFlag) { if (-1 == pathLength) { certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true)); } else { certificateGenerator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(pathLength)); } } if (null != ocspUri) { GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri); AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess( X509ObjectIdentifiers.ocspAccessMethod, ocspName); certificateGenerator.addExtension(X509Extensions.AuthorityInfoAccess.getId(), false, authorityInformationAccess); } if (null != keyUsage) { certificateGenerator.addExtension(X509Extensions.KeyUsage, true, keyUsage); } X509Certificate certificate; certificate = certificateGenerator.generate(issuerPrivateKey); /* * Next certificate factory trick is needed to make sure that the * certificate delivered to the caller is provided by the default * security provider instead of BouncyCastle. If we don't do this trick * we might run into trouble when trying to use the CertPath validator. */ CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); certificate = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(certificate.getEncoded())); return certificate; }
From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java
@Test public void testPassiveLoginPkiSignatureErrorPost() throws SecurityServiceException, WSSecurityException, CertificateEncodingException, IOException { String samlRequest = authNRequestPassivePkiPost; HttpServletRequest request = mock(HttpServletRequest.class); X509Certificate x509Certificate = mock(X509Certificate.class); SecurityManager securityManager = mock(SecurityManager.class); when(securityManager.getSubject(anyObject())).thenThrow(new SecurityServiceException("test")); idpEndpoint.setSecurityManager(securityManager); when(request.isSecure()).thenReturn(true); when(request.getRequestURL()).thenReturn(requestURL); when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*"); //dummy cert/*w w w.j a va 2 s . c o m*/ when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName)) .thenReturn(new X509Certificate[] { x509Certificate }); when(x509Certificate.getEncoded()).thenReturn(new byte[48]); Response response = idpEndpoint.showPostLogin(samlRequest, relayState, request); assertThat(response.getStatus(), is(500)); }
From source file:org.apache.rahas.impl.SAML2TokenIssuer.java
/** * This method is used to create the subject of an assertion * @param config//from w w w . j a va 2 s . com * @param doc * @param crypto * @param creationTime * @param expirationTime * @param data * @return Subject * @throws Exception */ private Subject createSubjectWithHolderOfKeySC(SAMLTokenIssuerConfig config, Document doc, Crypto crypto, DateTime creationTime, DateTime expirationTime, RahasData data) throws Exception { XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory(); SAMLObjectBuilder<Subject> subjectBuilder = (SAMLObjectBuilder<Subject>) builderFactory .getBuilder(Subject.DEFAULT_ELEMENT_NAME); Subject subject = subjectBuilder.buildObject(); Element keyInfoElem = null; // If it is a Symmetric Key if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) { isSymmetricKeyBasedHoK = true; Element encryptedKeyElem; X509Certificate serviceCert = null; try { if (data.getPrincipal() != null) { //get subject's name from Rahas data String subjectNameID = data.getPrincipal().getName(); //Create NameID and attach it to the subject NameID nameID = new NameIDBuilder().buildObject(); nameID.setValue(subjectNameID); nameID.setFormat(NameIdentifier.EMAIL); subject.setNameID(nameID); } // Get ApliesTo to figure out which service to issue the token // for serviceCert = config.getServiceCert(crypto, data.getAppliesToAddress()); // Create the encrypted key WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey(); // Use thumbprint id encrKeyBuilder.setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER); // SEt the encryption cert encrKeyBuilder.setUseThisCert(serviceCert); // set keysize int keysize = data.getKeysize(); keysize = (keysize != -1) ? keysize : config.keySize; encrKeyBuilder.setKeySize(keysize); encrKeyBuilder .setEphemeralKey(TokenIssuerUtil.getSharedSecret(data, config.keyComputation, keysize)); // Set key encryption algo encrKeyBuilder.setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15); // Build encrKeyBuilder.prepare(doc, crypto); // Extract the base64 encoded secret value byte[] tempKey = new byte[keysize / 8]; System.arraycopy(encrKeyBuilder.getEphemeralKey(), 0, tempKey, 0, keysize / 8); data.setEphmeralKey(tempKey); // Extract the Encryptedkey DOM element encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement(); } catch (WSSecurityException e) { throw new TrustException("errorInBuildingTheEncryptedKeyForPrincipal", new String[] { serviceCert.getSubjectDN().getName() }, e); } keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo"); ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX); ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.ENC_NS, WSConstants.ENC_PREFIX); keyInfoElem.appendChild(encryptedKeyElem); } // If it is a public Key else if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)) { try { String subjectNameId = data.getPrincipal().getName(); //Create NameID and attach it to the subject NameIDBuilder nb = new NameIDBuilder(); NameID nameID = nb.buildObject(); nameID.setValue(subjectNameId); nameID.setFormat(NameIdentifier.EMAIL); subject.setNameID(nameID); // Create the ds:KeyValue element with the ds:X509Data X509Certificate clientCert = data.getClientCert(); if (clientCert == null) { X509Certificate[] certs = crypto.getCertificates(data.getPrincipal().getName()); clientCert = certs[0]; } byte[] clientCertBytes = clientCert.getEncoded(); String base64Cert = Base64.encode(clientCertBytes); Text base64CertText = doc.createTextNode(base64Cert); //----------------------------------------- Element x509CertElem = doc.createElementNS(WSConstants.SIG_NS, "ds:X509Certificate"); x509CertElem.appendChild(base64CertText); Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS, "ds:X509Data"); x509DataElem.appendChild(x509CertElem); if (x509DataElem != null) { keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo"); ((OMElement) x509DataElem).declareNamespace(WSConstants.SIG_NS, WSConstants.SIG_PREFIX); keyInfoElem.appendChild(x509DataElem); } } catch (Exception e) { throw new TrustException("samlAssertionCreationError", e); } } // Unmarshall the keyInfo DOM element into an XMLObject String keyInfoElementString = keyInfoElem.toString(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = docBuilder.parse(new ByteArrayInputStream(keyInfoElementString.trim().getBytes())); Element element = document.getDocumentElement(); // Get appropriate unmarshaller UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element); // Unmarshall using the document root element, an keyInfo element in this case XMLObject keyInfoElement = null; try { keyInfoElement = unmarshaller.unmarshall(element); } catch (UnmarshallingException e) { throw new TrustException("Error unmarshalling KeyInfo Element", e); } //Build the Subject Confirmation SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) builderFactory .getBuilder(SubjectConfirmation.DEFAULT_ELEMENT_NAME); SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject(); //Set the subject Confirmation method subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:holder-of-key"); SAMLObjectBuilder<KeyInfoConfirmationDataType> keyInfoSubjectConfirmationDataBuilder = (SAMLObjectBuilder<KeyInfoConfirmationDataType>) builderFactory .getBuilder(KeyInfoConfirmationDataType.TYPE_NAME); //Build the subject confirmation data element KeyInfoConfirmationDataType scData = keyInfoSubjectConfirmationDataBuilder .buildObject(SubjectConfirmationData.DEFAULT_ELEMENT_NAME, KeyInfoConfirmationDataType.TYPE_NAME); //Set the keyInfo element scData.getKeyInfos().add(keyInfoElement); // Set the validity period scData.setNotBefore(creationTime); scData.setNotOnOrAfter(expirationTime); //Set the subject confirmation data subjectConfirmation.setSubjectConfirmationData(scData); //set the subject confirmation subject.getSubjectConfirmations().add(subjectConfirmation); log.debug("SAML2.0 subject is constructed successfully."); return subject; }
From source file:org.tolven.security.bean.DocProtectionBean.java
/** * Sign the clear text content of DocContentSecurity and return a DocumentSignatute * @param doc/*from ww w . j av a 2 s . c o m*/ * @param activeAccountUser * @return */ public DocumentSignature sign(DocBase doc, AccountUser activeAccountUser, PrivateKey privateKey, X509Certificate x509Certificate) { if (doc.getContent() == null) { return null; } if (privateKey == null) { throw new RuntimeException("A private key is required to sign a document"); } if (x509Certificate == null) { throw new RuntimeException("An X509 Certificate is required to sign a document"); } String signatureAlgorithm = propertiesBean.getProperty(DocumentSignature.DOC_SIGNATURE_ALGORITHM_PROP); try { Signature signature = Signature.getInstance(signatureAlgorithm); signature.initSign(privateKey); byte[] document = getDecryptedContent(doc, activeAccountUser, privateKey); signature.update(document); DocumentSignature documentSignature = new DocumentSignature(); documentSignature.setDocBase(doc); documentSignature.setSignature(signature.sign()); documentSignature.setSignatureAlgorithm(signatureAlgorithm); documentSignature.setCertificate(x509Certificate.getEncoded()); documentSignature.setUser(activeAccountUser.getUser()); documentSignature.setTimstamp(new Date()); em.persist(documentSignature); return documentSignature; } catch (Exception ex) { throw new RuntimeException("Could not sign documentId: " + doc.getId()); } }