List of usage examples for java.security.cert X509Certificate getExtensionValue
public byte[] getExtensionValue(String oid);
From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java
private byte[] getAKId(final X509Certificate cert) throws IOException { final byte[] extValue = cert.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); if (extValue != null) { final DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extValue)) .readObject());// www . j av a 2 s.c om final AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject()); return keyId.getKeyIdentifier(); } else { return null; } }
From source file:org.viafirma.nucleo.X509.X509Handler.java
/** * Parsea un certificado X509 para extraer todos sus oids * /*from w w w.ja v a 2s .com*/ * @param certificadoX509 * @return */ public Map<String, String> readPropertiesOid(X509Certificate certificadoX509) { Map<String, String> propiedadesOid = new HashMap<String, String>(); // obtengo los Oids Set<String> oids = certificadoX509.getNonCriticalExtensionOIDs(); if (oids != null) { // iteramos sobre los Oids // TODO ( este es el mecanismo para FNMT) for (String oid : oids) { try { ASN1InputStream aIn = new ASN1InputStream( new ByteArrayInputStream(certificadoX509.getExtensionValue(oid))); ASN1OctetString extValue = (ASN1OctetString) aIn.readObject(); aIn = new ASN1InputStream(new ByteArrayInputStream(extValue.getOctets())); @SuppressWarnings("unused") DERObject extensionType = aIn.readObject(); // System.out.println("oid= "+ oid + // ", valor= "+ASN1Dump.dumpAsString(extValue) // +"\n-\ntipo "+ASN1Dump.dumpAsString(extensionType)); readPropiedadesOid(oid, extValue, propiedadesOid); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // retornamos el conjunto de oids recuperados. return propiedadesOid; }
From source file:org.hyperledger.fabric.sdk.MemberServicesImpl.java
/** * Process a batch of tcerts after having retrieved them from the TCA. *//*from ww w . j a va 2s . c om*/ private List<TCert> processTCertBatch(GetTCertBatchRequest req, TCertCreateSetResp resp) throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, CryptoException, IOException { String enrollKey = req.getEnrollment().getKey(); byte[] tCertOwnerKDFKey = resp.getCerts().getKey().toByteArray(); List<Ca.TCert> tCerts = resp.getCerts().getCertsList(); byte[] byte1 = new byte[] { 1 }; byte[] byte2 = new byte[] { 2 }; byte[] tCertOwnerEncryptKey = Arrays.copyOfRange(cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte1), 0, 32); byte[] expansionKey = cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte2); List<TCert> tCertBatch = new ArrayList<>(tCerts.size()); // Loop through certs and extract private keys for (Ca.TCert tCert : tCerts) { X509Certificate x509Certificate; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); x509Certificate = (X509Certificate) cf.generateCertificate(tCert.getCert().newInput()); } catch (Exception ex) { logger.debug("Warning: problem parsing certificate bytes; retrying ... ", ex); continue; } // extract the encrypted bytes from extension attribute byte[] tCertIndexCT = fromDer(x509Certificate.getExtensionValue(TCERT_ENC_TCERT_INDEX)); byte[] tCertIndex = cryptoPrimitives.aesCBCPKCS7Decrypt(tCertOwnerEncryptKey, tCertIndexCT); byte[] expansionValue = cryptoPrimitives.calculateMac(expansionKey, tCertIndex); // compute the private key BigInteger k = new BigInteger(1, expansionValue); BigInteger n = ((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))) .getParameters().getN().subtract(BigInteger.ONE); k = k.mod(n).add(BigInteger.ONE); BigInteger D = ((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getD() .add(k); D = D.mod(((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getParameters() .getN()); // Put private and public key in returned tcert TCert tcert = new TCert(tCert.getCert().toByteArray(), cryptoPrimitives.ecdsaKeyFromBigInt(D)); tCertBatch.add(tcert); } if (tCertBatch.size() == 0) { throw new RuntimeException("Failed fetching TCertBatch. No valid TCert received."); } return tCertBatch; }
From source file:org.apache.directory.studio.connection.ui.widgets.CertificateInfoComposite.java
private void populateExtensions(final TreeItem extensionsItem, final X509Certificate certificate, boolean critical) { Set<String> oids = critical ? certificate.getCriticalExtensionOIDs() : certificate.getNonCriticalExtensionOIDs(); if (oids != null) { for (String oid : oids) { // try to parse the extension value byte[] to an ASN1 object byte[] extensionValueBin = certificate.getExtensionValue(oid); String extensionValue = null; try { ASN1Object extension = X509ExtensionUtil.fromExtensionValue(extensionValueBin); extensionValue = extension.toString(); } catch (IOException e) { extensionValue = new String(Hex.encodeHex(extensionValueBin)); }/* www . j a va 2 s . com*/ String value = Messages.getString("CertificateInfoComposite.ExtensionOIDColon") + oid + '\n'; //$NON-NLS-1$ value += Messages.getString("CertificateInfoComposite.CriticalColon") + Boolean.toString(critical) //$NON-NLS-1$ + '\n'; value += Messages.getString("CertificateInfoComposite.ExtensionValueColon") + extensionValue + '\n'; //$NON-NLS-1$ // TODO: OID descriptions // TODO: formatting of extension value TreeItem item = createTreeItem(extensionsItem, oid, value); createTreeItem(item, Messages.getString("CertificateInfoComposite.ExtensionOID"), oid); //$NON-NLS-1$ createTreeItem(item, Messages.getString("CertificateInfoComposite.Critical"), //$NON-NLS-1$ Boolean.toString(critical)); createTreeItem(item, Messages.getString("CertificateInfoComposite.ExtensionValue"), extensionValue); //$NON-NLS-1$ } } }
From source file:org.viafirma.nucleo.validacion.CRLUtil.java
/** * Recupero los puntos de distribucin/*w w w . ja va2 s . co m*/ * * @param certificadoX509 * @return */ private List<String> getCrlPuntosDeDistribucion(X509Certificate certificadoX509) throws CertificateParsingException { try { log.debug("Recuperando puntos de distribucin CRL del certificado: " + certificadoX509.getSubjectDN()); // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds // segun el RFC 3280 seccin 4.2.1.14) byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS); if (val1 == null) { if (certificadoX509.getSubjectDN().getName().equals(certificadoX509.getIssuerDN().getName())) { log.debug("El certificado es un certificado raiz: " + certificadoX509.getSubjectDN().getName()); } else { log.warn(" El certificado NO tiene punto de distribucin de CRL : " + certificadoX509.getSubjectDN().getName()); } return Collections.emptyList(); } else { ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1)); DERObject derObj = oAsnInStream.readObject(); DEROctetString dos = (DEROctetString) derObj; byte[] val2 = dos.getOctets(); ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2)); DERObject derObj2 = oAsnInStream2.readObject(); // Map<String,String> propiedades= new HashMap<String,String>(); List<String> urls = getDERValue(derObj2); return urls; /* * CertificadoHelper.getCurrentInstance().readPropiedadesOid(OID_CRLS,derObj2,propiedades); * if(log.isDebugEnabled())log.debug("Informacin sobre CRls del * certificado que ha sido recuperada: "+propiedades); // por * simplificar, aunque el certificado informe de varias crls que * utilizar. Solo trabajamos con la primera List listaCrls=new * ArrayList(1); listaCrls.add(propiedades.get(OID_CRLS)); * return listaCrls;//listaCrls.addAll(getDERValue(derObj2)) */} } catch (Exception e) { e.printStackTrace(); throw new CertificateParsingException(e.toString()); } }
From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java
private Object getExtensionValue(X509Certificate X509Certificate, String oid, Object what) throws IOException { String decoded = null;/*from w w w.j av a 2 s. c o m*/ byte[] extensionValue = X509Certificate.getExtensionValue(oid); if (extensionValue != null) { ASN1Primitive derObject = toASN1Primitive(extensionValue); if (derObject instanceof DEROctetString) { DEROctetString derOctetString = (DEROctetString) derObject; derObject = toASN1Primitive(derOctetString.getOctets()); if (what == BasicConstraints.class) { return BasicConstraints.getInstance(ASN1Primitive.fromByteArray(derOctetString.getOctets())); } else if (what == KeyUsage.class) { return KeyUsage.getInstance(ASN1Primitive.fromByteArray(derOctetString.getOctets())); } else if (derObject instanceof ASN1String) { ASN1String s = (ASN1String) derObject; decoded = s.getString(); } } } return decoded; }
From source file:org.wso2.carbon.security.util.ServerCrypto.java
@Override /**/* w w w. j a v a 2 s . com*/ * @see org.apache.ws.security.components.crypto.Crypto#getSKIBytesFromCert(java.security.cert.X509Certificate) */ public byte[] getSKIBytesFromCert(X509Certificate cert) throws WSSecurityException { /* * Gets the DER-encoded OCTET string for the extension value (extnValue) * identified by the passed-in oid String. The oid string is represented * by a set of positive whole numbers separated by periods. */ byte[] derEncodedValue = cert.getExtensionValue(SKI_OID); if (cert.getVersion() < 3 || derEncodedValue == null) { PublicKey key = cert.getPublicKey(); if (!(key instanceof RSAPublicKey)) { throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Support for RSA key only" }); } byte[] encoded = key.getEncoded(); // remove 22-byte algorithm ID and header byte[] value = new byte[encoded.length - 22]; System.arraycopy(encoded, 22, value, 0, value.length); MessageDigest sha; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Wrong certificate version (<3) and no " + "SHA1 message digest availabe" }); } sha.reset(); sha.update(value); return sha.digest(); } /** * Strip away first four bytes from the DerValue (tag and length of * ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING) */ byte abyte0[] = new byte[derEncodedValue.length - 4]; System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length); return abyte0; }
From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java
protected void copyExtension(final ASN1ObjectIdentifier extensionType, X509Certificate issuerCertificate, List<Extension> extensions) { final byte[] encodedAttribute = issuerCertificate.getExtensionValue(extensionType.getId()); ASN1OctetString data = ASN1OctetString.getInstance(encodedAttribute); boolean isCritical = issuerCertificate.getCriticalExtensionOIDs().contains(extensionType.getId()); if (encodedAttribute != null) { extensions.add(new Extension(extensionType, isCritical, data)); }// www. j a v a 2s .c om }
From source file:org.apache.ws.security.components.crypto.CryptoBase.java
/** * Reads the SubjectKeyIdentifier information from the certificate. * <p/>//from w w w .j av a 2s.c o m * If the the certificate does not contain a SKI extension then * try to compute the SKI according to RFC3280 using the * SHA-1 hash value of the public key. The second method described * in RFC3280 is not support. Also only RSA public keys are supported. * If we cannot compute the SKI throw a WSSecurityException. * * @param cert The certificate to read SKI * @return The byte array containing the binary SKI data */ public byte[] getSKIBytesFromCert(X509Certificate cert) throws WSSecurityException { // // Gets the DER-encoded OCTET string for the extension value (extnValue) // identified by the passed-in oid String. The oid string is represented // by a set of positive whole numbers separated by periods. // byte[] derEncodedValue = cert.getExtensionValue(SKI_OID); if (cert.getVersion() < 3 || derEncodedValue == null) { PublicKey key = cert.getPublicKey(); if (!(key instanceof RSAPublicKey)) { throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Support for RSA key only" }); } byte[] encoded = key.getEncoded(); // remove 22-byte algorithm ID and header byte[] value = new byte[encoded.length - 22]; System.arraycopy(encoded, 22, value, 0, value.length); MessageDigest sha; try { sha = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN, "noSKIHandling", new Object[] { "Wrong certificate version (<3) and no SHA1 message digest availabe" }, ex); } sha.reset(); sha.update(value); return sha.digest(); } // // Strip away first four bytes from the DerValue (tag and length of // ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING) // byte abyte0[] = new byte[derEncodedValue.length - 4]; System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length); return abyte0; }
From source file:test.unit.org.owasp.webscarab.util.SunCertificateUtilsTest.java
@Test public void testSign() throws Exception { // setup/* www . j a va2s . co m*/ KeyPair caKeyPair = generateKeyPair(); KeyPair entityKeyPair = generateKeyPair(); X500Principal subject = new X500Principal("CN=Test"); PublicKey pubKey = entityKeyPair.getPublic(); X500Principal issuer = new X500Principal("CN=CA"); PublicKey caPubKey = caKeyPair.getPublic(); PrivateKey caKey = caKeyPair.getPrivate(); Date begin = new Date(); Date ends = new Date(begin.getTime() + (long) 1000 * 60 * 60 * 24 * 30); BigInteger serialNo = BigInteger.valueOf(1234); JcaX509ExtensionUtils jxeu = new JcaX509ExtensionUtils(); // operate X509Certificate resultCert = SunCertificateUtils.sign(subject, pubKey, issuer, caPubKey, caKey, begin, ends, serialNo, null); // verify assertNotNull(resultCert); LOG.debug("result certificate: " + resultCert); resultCert.verify(caPubKey); assertEquals(subject, resultCert.getSubjectX500Principal()); assertEquals(issuer, resultCert.getIssuerX500Principal()); assertEquals(serialNo, resultCert.getSerialNumber()); assertEquals(pubKey, resultCert.getPublicKey()); LOG.debug("expected begin: " + begin.getTime()); LOG.debug("actual begin: " + resultCert.getNotBefore().getTime()); /* * BouncyCastle drops the milliseconds. */ assertTrue(Math.abs(begin.getTime() - resultCert.getNotBefore().getTime()) < 1000); assertTrue(Math.abs(ends.getTime() - resultCert.getNotAfter().getTime()) < 1000); byte[] subjectKeyIdentifierExtValue = resultCert .getExtensionValue(X509Extension.subjectKeyIdentifier.getId()); assertNotNull(subjectKeyIdentifierExtValue); ASN1Primitive subjectKeyIdentifier = JcaX509ExtensionUtils .parseExtensionValue(subjectKeyIdentifierExtValue); ASN1Primitive expSKI = jxeu.createSubjectKeyIdentifier(pubKey).toASN1Primitive(); assertArrayEquals(expSKI.getEncoded(), subjectKeyIdentifier.getEncoded()); byte[] authorityKeyIdentifierExtValue = resultCert .getExtensionValue(X509Extension.authorityKeyIdentifier.getId()); ASN1Primitive authorityKeyIdentifier = JcaX509ExtensionUtils .parseExtensionValue(authorityKeyIdentifierExtValue); ASN1Primitive expAKI = jxeu.createAuthorityKeyIdentifier(caPubKey).toASN1Primitive(); assertArrayEquals(expAKI.getEncoded(), authorityKeyIdentifier.getEncoded()); assertEquals(-1, resultCert.getBasicConstraints()); byte[] netscapeCertTypeExtValue = resultCert .getExtensionValue(MiscObjectIdentifiers.netscapeCertType.getId()); assertNotNull(netscapeCertTypeExtValue); DERBitString netscapeCertTypeExt = (DERBitString) X509ExtensionUtil .fromExtensionValue(netscapeCertTypeExtValue); NetscapeCertType netscapeCertType = new NetscapeCertType(netscapeCertTypeExt); assertEquals(NetscapeCertType.sslClient, netscapeCertType.intValue() & NetscapeCertType.sslClient); assertEquals(NetscapeCertType.sslServer, netscapeCertType.intValue() & NetscapeCertType.sslServer); assertTrue(resultCert.getKeyUsage()[0]); assertTrue(resultCert.getKeyUsage()[2]); byte[] extendedKeyUsageExtValue = resultCert.getExtensionValue(X509Extension.extendedKeyUsage.getId()); assertNotNull(extendedKeyUsageExtValue); ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage .getInstance(X509ExtensionUtil.fromExtensionValue(extendedKeyUsageExtValue)); assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth)); assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth)); }