List of usage examples for org.bouncycastle.asn1 DEROctetString getOctets
public byte[] getOctets()
From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java
License:Open Source License
protected void generateCrmf() throws Exception { // Edit our favorite test user UserDataVOWS user1 = new UserDataVOWS(); user1.setUsername(CA1_WSTESTUSER1);/*w w w . j a v a 2s . c o m*/ user1.setPassword(PASSWORD); user1.setClearPwd(true); user1.setSubjectDN(getDN(CA1_WSTESTUSER1)); user1.setCaName(CA1); user1.setStatus(UserDataVOWS.STATUS_NEW); user1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED); user1.setEndEntityProfileName(WS_EEPROF_EI); user1.setCertificateProfileName(WS_CERTPROF_EI); ejbcaraws.editUser(user1); final AuthenticationToken admin = new TestAlwaysAllowLocalAuthenticationToken( new UsernamePrincipal("SYSTEMTEST")); KeyPair keys = KeyTools.genKeys("512", "RSA"); CAInfo info = caSession.getCAInfo(admin, CA1); CertReqMsg req = createCrmfRequest(info.getSubjectDN(), getDN(CA1_WSTESTUSER1), keys, "1.2.3.4"); CertReqMessages msgs = new CertReqMessages(req); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(msgs); byte[] ba = bao.toByteArray(); String reqstr = new String(Base64.encode(ba)); //CertificateResponse certenv = ejbcaraws.crmfRequest(CA1_WSTESTUSER1, PASSWORD, CRMF, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); CertificateResponse certenv = ejbcaraws.crmfRequest(CA1_WSTESTUSER1, PASSWORD, reqstr, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); assertNotNull(certenv); X509Certificate cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData()); assertNotNull(cert); log.info(cert.getSubjectDN().toString()); assertEquals(getDN(CA1_WSTESTUSER1), cert.getSubjectDN().toString()); byte[] ext = cert.getExtensionValue("1.2.3.4"); // Certificate profile did not allow extension override assertNull("no extension should exist", ext); // Allow extension override CertificateProfile profile = certificateProfileSession.getCertificateProfile(WS_CERTPROF_EI); profile.setAllowExtensionOverride(true); certificateProfileSession.changeCertificateProfile(admin, WS_CERTPROF_EI, profile); // Now our extension should be possible to get in there try { ejbcaraws.editUser(user1); keys = KeyTools.genKeys("512", "RSA"); info = caSession.getCAInfo(admin, CA1); req = createCrmfRequest(info.getSubjectDN(), getDN(CA1_WSTESTUSER1), keys, "1.2.3.4"); msgs = new CertReqMessages(req); bao = new ByteArrayOutputStream(); out = new DEROutputStream(bao); out.writeObject(msgs); ba = bao.toByteArray(); reqstr = new String(Base64.encode(ba)); certenv = ejbcaraws.crmfRequest(CA1_WSTESTUSER1, PASSWORD, reqstr, null, CertificateHelper.RESPONSETYPE_CERTIFICATE); assertNotNull(certenv); cert = (X509Certificate) CertificateHelper.getCertificate(certenv.getData()); assertNotNull(cert); assertEquals(getDN(CA1_WSTESTUSER1), cert.getSubjectDN().toString()); ext = cert.getExtensionValue("1.2.3.4"); assertNotNull("there should be an extension", ext); ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(ext)); try { DEROctetString oct = (DEROctetString) (asn1InputStream.readObject()); assertEquals("Extension did not have the correct value", "foo123", (new String(oct.getOctets()).trim())); } finally { asn1InputStream.close(); } } finally { // restore profile.setAllowExtensionOverride(false); certificateProfileSession.changeCertificateProfile(admin, WS_CERTPROF_EI, profile); } }
From source file:org.ejbca.util.CertTools.java
License:Open Source License
/** * Get the authority key identifier from a certificate extensions * * @param cert certificate containing the extension * @return byte[] containing the authority key identifier, or null if it does not exist * @throws IOException if extension can not be parsed *//*from w ww . j a v a2 s . c o m*/ public static byte[] getAuthorityKeyId(Certificate cert) throws IOException { if (cert == null) { return null; } if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; byte[] extvalue = x509cert.getExtensionValue("2.5.29.35"); if (extvalue == null) { return null; } DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue)) .readObject()); AuthorityKeyIdentifier keyId = new AuthorityKeyIdentifier( (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject()); return keyId.getKeyIdentifier(); } return null; }
From source file:org.ejbca.util.CertTools.java
License:Open Source License
/** * Get a certificate policy ID from a certificate policies extension * * @param cert certificate containing the extension * @param pos position of the policy id, if several exist, the first is as pos 0 * @return String with the certificate policy OID * @throws IOException if extension can not be parsed *///from w ww .j a v a 2 s.co m public static String getCertificatePolicyId(Certificate cert, int pos) throws IOException { String ret = null; if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; byte[] extvalue = x509cert.getExtensionValue(X509Extensions.CertificatePolicies.getId()); if (extvalue == null) { return null; } DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue)) .readObject()); ASN1Sequence seq = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())) .readObject(); // Check the size so we don't ArrayIndexOutOfBounds if (seq.size() < pos + 1) { return null; } PolicyInformation pol = new PolicyInformation((ASN1Sequence) seq.getObjectAt(pos)); ret = pol.getPolicyIdentifier().getId(); } return ret; }
From source file:org.glite.authz.pep.pip.provider.ExtractorX509GenericPIP.java
License:Apache License
/** * Gets the policy OIDs from a {@link X509Certificate} and returns a list of * policy OIds in String object format./*from ww w.j a v a 2 s. c o m*/ * * @param cert * The x509Certificate where the Policy OID(s) are extracted * from. * @return a List of String instance. The list is filled with Policy OIDs * strings. * * @throws IOException * Thrown when readObject method does not work. */ @SuppressWarnings("resource") // Added to supres errors that are not useful protected List<String> getPolicyOIDs(X509Certificate cert) throws IOException { List<String> oidList = new LazyList<String>(); String certPolicies = null; try { Class<?> extension = Class.forName("org.bouncycastle.asn1.x509.Extension"); // java.lang.reflect.Field field = extension.getField("certificatePolicies"); // Object fieldvalue = field.get(extension); // certPolicies = ((org.bouncycastle.asn1.ASN1ObjectIdentifier)fieldvalue).toString(); certPolicies = extension.getField("certificatePolicies").get(extension).toString(); } catch (Exception e) { // NoSuchFieldException or ClassNotFoundException certPolicies = org.bouncycastle.asn1.x509.X509Extension.certificatePolicies.toString(); } byte[] extvalue = cert.getExtensionValue(certPolicies); if (extvalue == null) { log.warn("No valid certificate policies found!"); return null; } // Convert extension blob into DER octet string DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(extvalue)) .readObject()); // ANS1 sequence generated from the DER octet string ASN1Sequence seq = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())) .readObject(); /* Loop over all policy OIDs */ for (int pos = 0; pos < seq.size(); pos++) { if (PolicyInformation.getInstance(seq.getObjectAt(pos)).getPolicyIdentifier().getId() != null) { oidList.add(PolicyInformation.getInstance(seq.getObjectAt(pos)).getPolicyIdentifier().getId()); } else { throw new IOException("Policy does not exist!"); } } return oidList; }
From source file:org.glite.security.util.CertUtil.java
License:Apache License
/** * Gets the certificate extension identified by the oid and returns the value bytes unwrapped by the ASN1OctetString. * @param cert The certificate to inspect. * @param oid The extension OID to fetch. * @return The value bytes of the extension, returns null in case the extension was not present or was empty. * @throws IOException thrown in case the certificate parsing fails. *///from w w w.ja v a2 s .c om static public byte[] getExtensionBytes(X509Certificate cert, String oid) throws IOException { byte[] bytes = cert.getExtensionValue(oid); if (bytes == null) { return null; } DEROctetString valueOctets = (DEROctetString) ASN1Object.fromByteArray(bytes); return valueOctets.getOctets(); }
From source file:org.glite.security.util.FileCRLChecker.java
License:Apache License
/** * Checks the issuerDistributionPoint extension, whether it contains unsupported information. * /*from ww w.j av a 2s.c o m*/ * @throws CertificateException thrown in case there is problems with the certificate handling. * @throws IOException thrown in case the extension parsing fails. */ private void checkIssuinDistributionPoint() throws CertificateException, IOException { byte extensionBytes[] = m_crl.getExtensionValue(X509Extensions.IssuingDistributionPoint.toString()); ASN1Object object = ASN1Object.fromByteArray(extensionBytes); if (!(object instanceof DEROctetString)) { throw new CertificateException( "Invalid data in IssuingDistributionPoint extension, not DEROctetString"); } DEROctetString string = (DEROctetString) object; object = ASN1Object.fromByteArray(string.getOctets()); if (!(object instanceof ASN1Sequence)) { throw new CertificateException("Invalid data in IssuingDistributionPoint extension, not ASN1Sequence"); } IssuingDistributionPoint issuingDistributionPoint = new IssuingDistributionPoint((ASN1Sequence) object); if (issuingDistributionPoint.onlyContainsAttributeCerts()) { throw new CertificateException("CRL only contains attribute certs, not useful for authentication."); } if (issuingDistributionPoint.getOnlySomeReasons() != null) { throw new CertificateException( "CRL only contains some reasons of revocations, can't trust the certificates without other complementing CRL(s), which is not supported."); } }
From source file:org.glite.slcs.caclient.impl.CMPRequest.java
License:eu-egee.org license
private static byte[] makeProtection(String secret, int iterCount, String owfAlgId, String macAlgId, DEROctetString salt, PKIMessage message) { byte[] saltBytes = salt.getOctets(); byte[] sharedSecret = secret.getBytes(); byte[] firstKey = new byte[sharedSecret.length + saltBytes.length]; for (int i = 0; i < sharedSecret.length; i++) { firstKey[i] = sharedSecret[i];//w ww . j av a 2 s . com } for (int i = 0; i < saltBytes.length; i++) { firstKey[sharedSecret.length + i] = saltBytes[i]; } // Construct the base key according to rfc4210, section 5.1.3.1 MessageDigest dig = null; Mac mac = null; try { dig = MessageDigest.getInstance(owfAlgId, "BC"); for (int i = 0; i < iterCount; i++) { firstKey = dig.digest(firstKey); dig.reset(); } mac = Mac.getInstance(macAlgId, "BC"); SecretKey key = new SecretKeySpec(firstKey, macAlgId); mac.init(key); } catch (Exception e) { log.error("Error while calculating PKIMessage protection", e); } mac.reset(); byte[] protectedBytes = message.getProtectedBytes(); mac.update(protectedBytes, 0, protectedBytes.length); return mac.doFinal(); }
From source file:org.icepdf.core.pobjects.acroform.signature.certificates.CRLVerifier.java
License:Apache License
/** * Extracts all CRL distribution point URLs from the "CRL Distribution Point" * extension in a X.509 certificate. If CRL distribution point extension is * unavailable, returns an empty list./* w w w . j a va 2s . c om*/ */ public static List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateParsingException, IOException { byte[] crldpExt = cert.getExtensionValue(Extension.cRLDistributionPoints.getId()); if (crldpExt == null) { return new ArrayList<String>(); } ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(crldpExt)); ASN1Primitive derObjCrlDP = oAsnInStream.readObject(); DEROctetString dosCrlDP = (DEROctetString) derObjCrlDP; byte[] crldpExtOctets = dosCrlDP.getOctets(); ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets)); ASN1Primitive derObj2 = oAsnInStream2.readObject(); CRLDistPoint distPoint = CRLDistPoint.getInstance(derObj2); List<String> crlUrls = new ArrayList<String>(); for (DistributionPoint dp : distPoint.getDistributionPoints()) { DistributionPointName dpn = dp.getDistributionPoint(); // Look for URIs in fullName if (dpn != null) { if (dpn.getType() == DistributionPointName.FULL_NAME) { GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames(); // Look for an URI for (GeneralName genName : genNames) { if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) { String url = DERIA5String.getInstance(genName.getName()).getString(); crlUrls.add(url); } } } } } return crlUrls; }
From source file:org.identityconnectors.racf.BouncyCastlePEUtilities.java
License:Open Source License
public String getPassword(byte[] envelope) { ASN1InputStream aIn = null;//from w w w.java 2 s .c o m try { aIn = new ASN1InputStream(envelope); Object o = null; DEROctetString oString = null; while ((o = aIn.readObject()) != null) { if (o instanceof DERSequence) { // identifier (1.2.840.113549.1.7.1) DERSequence seq = (DERSequence) o; if (seq.size() >= 2 && seq.getObjectAt(0) instanceof DERObjectIdentifier && "1.2.840.113549.1.7.1".equals(((DERObjectIdentifier) seq.getObjectAt(0)).getId())) { if (seq.getObjectAt(1) instanceof DERTaggedObject && ((DERTaggedObject) seq.getObjectAt(1)).getObject() instanceof DEROctetString) { oString = (DEROctetString) ((DERTaggedObject) seq.getObjectAt(1)).getObject(); break; } } } } aIn.close(); aIn = null; String pw = null; if (oString != null) { aIn = new ASN1InputStream(oString.getOctets()); DERSequence seq = (DERSequence) aIn.readObject(); if (seq.getObjectAt(2) instanceof DERUTF8String) { pw = ((DERUTF8String) seq.getObjectAt(2)).getString(); } aIn.close(); aIn = null; } return pw; } catch (IOException e) { try { if (aIn != null) aIn.close(); } catch (IOException e2) { } throw ConnectorException.wrap(e); } }
From source file:org.jmrtd.lds.SignedDataUtil.java
License:Open Source License
public static ASN1Primitive getContent(SignedData signedData) { ContentInfo encapContentInfo = signedData.getEncapContentInfo(); String contentType = encapContentInfo.getContentType().getId(); DEROctetString eContent = (DEROctetString) encapContentInfo.getContent(); ASN1InputStream inputStream = null; try {//from w w w .j a v a 2s .c om inputStream = new ASN1InputStream(new ByteArrayInputStream(eContent.getOctets())); ASN1Primitive firstObject = inputStream.readObject(); return firstObject; } catch (IOException ioe) { LOGGER.log(Level.WARNING, "Unexpected exception", ioe); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ioe) { LOGGER.log(Level.WARNING, "Exception closing input stream"); /* At least we tried... */ } } } return null; }