List of usage examples for java.security.cert X509Certificate getEncoded
public abstract byte[] getEncoded() throws CertificateEncodingException;
From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java
public static void checkSigningCertificate(X509Certificate signingCertificate, SignedSignaturePropertiesType signedSignatureProperties) throws XAdESValidationException, CertificateEncodingException { CertIDListType signingCertificateCertIDList = signedSignatureProperties.getSigningCertificate(); List<CertIDType> signingCertificateCertIDs = signingCertificateCertIDList.getCert(); CertIDType signingCertificateCertID = signingCertificateCertIDs.get(0); DigestAlgAndValueType signingCertificateDigestAlgAndValue = signingCertificateCertID.getCertDigest(); String certXmlDigestAlgo = signingCertificateDigestAlgAndValue.getDigestMethod().getAlgorithm(); String certDigestAlgo = XAdESUtils.getDigestAlgo(certXmlDigestAlgo); byte[] certDigestValue = signingCertificateDigestAlgAndValue.getDigestValue(); MessageDigest messageDigest;/*ww w .j a v a2s . co m*/ try { messageDigest = MessageDigest.getInstance(certDigestAlgo); } catch (NoSuchAlgorithmException e) { throw new XAdESValidationException("message digest algo error: " + e.getMessage(), e); } byte[] actualCertDigestValue = messageDigest.digest(signingCertificate.getEncoded()); if (!Arrays.equals(actualCertDigestValue, certDigestValue)) { throw new XAdESValidationException( "XAdES signing certificate not corresponding with actual signing certificate"); } X509IssuerSerialType issuerSerial = signingCertificateCertID.getIssuerSerial(); BigInteger serialNumber = issuerSerial.getX509SerialNumber(); if (false == signingCertificate.getSerialNumber().equals(serialNumber)) { throw new XAdESValidationException("xades:SigningCertificate serial number mismatch"); } X509Name issuerName; try { /*issuerName = new X509Name( (ASN1Sequence) new ASN1InputStream(signingCertificate .getIssuerX500Principal().getEncoded()) .readObject());*/ X509Principal sprin = new X509Principal(signingCertificate.getIssuerX500Principal().getEncoded()); //issuerName = new X509Name( signingCertificate.getIssuerX500Principal().getName(X500Principal.RFC1779) ); issuerName = new X509Name(sprin.getName()); } catch (IOException e) { throw new XAdESValidationException("error parsing xades:SigningCertificate ds:X509IssuerName: " + e); } X509Name xadesIssuerName = new X509Name(issuerSerial.getX509IssuerName()); if (false == issuerName.equals(xadesIssuerName)) { throw new XAdESValidationException("xades:SigningCertificate issuer name mismatch"); } LOG.debug("XAdES SigningCertificate OK"); }
From source file:ee.ria.xroad.signer.console.SignerCLI.java
/** * Create dummy public key certificate./*from w ww . java 2 s . c o m*/ * @param keyId key id * @param cn common name * @throws Exception if an error occurs */ @Command(description = "Create dummy public key certificate") public void dummyCert(@Param(name = "keyId", description = "Key ID") String keyId, @Param(name = "cn", description = "Common name") String cn) throws Exception { Calendar cal = GregorianCalendar.getInstance(); cal.add(Calendar.YEAR, -1); Date notBefore = cal.getTime(); cal.add(Calendar.YEAR, 2); Date notAfter = cal.getTime(); ClientId memberId = ClientId.create("FOO", "BAR", "BAZ"); GenerateSelfSignedCert request = new GenerateSelfSignedCert(keyId, cn, notBefore, notAfter, KeyUsageInfo.SIGNING, memberId); GenerateSelfSignedCertResponse response = SignerClient.execute(request); X509Certificate cert = readCertificate(response.getCertificateBytes()); System.out.println("Certificate base64:"); System.out.println(encodeBase64(cert.getEncoded())); bytesToFile(keyId + ".crt", cert.getEncoded()); base64ToFile(keyId + ".crt.b64", cert.getEncoded()); }
From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java
/** * Test importing a new certificate chain to an existing keystore. * @throws Exception /*from ww w . j a v a 2 s . c o m*/ */ public void testImportCertificateChain() throws Exception { LOG.info("testImportCertificateChain"); final boolean autoActivate = false; final int workerId = WORKER_CMS; try { setCMSSignerPropertiesCombined(workerId, autoActivate); // Generate key and issue certificate final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC"); kpg.initialize(1024); final KeyPair keyPair = kpg.generateKeyPair(); // Create a key-pair and certificate in the keystore FileOutputStream out = null; try { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null, null); final X509Certificate[] chain = new X509Certificate[1]; chain[0] = getSelfCertificate("CN=Test", (long) 30 * 24 * 60 * 60 * 365, keyPair); ks.setKeyEntry("newkey11", keyPair.getPrivate(), pin.toCharArray(), chain); out = new FileOutputStream(keystoreFile); ks.store(out, pin.toCharArray()); } finally { IOUtils.closeQuietly(out); } workerSession.setWorkerProperty(workerId, "DEFAULTKEY", "newkey11"); workerSession.reloadConfiguration(workerId); // Activate first so we can generate a key workerSession.activateSigner(workerId, pin); List<String> errors = workerSession.getStatus(workerId).getFatalErrors(); assertTrue("Fatal errors: " + errors, workerSession.getStatus(workerId).getFatalErrors().isEmpty()); // generate a new certificate final X509Certificate newCert = getSelfCertificate("CN=TestNew", (long) 30 * 24 * 60 * 60 * 365, keyPair); workerSession.importCertificateChain(workerId, Arrays.asList(newCert.getEncoded()), "newkey11", null); final Certificate readCert = workerSession.getSignerCertificate(workerId); assertTrue("Matching certificates", Arrays.equals(newCert.getEncoded(), readCert.getEncoded())); } finally { FileUtils.deleteQuietly(keystoreFile); removeWorker(workerId); } }
From source file:org.apache.ws.security.message.token.SecurityTokenReference.java
/** * Sets the KeyIdentifier Element as a X509 certificate. Takes a X509 certificate, converts its * data into base 64 and inserts it into a <code>wsse:KeyIdentifier</code> element, which is * placed in the <code>wsse:SecurityTokenReference</code> element. * /*w w w. ja v a 2 s .c om*/ * @param cert * is the X509 certificate to be inserted as key identifier */ public void setKeyIdentifier(X509Certificate cert) throws WSSecurityException { Document doc = this.element.getOwnerDocument(); byte data[] = null; try { data = cert.getEncoded(); } catch (CertificateEncodingException e) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError", null, e); } Text text = doc.createTextNode(Base64.encode(data)); createKeyIdentifier(doc, X509Security.X509_V3_TYPE, text, true); }
From source file:test.unit.be.fedict.eid.idp.protocol.ws_federation.WSFederationMetadataHttpServletTest.java
private X509Certificate generateSelfSignedCertificate(KeyPair keyPair, String subjectDn, DateTime notBefore, DateTime notAfter) throws Exception { PublicKey subjectPublicKey = keyPair.getPublic(); PrivateKey issuerPrivateKey = keyPair.getPrivate(); String signatureAlgorithm = "SHA1WithRSAEncryption"; X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.reset();/*from w w w. j ava2s .co m*/ 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:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ArtifactProtocolServiceTest.java
private X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, DateTime notBefore, DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey) throws Exception { X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); certificateGenerator.reset();// w w w.ja v a 2s.c om certificateGenerator.setPublicKey(subjectPublicKey); certificateGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption"); 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; if (null != issuerCertificate) { issuerPublicKey = issuerCertificate.getPublicKey(); } else { issuerPublicKey = subjectPublicKey; } certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey)); 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.slc.sli.api.resources.security.SamlFederationResource.java
private String fetchCertificateText(KeyStore.PrivateKeyEntry keystoreEntry) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException { X509Certificate certificate = (X509Certificate) keystoreEntry.getCertificate(); Base64 encoder = new Base64(64); String certificateText = new String(encoder.encode(certificate.getEncoded())); return certificateText; }
From source file:org.strongswan.android.logic.CharonVpnService.java
/** * Function called via JNI to get a list containing the DER encoded certificates * of the user selected certificate chain (beginning with the user certificate). * * Since this method is called from a thread of charon's thread pool we are safe * to call methods on KeyChain directly. * * @return list containing the certificates (first element is the user certificate) * @throws InterruptedException/* w w w .jav a 2 s .c o m*/ * @throws KeyChainException * @throws CertificateEncodingException */ private byte[][] getUserCertificate() throws KeyChainException, InterruptedException, CertificateEncodingException { ArrayList<byte[]> encodings = new ArrayList<byte[]>(); X509Certificate[] chain = KeyChain.getCertificateChain(getApplicationContext(), mCurrentUserCertificateAlias); if (chain == null || chain.length == 0) { return null; } for (X509Certificate cert : chain) { encodings.add(cert.getEncoded()); } return encodings.toArray(new byte[encodings.size()][]); }
From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileC.java
/** * Gives back the JAXB CertID data structure. * //from w ww. j a v a2s . c om * @param certificate * @param xadesObjectFactory * @param xmldsigObjectFactory * @param digestAlgorithm * @return */ private CertIDType getCertID(X509Certificate certificate, DigestAlgorithm digestAlgorithm) { CertIDType certId = xadesObjectFactory.createCertIDType(); X509IssuerSerialType issuerSerial = getXmldsigObjectFactory().createX509IssuerSerialType(); certId.setIssuerSerial(issuerSerial); String issuerName = certificate.getIssuerX500Principal().toString(); issuerSerial.setX509IssuerName(issuerName); issuerSerial.setX509SerialNumber(certificate.getSerialNumber()); byte[] encodedCertificate; try { encodedCertificate = certificate.getEncoded(); } catch (CertificateEncodingException e) { throw new RuntimeException("certificate encoding error: " + e.getMessage(), e); } DigestAlgAndValueType certDigest = getDigestAlgAndValue(encodedCertificate, digestAlgorithm); certId.setCertDigest(certDigest); return certId; }
From source file:org.tolven.config.model.CredentialManager.java
private void writeDER(X509Certificate certificate, File file) throws IOException, GeneralSecurityException { FileUtils.writeByteArrayToFile(file, certificate.getEncoded()); }