Search in sources :

Example 6 with Attribute

use of com.android.org.bouncycastle.asn1.x509.Attribute in project android_frameworks_base by ResurrectionRemix.

the class ESTHandler method buildCSR.

private byte[] buildCSR(ByteBuffer octetBuffer, OMADMAdapter omadmAdapter, HTTPHandler httpHandler) throws IOException, GeneralSecurityException {
    //Security.addProvider(new BouncyCastleProvider());
    Log.d(TAG, "/csrattrs:");
    /*
        byte[] octets = new byte[octetBuffer.remaining()];
        octetBuffer.duplicate().get(octets);
        for (byte b : octets) {
            System.out.printf("%02x ", b & 0xff);
        }
        */
    Collection<Asn1Object> csrs = Asn1Decoder.decode(octetBuffer);
    for (Asn1Object asn1Object : csrs) {
        Log.d(TAG, asn1Object.toString());
    }
    if (csrs.size() != 1) {
        throw new IOException("Unexpected object count in CSR attributes response: " + csrs.size());
    }
    Asn1Object sequence = csrs.iterator().next();
    if (sequence.getClass() != Asn1Constructed.class) {
        throw new IOException("Unexpected CSR attribute container: " + sequence);
    }
    String keyAlgo = null;
    Asn1Oid keyAlgoOID = null;
    String sigAlgo = null;
    String curveName = null;
    Asn1Oid pubCrypto = null;
    int keySize = -1;
    Map<Asn1Oid, ASN1Encodable> idAttributes = new HashMap<>();
    for (Asn1Object child : sequence.getChildren()) {
        if (child.getTag() == Asn1Decoder.TAG_OID) {
            Asn1Oid oid = (Asn1Oid) child;
            OidMappings.SigEntry sigEntry = OidMappings.getSigEntry(oid);
            if (sigEntry != null) {
                sigAlgo = sigEntry.getSigAlgo();
                keyAlgoOID = sigEntry.getKeyAlgo();
                keyAlgo = OidMappings.getJCEName(keyAlgoOID);
            } else if (oid.equals(OidMappings.sPkcs9AtChallengePassword)) {
                byte[] tlsUnique = httpHandler.getTLSUnique();
                if (tlsUnique != null) {
                    idAttributes.put(oid, new DERPrintableString(Base64.encodeToString(tlsUnique, Base64.DEFAULT)));
                } else {
                    Log.w(TAG, "Cannot retrieve TLS unique channel binding");
                }
            }
        } else if (child.getTag() == Asn1Decoder.TAG_SEQ) {
            Asn1Oid oid = null;
            Set<Asn1Oid> oidValues = new HashSet<>();
            List<Asn1Object> values = new ArrayList<>();
            for (Asn1Object attributeSeq : child.getChildren()) {
                if (attributeSeq.getTag() == Asn1Decoder.TAG_OID) {
                    oid = (Asn1Oid) attributeSeq;
                } else if (attributeSeq.getTag() == Asn1Decoder.TAG_SET) {
                    for (Asn1Object value : attributeSeq.getChildren()) {
                        if (value.getTag() == Asn1Decoder.TAG_OID) {
                            oidValues.add((Asn1Oid) value);
                        } else {
                            values.add(value);
                        }
                    }
                }
            }
            if (oid == null) {
                throw new IOException("Invalid attribute, no OID");
            }
            if (oid.equals(OidMappings.sExtensionRequest)) {
                for (Asn1Oid subOid : oidValues) {
                    if (OidMappings.isIDAttribute(subOid)) {
                        if (subOid.equals(OidMappings.sMAC)) {
                            idAttributes.put(subOid, new DERIA5String(omadmAdapter.getMAC()));
                        } else if (subOid.equals(OidMappings.sIMEI)) {
                            idAttributes.put(subOid, new DERIA5String(omadmAdapter.getImei()));
                        } else if (subOid.equals(OidMappings.sMEID)) {
                            idAttributes.put(subOid, new DERBitString(omadmAdapter.getMeid()));
                        } else if (subOid.equals(OidMappings.sDevID)) {
                            idAttributes.put(subOid, new DERPrintableString(omadmAdapter.getDevID()));
                        }
                    }
                }
            } else if (OidMappings.getCryptoID(oid) != null) {
                pubCrypto = oid;
                if (!values.isEmpty()) {
                    for (Asn1Object value : values) {
                        if (value.getTag() == Asn1Decoder.TAG_INTEGER) {
                            keySize = (int) ((Asn1Integer) value).getValue();
                        }
                    }
                }
                if (oid.equals(OidMappings.sAlgo_EC)) {
                    if (oidValues.isEmpty()) {
                        throw new IOException("No ECC curve name provided");
                    }
                    for (Asn1Oid value : oidValues) {
                        curveName = OidMappings.getJCEName(value);
                        if (curveName != null) {
                            break;
                        }
                    }
                    if (curveName == null) {
                        throw new IOException("Found no ECC curve for " + oidValues);
                    }
                }
            }
        }
    }
    if (keyAlgoOID == null) {
        throw new IOException("No public key algorithm specified");
    }
    if (pubCrypto != null && !pubCrypto.equals(keyAlgoOID)) {
        throw new IOException("Mismatching key algorithms");
    }
    if (keyAlgoOID.equals(OidMappings.sAlgo_RSA)) {
        if (keySize < MinRSAKeySize) {
            if (keySize >= 0) {
                Log.i(TAG, "Upgrading suggested RSA key size from " + keySize + " to " + MinRSAKeySize);
            }
            keySize = MinRSAKeySize;
        }
    }
    Log.d(TAG, String.format("pub key '%s', signature '%s', ECC curve '%s', id-atts %s", keyAlgo, sigAlgo, curveName, idAttributes));
    /*
          Ruckus:
            SEQUENCE:
              OID=1.2.840.113549.1.1.11 (algo_id_sha256WithRSAEncryption)

          RFC-7030:
            SEQUENCE:
              OID=1.2.840.113549.1.9.7 (challengePassword)
              SEQUENCE:
                OID=1.2.840.10045.2.1 (algo_id_ecPublicKey)
                SET:
                  OID=1.3.132.0.34 (secp384r1)
              SEQUENCE:
                OID=1.2.840.113549.1.9.14 (extensionRequest)
                SET:
                  OID=1.3.6.1.1.1.1.22 (mac-address)
              OID=1.2.840.10045.4.3.3 (eccdaWithSHA384)

              1L, 3L, 6L, 1L, 1L, 1L, 1L, 22
         */
    // ECC Does not appear to be supported currently
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo);
    if (curveName != null) {
        AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(keyAlgo);
        algorithmParameters.init(new ECNamedCurveGenParameterSpec(curveName));
        kpg.initialize(algorithmParameters.getParameterSpec(ECNamedCurveGenParameterSpec.class));
    } else {
        kpg.initialize(keySize);
    }
    KeyPair kp = kpg.generateKeyPair();
    X500Principal subject = new X500Principal("CN=Android, O=Google, C=US");
    mClientKey = kp.getPrivate();
    // !!! Map the idAttributes into an ASN1Set of values to pass to
    // the PKCS10CertificationRequest - this code is using outdated BC classes and
    // has *not* been tested.
    ASN1Set attributes;
    if (!idAttributes.isEmpty()) {
        ASN1EncodableVector payload = new DEREncodableVector();
        for (Map.Entry<Asn1Oid, ASN1Encodable> entry : idAttributes.entrySet()) {
            DERObjectIdentifier type = new DERObjectIdentifier(entry.getKey().toOIDString());
            ASN1Set values = new DERSet(entry.getValue());
            Attribute attribute = new Attribute(type, values);
            payload.add(attribute);
        }
        attributes = new DERSet(payload);
    } else {
        attributes = null;
    }
    return new PKCS10CertificationRequest(sigAlgo, subject, kp.getPublic(), attributes, mClientKey).getEncoded();
}
Also used : DERSet(com.android.org.bouncycastle.asn1.DERSet) ASN1Set(com.android.org.bouncycastle.asn1.ASN1Set) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) Attribute(com.android.org.bouncycastle.asn1.x509.Attribute) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) DERPrintableString(com.android.org.bouncycastle.asn1.DERPrintableString) DERIA5String(com.android.org.bouncycastle.asn1.DERIA5String) DERSet(com.android.org.bouncycastle.asn1.DERSet) DERIA5String(com.android.org.bouncycastle.asn1.DERIA5String) Asn1Integer(com.android.hotspot2.asn1.Asn1Integer) DERPrintableString(com.android.org.bouncycastle.asn1.DERPrintableString) ASN1EncodableVector(com.android.org.bouncycastle.asn1.ASN1EncodableVector) List(java.util.List) ArrayList(java.util.ArrayList) ASN1Encodable(com.android.org.bouncycastle.asn1.ASN1Encodable) PKCS10CertificationRequest(com.android.org.bouncycastle.jce.PKCS10CertificationRequest) Asn1Oid(com.android.hotspot2.asn1.Asn1Oid) KeyPair(java.security.KeyPair) ECNamedCurveGenParameterSpec(com.android.org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec) DEREncodableVector(com.android.org.bouncycastle.asn1.DEREncodableVector) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) IOException(java.io.IOException) KeyPairGenerator(java.security.KeyPairGenerator) DERObjectIdentifier(com.android.org.bouncycastle.asn1.DERObjectIdentifier) Asn1Object(com.android.hotspot2.asn1.Asn1Object) OidMappings(com.android.hotspot2.asn1.OidMappings) ASN1Set(com.android.org.bouncycastle.asn1.ASN1Set) X500Principal(javax.security.auth.x500.X500Principal) Map(java.util.Map) HashMap(java.util.HashMap) AlgorithmParameters(java.security.AlgorithmParameters)

Example 7 with Attribute

use of com.android.org.bouncycastle.asn1.x509.Attribute in project nhin-d by DirectProject.

the class CertGenerator method createCertFromCSR.

public static X509Certificate createCertFromCSR(PKCS10CertificationRequest certReq, CertCreateFields signerCert) throws Exception {
    certReq.verify();
    final CertificationRequestInfo reqInfo = certReq.getCertificationRequestInfo();
    final X509V3CertificateGenerator v1CertGen = new X509V3CertificateGenerator();
    final Calendar start = Calendar.getInstance();
    final Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 3);
    v1CertGen.setSerialNumber(BigInteger.valueOf(generatePositiveRandom()));
    // issuer is the parent cert
    v1CertGen.setIssuerDN(signerCert.getSignerCert().getSubjectX500Principal());
    v1CertGen.setNotBefore(start.getTime());
    v1CertGen.setNotAfter(end.getTime());
    v1CertGen.setSubjectDN(new X509Principal(reqInfo.getSubject().toString()));
    v1CertGen.setPublicKey(certReq.getPublicKey());
    v1CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    final ASN1Set attributesAsn1Set = reqInfo.getAttributes();
    X509Extensions certificateRequestExtensions = null;
    for (int i = 0; i < attributesAsn1Set.size(); ++i) {
        // There should be only only one attribute in the set. (that is, only
        // the `Extension Request`, but loop through to find it properly)
        final DEREncodable derEncodable = attributesAsn1Set.getObjectAt(i);
        if (derEncodable instanceof DERSequence) {
            final Attribute attribute = new Attribute((DERSequence) attributesAsn1Set.getObjectAt(i));
            if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                // The `Extension Request` attribute is present.
                final ASN1Set attributeValues = attribute.getAttrValues();
                // Assume that it is the first value of the set.
                if (attributeValues.size() >= 1) {
                    certificateRequestExtensions = new X509Extensions((ASN1Sequence) attributeValues.getObjectAt(0));
                // No need to search any more.
                //break;
                }
            }
        }
    }
    @SuppressWarnings("unchecked") Enumeration<DERObjectIdentifier> oids = certificateRequestExtensions.oids();
    while (oids.hasMoreElements()) {
        DERObjectIdentifier oid = oids.nextElement();
        X509Extension ex = certificateRequestExtensions.getExtension(oid);
        v1CertGen.addExtension(oid, ex.isCritical(), X509Extension.convertValueToObject(ex));
    }
    return v1CertGen.generate((PrivateKey) signerCert.getSignerKey(), CryptoExtensions.getJCEProviderName());
}
Also used : CertificationRequestInfo(org.bouncycastle.asn1.pkcs.CertificationRequestInfo) Attribute(org.bouncycastle.asn1.cms.Attribute) X509Extension(org.bouncycastle.asn1.x509.X509Extension) Calendar(java.util.Calendar) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) X509Principal(org.bouncycastle.jce.X509Principal) DEREncodable(org.bouncycastle.asn1.DEREncodable)

Example 8 with Attribute

use of com.android.org.bouncycastle.asn1.x509.Attribute in project nhin-d by DirectProject.

the class MessageSigInspector method main.

public static void main(String[] args) {
    if (args.length == 0) {
        //printUsage();
        System.exit(-1);
    }
    String messgefile = null;
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        // Options
        if (!arg.startsWith("-")) {
            System.err.println("Error: Unexpected argument [" + arg + "]\n");
            //printUsage();
            System.exit(-1);
        } else if (arg.equalsIgnoreCase("-msgFile")) {
            if (i == args.length - 1 || args[i + 1].startsWith("-")) {
                System.err.println("Error: Missing message file");
                System.exit(-1);
            }
            messgefile = args[++i];
        } else if (arg.equals("-help")) {
            //printUsage();
            System.exit(-1);
        } else {
            System.err.println("Error: Unknown argument " + arg + "\n");
            //printUsage();
            System.exit(-1);
        }
    }
    if (messgefile == null) {
        System.err.println("Error: missing message file\n");
    }
    InputStream inStream = null;
    try {
        inStream = FileUtils.openInputStream(new File(messgefile));
        MimeMessage message = new MimeMessage(null, inStream);
        MimeMultipart mm = (MimeMultipart) message.getContent();
        //byte[] messageBytes = EntitySerializer.Default.serializeToBytes(mm.getBodyPart(0).getContent());
        //MimeBodyPart signedContent = null;
        //signedContent = new MimeBodyPart(new ByteArrayInputStream(messageBytes));
        final CMSSignedData signed = new CMSSignedData(new CMSProcessableBodyPart(mm.getBodyPart(0)), mm.getBodyPart(1).getInputStream());
        CertStore certs = signed.getCertificatesAndCRLs("Collection", CryptoExtensions.getJCEProviderName());
        SignerInformationStore signers = signed.getSignerInfos();
        @SuppressWarnings("unchecked") Collection<SignerInformation> c = signers.getSigners();
        System.out.println("Found " + c.size() + " signers");
        int cnt = 1;
        for (SignerInformation signer : c) {
            Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID());
            if (certCollection != null && certCollection.size() > 0) {
                X509Certificate cert = (X509Certificate) certCollection.iterator().next();
                System.out.println("\r\nInfo for certificate " + cnt++);
                System.out.println("\tSubject " + cert.getSubjectDN());
                FileUtils.writeByteArrayToFile(new File("SigCert.der"), cert.getEncoded());
                byte[] bytes = cert.getExtensionValue("2.5.29.15");
                if (bytes != null) {
                    final DERObject obj = getObject(bytes);
                    final KeyUsage keyUsage = new KeyUsage((DERBitString) obj);
                    final byte[] data = keyUsage.getBytes();
                    final int intValue = (data.length == 1) ? data[0] & 0xff : (data[1] & 0xff) << 8 | (data[0] & 0xff);
                    System.out.println("\tKey Usage: " + intValue);
                } else
                    System.out.println("\tKey Usage: NONE");
                //verify and get the digests
                final Attribute digAttr = signer.getSignedAttributes().get(CMSAttributes.messageDigest);
                final DERObject hashObj = digAttr.getAttrValues().getObjectAt(0).getDERObject();
                final byte[] signedDigest = ((ASN1OctetString) hashObj).getOctets();
                final String signedDigestHex = org.apache.commons.codec.binary.Hex.encodeHexString(signedDigest);
                System.out.println("\r\nSigned Message Digest: " + signedDigestHex);
                try {
                    signer.verify(cert, "BC");
                    System.out.println("Signature verified.");
                } catch (CMSException e) {
                    System.out.println("Signature failed to verify.");
                }
                // should have the computed digest now
                final byte[] digest = signer.getContentDigest();
                final String digestHex = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
                System.out.println("\r\nComputed Message Digest: " + digestHex);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(inStream);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) Attribute(org.bouncycastle.asn1.cms.Attribute) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) InputStream(java.io.InputStream) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) SignerInformation(org.bouncycastle.cms.SignerInformation) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CMSException(org.bouncycastle.cms.CMSException) PolicyProcessException(org.nhindirect.policy.PolicyProcessException) CMSProcessableBodyPart(org.bouncycastle.mail.smime.CMSProcessableBodyPart) DERObject(org.bouncycastle.asn1.DERObject) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) File(java.io.File) CertStore(java.security.cert.CertStore) CMSException(org.bouncycastle.cms.CMSException)

Example 9 with Attribute

use of com.android.org.bouncycastle.asn1.x509.Attribute in project robovm by robovm.

the class SignerInformation method doVerify.

private boolean doVerify(SignerInformationVerifier verifier) throws CMSException {
    String encName = CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID());
    ContentVerifier contentVerifier;
    try {
        contentVerifier = verifier.getContentVerifier(encryptionAlgorithm, info.getDigestAlgorithm());
    } catch (OperatorCreationException e) {
        throw new CMSException("can't create content verifier: " + e.getMessage(), e);
    }
    try {
        OutputStream sigOut = contentVerifier.getOutputStream();
        if (resultDigest == null) {
            DigestCalculator calc = verifier.getDigestCalculator(this.getDigestAlgorithmID());
            if (content != null) {
                OutputStream digOut = calc.getOutputStream();
                if (signedAttributeSet == null) {
                    if (contentVerifier instanceof RawContentVerifier) {
                        content.write(digOut);
                    } else {
                        OutputStream cOut = new TeeOutputStream(digOut, sigOut);
                        content.write(cOut);
                        cOut.close();
                    }
                } else {
                    content.write(digOut);
                    sigOut.write(this.getEncodedSignedAttributes());
                }
                digOut.close();
            } else if (signedAttributeSet != null) {
                sigOut.write(this.getEncodedSignedAttributes());
            } else {
                // TODO Get rid of this exception and just treat content==null as empty not missing?
                throw new CMSException("data not encapsulated in signature - use detached constructor.");
            }
            resultDigest = calc.getDigest();
        } else {
            if (signedAttributeSet == null) {
                if (content != null) {
                    content.write(sigOut);
                }
            } else {
                sigOut.write(this.getEncodedSignedAttributes());
            }
        }
        sigOut.close();
    } catch (IOException e) {
        throw new CMSException("can't process mime object to create signature.", e);
    } catch (OperatorCreationException e) {
        throw new CMSException("can't create digest calculator: " + e.getMessage(), e);
    }
    // RFC 3852 11.1 Check the content-type attribute is correct
    {
        ASN1Primitive validContentType = getSingleValuedSignedAttribute(CMSAttributes.contentType, "content-type");
        if (validContentType == null) {
            if (!isCounterSignature && signedAttributeSet != null) {
                throw new CMSException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
            }
        } else {
            if (isCounterSignature) {
                throw new CMSException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
            }
            if (!(validContentType instanceof ASN1ObjectIdentifier)) {
                throw new CMSException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
            }
            ASN1ObjectIdentifier signedContentType = (ASN1ObjectIdentifier) validContentType;
            if (!signedContentType.equals(contentType)) {
                throw new CMSException("content-type attribute value does not match eContentType");
            }
        }
    }
    // RFC 3852 11.2 Check the message-digest attribute is correct
    {
        ASN1Primitive validMessageDigest = getSingleValuedSignedAttribute(CMSAttributes.messageDigest, "message-digest");
        if (validMessageDigest == null) {
            if (signedAttributeSet != null) {
                throw new CMSException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
            }
        } else {
            if (!(validMessageDigest instanceof ASN1OctetString)) {
                throw new CMSException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
            }
            ASN1OctetString signedMessageDigest = (ASN1OctetString) validMessageDigest;
            if (!Arrays.constantTimeAreEqual(resultDigest, signedMessageDigest.getOctets())) {
                throw new CMSSignerDigestMismatchException("message-digest attribute value does not match calculated value");
            }
        }
    }
    // RFC 3852 11.4 Validate countersignature attribute(s)
    {
        AttributeTable signedAttrTable = this.getSignedAttributes();
        if (signedAttrTable != null && signedAttrTable.getAll(CMSAttributes.counterSignature).size() > 0) {
            throw new CMSException("A countersignature attribute MUST NOT be a signed attribute");
        }
        AttributeTable unsignedAttrTable = this.getUnsignedAttributes();
        if (unsignedAttrTable != null) {
            ASN1EncodableVector csAttrs = unsignedAttrTable.getAll(CMSAttributes.counterSignature);
            for (int i = 0; i < csAttrs.size(); ++i) {
                Attribute csAttr = (Attribute) csAttrs.get(i);
                if (csAttr.getAttrValues().size() < 1) {
                    throw new CMSException("A countersignature attribute MUST contain at least one AttributeValue");
                }
            // Note: We don't recursively validate the countersignature value
            }
        }
    }
    try {
        if (signedAttributeSet == null && resultDigest != null) {
            if (contentVerifier instanceof RawContentVerifier) {
                RawContentVerifier rawVerifier = (RawContentVerifier) contentVerifier;
                if (encName.equals("RSA")) {
                    DigestInfo digInfo = new DigestInfo(new AlgorithmIdentifier(digestAlgorithm.getAlgorithm(), DERNull.INSTANCE), resultDigest);
                    return rawVerifier.verify(digInfo.getEncoded(ASN1Encoding.DER), this.getSignature());
                }
                return rawVerifier.verify(resultDigest, this.getSignature());
            }
        }
        return contentVerifier.verify(this.getSignature());
    } catch (IOException e) {
        throw new CMSException("can't process mime object to create signature.", e);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) TeeOutputStream(org.bouncycastle.util.io.TeeOutputStream) Attribute(org.bouncycastle.asn1.cms.Attribute) ContentVerifier(org.bouncycastle.operator.ContentVerifier) RawContentVerifier(org.bouncycastle.operator.RawContentVerifier) OutputStream(java.io.OutputStream) TeeOutputStream(org.bouncycastle.util.io.TeeOutputStream) DigestCalculator(org.bouncycastle.operator.DigestCalculator) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) RawContentVerifier(org.bouncycastle.operator.RawContentVerifier) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 10 with Attribute

use of com.android.org.bouncycastle.asn1.x509.Attribute in project robovm by robovm.

the class X509AttributeCertificateHolder method isSignatureValid.

/**
     * Validate the signature on the attribute certificate in this holder.
     *
     * @param verifierProvider a ContentVerifierProvider that can generate a verifier for the signature.
     * @return true if the signature is valid, false otherwise.
     * @throws CertException if the signature cannot be processed or is inappropriate.
     */
public boolean isSignatureValid(ContentVerifierProvider verifierProvider) throws CertException {
    AttributeCertificateInfo acinfo = attrCert.getAcinfo();
    if (!CertUtils.isAlgIdEqual(acinfo.getSignature(), attrCert.getSignatureAlgorithm())) {
        throw new CertException("signature invalid - algorithm identifier mismatch");
    }
    ContentVerifier verifier;
    try {
        verifier = verifierProvider.get((acinfo.getSignature()));
        OutputStream sOut = verifier.getOutputStream();
        DEROutputStream dOut = new DEROutputStream(sOut);
        dOut.writeObject(acinfo);
        sOut.close();
    } catch (Exception e) {
        throw new CertException("unable to process signature: " + e.getMessage(), e);
    }
    return verifier.verify(attrCert.getSignatureValue().getBytes());
}
Also used : AttributeCertificateInfo(org.bouncycastle.asn1.x509.AttributeCertificateInfo) ContentVerifier(org.bouncycastle.operator.ContentVerifier) OutputStream(java.io.OutputStream) DEROutputStream(org.bouncycastle.asn1.DEROutputStream) IOException(java.io.IOException) DEROutputStream(org.bouncycastle.asn1.DEROutputStream)

Aggregations

Attribute (org.jdom2.Attribute)149 Element (org.jdom2.Element)104 IOException (java.io.IOException)31 ArrayList (java.util.ArrayList)27 Document (org.jdom2.Document)18 DataConversionException (org.jdom2.DataConversionException)16 X509Certificate (java.security.cert.X509Certificate)15 Editor (jmri.jmrit.display.Editor)15 GeneralName (org.bouncycastle.asn1.x509.GeneralName)15 Test (org.junit.Test)14 List (java.util.List)13 NamedIcon (jmri.jmrit.catalog.NamedIcon)13 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)12 Attribute (org.bouncycastle.asn1.pkcs.Attribute)12 Extensions (org.bouncycastle.asn1.x509.Extensions)12 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)12 CertificateEncodingException (java.security.cert.CertificateEncodingException)11 Attribute (org.bouncycastle.asn1.x509.Attribute)11 HashMap (java.util.HashMap)10 HashSet (java.util.HashSet)9