Example usage for org.bouncycastle.asn1 ASN1Primitive fromByteArray

List of usage examples for org.bouncycastle.asn1 ASN1Primitive fromByteArray

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1Primitive fromByteArray.

Prototype

public static ASN1Primitive fromByteArray(byte[] data) throws IOException 

Source Link

Document

Create a base ASN.1 object from a byte stream.

Usage

From source file:CreateSignatureBase.java

License:Apache License

/**
 * SignatureInterface implementation.//from  w ww  . j  av a 2 s .  c  om
 *
 * This method will be called from inside of the pdfbox and create the PKCS #7 signature.
 * The given InputStream contains the bytes that are given by the byte range.
 *
 * This method is for internal use only. <-- TODO this method should be private
 *
 * Use your favorite cryptographic library to implement PKCS #7 signature creation.
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    try {
        List<Certificate> certList = new ArrayList<Certificate>();
        certList.add(certificate);
        Store certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate
                .getInstance(ASN1Primitive.fromByteArray(certificate.getEncoded()));
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
        gen.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                        .build(sha1Signer, new X509CertificateHolder(cert)));
        gen.addCertificates(certs);
        CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
        CMSSignedData signedData = gen.generate(msg, false);
        if (tsaClient != null) {
            signedData = signTimeStamps(signedData);
        }
        return signedData.getEncoded();
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    } catch (CMSException e) {
        throw new IOException(e);
    } catch (TSPException e) {
        throw new IOException(e);
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    }
}

From source file:CreateSignature.java

License:Apache License

/**
 * We are extending CMS Signature/*from w  ww  .java 2 s . c o m*/
 *
 * @param signer information about signer
 * @return information about SignerInformation
 */
private SignerInformation signTimeStamp(SignerInformation signer) throws IOException, TSPException {
    AttributeTable unsignedAttributes = signer.getUnsignedAttributes();

    ASN1EncodableVector vector = new ASN1EncodableVector();
    if (unsignedAttributes != null) {
        vector = unsignedAttributes.toASN1EncodableVector();
    }

    byte[] token = getTsaClient().getTimeStampToken(signer.getSignature());
    ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.id_aa_signatureTimeStampToken;
    ASN1Encodable signatureTimeStamp = new Attribute(oid, new DERSet(ASN1Primitive.fromByteArray(token)));

    vector.add(signatureTimeStamp);
    Attributes signedAttributes = new Attributes(vector);

    SignerInformation newSigner = SignerInformation.replaceUnsignedAttributes(signer,
            new AttributeTable(signedAttributes));

    // TODO can this actually happen?
    if (newSigner == null) {
        return signer;
    }

    return newSigner;
}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
static protected SignedData includeCrls(byte[] assinatura, Collection crls) throws IOException, Exception,
        SecurityException, CRLException, NoSuchProviderException, NoSuchAlgorithmException {

    org.bouncycastle.asn1.pkcs.SignedData pkcs7 = pkcs7SignedData(assinatura);

    ContentInfo content = new ContentInfo(CMSObjectIdentifiers.data, null);

    SignedData signedCms = new SignedData(pkcs7.getDigestAlgorithms(), content, pkcs7.getCertificates(),
            pkcs7.getCRLs(), pkcs7.getSignerInfos());

    ASN1EncodableVector vec = new ASN1EncodableVector();

    for (X509CRLObject crl : (Collection<X509CRLObject>) crls)
        vec.add(ASN1Primitive.fromByteArray(crl.getEncoded()));

    DERSet set = new DERSet(vec);

    // for (X509CRLObject crl : (Collection<X509CRLObject>) crls)
    // set.addObject(ASN1Object.fromByteArray(crl.getEncoded()));

    SignedData signedCmsWithCrls = new SignedData(signedCms.getDigestAlgorithms(),
            signedCms.getEncapContentInfo(), signedCms.getCertificates(), set, signedCms.getSignerInfos());
    signedCmsWithCrls.getCertificates();
    signedCmsWithCrls.getCRLs();//from www  .j  a v a 2 s. c o m
    return signedCmsWithCrls;
}

From source file:ca.trustpoint.m2m.M2mCertificate.java

License:Apache License

/**
 * Returns the DER encoded to be signed certificate data. This is what would be sent to a CA for
 * signing, or the data that will be verified with the signature.
 *
 * @return The DER encoded to be signed certificate data.
 * @throws IOException if the encoding fails.
 *//*from   w ww  .  j av a2 s  .c om*/
public byte[] getTBSCertificate() throws IOException {
    if (!isTbsCertificateValid()) {
        throw new IOException("One or more TBS certificate fields are invalid.");
    }

    ASN1EncodableVector elements = new ASN1EncodableVector();

    /*
     * Since the default is v1 (0), we do not need to explicitly add this to the ASN.1 output.
     *
     * elements.add( new DERTaggedObject( false, TbsCertificateFields.VERSION.getTagNumber(), new
     * ASN1Integer(VERSION)));
     */
    elements.add(new DERTaggedObject(false, TbsCertificateFields.SERIAL_NUMBER.getTagNumber(),
            new DEROctetString(serialNumber)));

    if (caKeyDefinition != null) {
        if (caKeyDefinition.getAlgorithm() != null) {
            elements.add(new DERTaggedObject(false, TbsCertificateFields.CA_ALGORITHM.getTagNumber(),
                    ASN1Primitive.fromByteArray(caKeyDefinition.getEncodedAlgorithm())));
        }

        if (caKeyDefinition.getParameters() != null) {
            elements.add(new DERTaggedObject(false, TbsCertificateFields.CA_ALGORITHM_PARAMETERS.getTagNumber(),
                    ASN1Primitive.fromByteArray(caKeyDefinition.getEncodedParameters())));
        }
    }

    if (issuer != null) {
        elements.add(new DERTaggedObject(false, TbsCertificateFields.ISSUER.getTagNumber(),
                DERSequence.getInstance(issuer.getEncoded())));
    }

    if (validFrom != null) {
        elements.add(new DERTaggedObject(false, TbsCertificateFields.VALID_FROM.getTagNumber(),
                // We record seconds, not milliseconds, hence the / 1000
                new DEROctetString(BigInteger.valueOf(validFrom.getTime() / 1000).toByteArray())));
    }

    if (validDuration != null) {
        elements.add(new DERTaggedObject(false, TbsCertificateFields.VALID_DURATION.getTagNumber(),
                new DEROctetString(BigInteger.valueOf(validDuration.intValue()).toByteArray())));
    }

    elements.add(new DERTaggedObject(false, TbsCertificateFields.SUBJECT.getTagNumber(),
            DERSequence.getInstance(subject.getEncoded())));

    if (publicKeyDefinition != null) {
        if (publicKeyDefinition.getAlgorithm() != null) {
            elements.add(new DERTaggedObject(false, TbsCertificateFields.PUBLIC_KEY_ALGORITHM.getTagNumber(),
                    ASN1Primitive.fromByteArray(publicKeyDefinition.getEncodedAlgorithm())));
        }

        if (publicKeyDefinition.getParameters() != null) {
            elements.add(new DERTaggedObject(false,
                    TbsCertificateFields.PUBLIC_KEY_ALGORITHM_PARAMETERS.getTagNumber(),
                    ASN1Primitive.fromByteArray(publicKeyDefinition.getEncodedParameters())));
        }
    }

    if (publicKey != null) {
        byte[] publicKeyBytes = KeyConversionUtils.convertEcPublicKeyToRawBytes(publicKey,
                isPublicKeyCompressed);

        elements.add(new DERTaggedObject(false, TbsCertificateFields.PUBLIC_KEY.getTagNumber(),
                new DEROctetString(publicKeyBytes)));
    }

    if (authorityKeyIdentifier != null) {
        elements.add(new DERTaggedObject(false, TbsCertificateFields.AUTHORITY_KEY_ID.getTagNumber(),
                ASN1Primitive.fromByteArray(authorityKeyIdentifier.getEncoded())));
    }

    if (subjectKeyIdentifier != null) {
        elements.add(new DERTaggedObject(false, TbsCertificateFields.SUBJECT_KEY_ID.getTagNumber(),
                new DEROctetString(subjectKeyIdentifier)));
    }

    if (keyUsage != null) {
        elements.add(new DERTaggedObject(false, TbsCertificateFields.KEY_USAGE.getTagNumber(),
                ASN1Primitive.fromByteArray(keyUsage.getEncoded())));
    }

    if (basicConstraints != null) {
        elements.add(new DERTaggedObject(false, TbsCertificateFields.BASIC_CONSTRAINTS.getTagNumber(),
                new ASN1Integer(basicConstraints.intValue())));
    }

    if (certificatePolicy != null) {
        elements.add(new DERTaggedObject(false, TbsCertificateFields.CERTIFICATE_POLICY.getTagNumber(),
                new ASN1ObjectIdentifier(certificatePolicy)));
    }

    if (subjectAlternativeName != null) {
        elements.add(new DERTaggedObject(true, TbsCertificateFields.SUBJECT_ALTERNATE_NAME.getTagNumber(),
                DERTaggedObject.getInstance(subjectAlternativeName.getEncoded())));
    }

    if (issuerAlternativeName != null) {
        elements.add(new DERTaggedObject(true, TbsCertificateFields.ISSUER_ALTERNATE_NAME.getTagNumber(),
                DERTaggedObject.getInstance(issuerAlternativeName.getEncoded())));
    }

    if (extendedKeyUsage != null) {
        elements.add(new DERTaggedObject(false, TbsCertificateFields.EXTENDED_KEY_USAGE.getTagNumber(),
                new ASN1ObjectIdentifier(extendedKeyUsage)));
    }

    if (authenticationInfoAccessOcsp != null) {
        elements.add(
                new DERTaggedObject(false, TbsCertificateFields.AUTHENTICATION_INFO_ACCESS_OCSP.getTagNumber(),
                        new DERIA5String(authenticationInfoAccessOcsp.toString())));
    }

    if (crlDistributionPointUri != null) {
        elements.add(new DERTaggedObject(false, TbsCertificateFields.CRL_DISTRIBUTION_POINT_URI.getTagNumber(),
                new DERIA5String(crlDistributionPointUri.toString())));
    }

    if (!extensions.isEmpty()) {
        ASN1EncodableVector toBeEncodedExtensions = new ASN1EncodableVector();

        for (Extension extension : extensions) {
            toBeEncodedExtensions.add(new DERSequence(extension.getEncoded()));
        }

        elements.add(new DERTaggedObject(false, TbsCertificateFields.EXTENSIONS.getTagNumber(),
                new DERSequence(toBeEncodedExtensions)));
    }

    return ((new DERSequence(elements)).getEncoded());
}

From source file:ca.trustpoint.m2m.M2mCertificateFactoryTest.java

License:Apache License

@BeforeClass
public static void initializeTests() throws Exception {
    // Construct certificate data
    // A full certificate
    M2mCertificate cert = new M2mCertificate();

    // serialNumber
    byte[] serialNumber = Hex.decode("F964EF36");
    cert.setSerialNumber(serialNumber);/* ww  w .  jav  a2s  . c  om*/

    // cAAlgorithm, CAAlgParams
    KeyAlgorithmDefinition caKeyDefinition = new KeyAlgorithmDefinition();
    caKeyDefinition.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA512_SECP521R1);
    caKeyDefinition.setParameters(Hex.decode("102030405060708090A0B0C0E0F0"));
    cert.setCaKeyDefinition(caKeyDefinition);

    // issuer
    EntityName issuer = new EntityName();
    issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.Country, "CA"));
    issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "MyRoot"));
    issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.DomainComponent, "DomC"));
    issuer.addAttribute(new EntityNameAttribute(EntityNameAttributeId.OctetsName, "ca2f00"));
    cert.setIssuer(issuer);

    // validFrom
    Calendar calendar = new GregorianCalendar(2016, 7, 1);
    Date validFrom = calendar.getTime();
    cert.setValidFrom(validFrom);

    // validDuration
    cert.setValidDuration(60 * 60 * 24 * 365);

    // subject
    EntityName subject = new EntityName();
    subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.Country, "CA"));
    subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.CommonName, "MyTest"));
    subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.DomainComponent, "DomC"));
    subject.addAttribute(new EntityNameAttribute(EntityNameAttributeId.OctetsName, "ca2f01"));
    cert.setSubject(subject);

    // pKAlgorithm, pKAlgParams
    KeyAlgorithmDefinition publicKeyDefinition = new KeyAlgorithmDefinition();
    publicKeyDefinition.setAlgorithm(M2mSignatureAlgorithmOids.ECDSA_SHA256_SECP256R1);
    publicKeyDefinition.setParameters(Hex.decode("0102030405060708090A0B0C0E0F"));
    cert.setPublicKeyDefinition(publicKeyDefinition);

    // pubKey
    byte[] rawPublicKey = Hex.decode("040078EF059D605AB85B6A25A6EF31A1A73A632D3CB04DC606A8CA0B58239661"
            + "68CFAF6131D8D9B53F6BDF6B62946EC4B41D618FA3FF7F8BBFACBFD4F64FE3C3"
            + "3DA9D200A47AE528DC50B6F3876D7F5BA3C082D9927751E1A8C4F934D90942B3"
            + "5C57DFE311B2663E8D0187AD4EDE31BF9CD2AD8317107360522FDB6975AB2CD6" + "6DC029981F");
    boolean isCompressed = KeyConversionUtils.isCompressedEcPoint(rawPublicKey);
    cert.setIsPublicKeyCompressed(isCompressed);

    PublicKey publicKey = KeyConversionUtils.convertRawBytestoEcPublicKey(rawPublicKey);
    cert.setPublicKey(publicKey);

    // authKeyId
    AuthorityKeyIdentifier authKeyId = new AuthorityKeyIdentifier();
    authKeyId.setKeyIdentifier(Hex.decode("793F0C56"));
    GeneralName authKeyIdIssuer = new GeneralName(GeneralNameAttributeId.DnsName, "authKeyIdIssuer");
    authKeyId.setCertificateIssuer(authKeyIdIssuer);
    authKeyId.setCertificateSerialNumber(new BigInteger(Hex.decode("729CB27DAE30")));
    cert.setAuthorityKeyIdentifier(authKeyId);

    // subjKeyId
    cert.setSubjectKeyIdentifier(Hex.decode("729CB27DAE31"));

    // keyUsage
    KeyUsage keyUsage = new KeyUsage();
    keyUsage.setDigitalSignature(true);
    cert.setKeyUsage(keyUsage);

    // basicConstraints
    cert.setBasicConstraints(5);

    // certificatePolicy
    cert.setCertificatePolicy("1.2.66.148.0.12");

    // subjectAltName
    GeneralName subjectAltName = new GeneralName(GeneralNameAttributeId.DnsName, "subjectAltName");
    cert.setSubjectAlternativeName(subjectAltName);

    // issuerAltName
    GeneralName issuerAltName = new GeneralName(GeneralNameAttributeId.DnsName, "issuerAltName");
    cert.setIssuerAlternativeName(issuerAltName);

    // extendedKeyUsage
    cert.setExtendedKeyUsage("1.3.22.174.22");

    // authInfoAccessOCSP
    URI authInfoAccessOCSP = new URI("https://ocsptest.trustpointinnovation.com");
    cert.setAuthenticationInfoAccessOcsp(authInfoAccessOCSP);

    // cRLDistribPointURI
    URI cRLDistribPointURI = new URI("https://ocsptest.trustpointinnovation.com");
    cert.setCrlDistributionPointUri(cRLDistribPointURI);

    // x509extensions
    String oid1 = "1.5.24.632.0";
    String oid2 = "1.5.24.632.1";
    byte[] value1 = Hex.decode("003a772fb1");
    byte[] value2 = Hex.decode("98f2b10e27");
    cert.addExtension(oid1, true, value1);
    cert.addExtension(oid2, false, value2);

    // cACalcValue
    byte[] caCalcValue = Hex.decode("3081880242014F15CAF8EF38626B2C7CFA85B9544E028668290CADB45F62E215"
            + "3EAAF5A9D51AF5BF0D02F2C057D3856B5CBFB3529C25B8481405924039FA612D"
            + "422AE9A1A85591024201868D3DFE5FC2BEDD2F7468B0B17ED2708E76CD0D37C4"
            + "4F4D0BB88693752046FCFC56D9818B32533B8992923C2C81499400AC44FBBECD" + "6324D8AE1DD41EC73A0B2A");
    cert.setCaCalcValue(caCalcValue);

    // get encoded data
    fullCertData = cert.getEncoded();

    int mySignerIndex = 0;
    int myIssuerIndex = 1;
    int bluelineIndex = 2;
    int certsTotal = 3;

    // construct certificate array
    ASN1Encodable[] certArray = new ASN1Encodable[certsTotal];
    certArray[mySignerIndex] = ASN1Primitive.fromByteArray(signerData);
    certArray[myIssuerIndex] = ASN1Primitive.fromByteArray(issuerData);
    certArray[bluelineIndex] = ASN1Primitive.fromByteArray(rootcaData);
    ASN1EncodableVector vCerts;

    // Construct PKI Path encoding input data
    vCerts = new ASN1EncodableVector();
    vCerts.add(certArray[bluelineIndex]);
    vCerts.add(certArray[myIssuerIndex]);
    vCerts.add(certArray[mySignerIndex]);
    pkiPathInputData = new DERSequence(vCerts).getEncoded();

    // Construct PKCS7 encoding input data
    ASN1EncodableVector vContentInfo = new ASN1EncodableVector();

    // contentType
    ASN1ObjectIdentifier contentType = PKCSObjectIdentifiers.data;
    vContentInfo.add(contentType);

    // content: signedData
    ASN1EncodableVector vSignedData = new ASN1EncodableVector();

    // version
    ASN1Integer sdVersion = new ASN1Integer(BigInteger.ONE);
    vSignedData.add(sdVersion);

    // digestAlgorithmIds
    DERSet sdDigestAlgorithmIds = new DERSet();
    vSignedData.add(sdDigestAlgorithmIds);

    // contentInfo without content
    BERSequence sdContentInfo = new BERSequence(PKCSObjectIdentifiers.data);
    vSignedData.add(sdContentInfo);

    // certificates [0] IMPLICIT SET OF certificate
    vCerts = new ASN1EncodableVector();
    vCerts.add(certArray[mySignerIndex]);
    vCerts.add(certArray[myIssuerIndex]);
    vCerts.add(certArray[bluelineIndex]);

    DERTaggedObject sdCertificates = new DERTaggedObject(false, 0, new DERSet(vCerts));
    vSignedData.add(sdCertificates);

    // signerInfos
    DERSet sdSignerInfos = new DERSet();
    vSignedData.add(sdSignerInfos);

    // content [0] EXPLICIT SEQUENCE signedData
    BERSequence signedData = new BERSequence(vSignedData);
    BERTaggedObject content = new BERTaggedObject(true, 0, signedData);
    vContentInfo.add(content);

    BERSequence contentInfo = new BERSequence(vContentInfo);
    pkcs7InputData = contentInfo.getEncoded();

    // Contruct cert path data list
    // Certificates are store in M2MCertPath from target to trust anchor.
    expectedCertPathData = new byte[][] { signerData, issuerData, rootcaData };
}

From source file:ca.trustpoint.m2m.M2mCertPath.java

License:Apache License

/**
 * Encode the CertPath using PKIPATH format.
 *
 * @return a byte array containing the binary encoding of the PkiPath object
 * @exception CertificateEncodingException if an exception occurs
 *///from  ww  w .j a  va 2s  . com
private byte[] encodePkiPath() throws CertificateEncodingException {
    ListIterator<M2mCertificate> li = certificates.listIterator(certificates.size());
    ASN1EncodableVector encodedList = new ASN1EncodableVector();

    // Get an encodable certificate vector. The certificates are encoded in reverse order (trust
    // anchor to target) according to PkiPath format.
    while (li.hasPrevious()) {
        M2mCertificate certificate = li.previous();

        if (isDuplicateCertificate(certificate)) {
            throw new CertificateEncodingException("Duplicate certificate detected in path.");
        }

        try {
            encodedList.add(ASN1Primitive.fromByteArray(certificate.getEncoded()));
        } catch (IOException ex) {
            throw new CertificateEncodingException("Error encoding certificate data.", ex);
        }
    }

    // Wrap the data in a SEQUENCE
    DERSequence sequence = new DERSequence(encodedList);

    try {
        return sequence.getEncoded();
    } catch (IOException ex) {
        throw new CertificateEncodingException("Error encoding certificate path.", ex);
    }
}

From source file:ca.trustpoint.m2m.M2mCertPath.java

License:Apache License

/**
 * Encode the CertPath using PKCS#7 format.
 *
 * @return a byte array containing the binary encoding of the PKCS#7 object
 * @exception CertificateEncodingException if an exception occurs
 *//*from   w w  w .  ja v  a  2  s. c o m*/
private byte[] encodePkcs7() throws CertificateEncodingException {
    ASN1EncodableVector encodedList = new ASN1EncodableVector();

    for (M2mCertificate certificate : certificates) {
        if (isDuplicateCertificate(certificate)) {
            throw new CertificateEncodingException("Duplicate certificate detected in path.");
        }

        try {
            encodedList.add(ASN1Primitive.fromByteArray(certificate.getEncoded()));
        } catch (IOException ex) {
            throw new CertificateEncodingException("Error encoding certificate data.", ex);
        }
    }

    SignedData sd = new SignedData(new ASN1Integer(BigInteger.ONE), // version
            new DERSet(), // digestAlgorithmIds
            new ContentInfo(PKCSObjectIdentifiers.data, null), // contentInfo
            new DERSet(encodedList), // certificates (optional)
            null, // CRLs (optional)
            new DERSet() // signerInfos
    );

    // make it a content info sequence
    ContentInfo ci = new ContentInfo(PKCSObjectIdentifiers.data, sd);

    try {
        return ci.getEncoded();
    } catch (IOException ex) {
        throw new CertificateEncodingException("Error encoding certificate path.", ex);
    }
}

From source file:ch.cyberduck.core.aquaticprime.ReceiptVerifier.java

License:Open Source License

@Override
public boolean verify() {
    try {/*from   ww w  . j  a  v  a  2 s .  c  om*/
        // For additional security, you may verify the fingerprint of the root CA and the OIDs of the
        // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the
        // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate
        // is (1 2 840 113635 100 6 11 1).
        final CMSSignedData s = new CMSSignedData(new FileInputStream(file.getAbsolute()));
        Store certs = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        for (SignerInformation signer : (Iterable<SignerInformation>) signers.getSigners()) {
            final Collection<X509CertificateHolder> matches = certs.getMatches(signer.getSID());
            for (X509CertificateHolder holder : matches) {
                if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder()
                        .setProvider(new BouncyCastleProvider()).build(holder))) {
                    return false;
                }
            }
        }
        // Extract the receipt attributes
        final CMSProcessable signedContent = s.getSignedContent();
        byte[] originalContent = (byte[]) signedContent.getContent();
        final ASN1Primitive asn = ASN1Primitive.fromByteArray(originalContent);

        byte[] opaque = null;
        String bundleIdentifier = null;
        String bundleVersion = null;
        byte[] hash = null;

        if (asn instanceof ASN1Set) {
            // 2 Bundle identifier      Interpret as an ASN.1 UTF8STRING.
            // 3 Application version    Interpret as an ASN.1 UTF8STRING.
            // 4 Opaque value           Interpret as a series of bytes.
            // 5 SHA-1 hash             Interpret as a 20-byte SHA-1 digest value.
            final ASN1Set set = (ASN1Set) asn;
            final Enumeration enumeration = set.getObjects();
            while (enumeration.hasMoreElements()) {
                Object next = enumeration.nextElement();
                if (next instanceof DLSequence) {
                    DLSequence sequence = (DLSequence) next;
                    ASN1Encodable type = sequence.getObjectAt(0);
                    if (type instanceof ASN1Integer) {
                        if (((ASN1Integer) type).getValue().intValue() == 2) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleIdentifier = new String(((DEROctetString) value).getOctets(), "UTF-8");
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 3) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleVersion = new String(((DEROctetString) value).getOctets(), "UTF-8");
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 4) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                opaque = ((DEROctetString) value).getOctets();
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 5) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                hash = ((DEROctetString) value).getOctets();
                            }
                        }
                    }
                }
            }
        } else {
            log.error(String.format("Expected set of attributes for %s", asn));
            return false;
        }
        if (!StringUtils.equals(PreferencesFactory.get().getDefault("application.identifier"),
                StringUtils.trim(bundleIdentifier))) {
            log.error(String.format("Bundle identifier %s in ASN set does not match", bundleIdentifier));
            return false;
        }
        if (!StringUtils.equals(PreferencesFactory.get().getDefault("application.version"),
                StringUtils.trim(bundleVersion))) {
            log.warn(String.format("Bundle version %s in ASN set does not match", bundleVersion));
        }
        final NetworkInterface en0 = NetworkInterface.getByName("en0");
        if (null == en0) {
            // Interface is not found when link is down #fail
            log.warn("No network interface en0");
            return true;
        } else {
            final byte[] mac = en0.getHardwareAddress();
            if (null == mac) {
                log.error("Cannot determine MAC address");
                // Continue without validation
                return true;
            }
            final String hex = Hex.encodeHexString(mac);
            if (log.isDebugEnabled()) {
                log.debug(String.format("Interface en0 %s", hex));
            }
            // Compute the hash of the GUID
            final MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(mac);
            if (null == opaque) {
                log.error(String.format("Missing opaque string in ASN.1 set %s", asn));
                return false;
            }
            digest.update(opaque);
            if (null == bundleIdentifier) {
                log.error(String.format("Missing bundle identifier in ASN.1 set %s", asn));
                return false;
            }
            digest.update(bundleIdentifier.getBytes(Charset.forName("UTF-8")));
            final byte[] result = digest.digest();
            if (Arrays.equals(result, hash)) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Valid receipt for GUID %s", hex));
                }
                guid = hex;
                return true;
            } else {
                log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt",
                        hex));
                return false;
            }
        }
    } catch (IOException e) {
        log.error("Receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    } catch (GeneralSecurityException e) {
        log.error("Receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    } catch (SecurityException e) {
        log.error("Receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    } catch (CMSException e) {
        log.error("Receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    } catch (Exception e) {
        log.error("Unknown receipt validation error", e);
        return true;
    }
}

From source file:com.ackpdfbox.app.CreateSignatureBase.java

License:Apache License

/**
 * SignatureInterface implementation.//from   w w  w .  j  a  va  2  s.com
 *
 * This method will be called from inside of the pdfbox and create the PKCS #7 signature.
 * The given InputStream contains the bytes that are given by the byte range.
 *
 * This method is for internal use only.
 *
 * Use your favorite cryptographic library to implement PKCS #7 signature creation.
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    //TODO this method should be private
    try {
        List<Certificate> certList = new ArrayList<Certificate>();
        certList.add(certificate);
        Store certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate
                .getInstance(ASN1Primitive.fromByteArray(certificate.getEncoded()));
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
        gen.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                        .build(sha1Signer, new X509CertificateHolder(cert)));
        gen.addCertificates(certs);
        CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
        CMSSignedData signedData = gen.generate(msg, false);
        if (tsaClient != null) {
            signedData = signTimeStamps(signedData);
        }
        return signedData.getEncoded();
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    } catch (CMSException e) {
        throw new IOException(e);
    } catch (TSPException e) {
        throw new IOException(e);
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    }
}

From source file:com.gsma.iariauth.validator.dsig.jre.BCCertificateInfo.java

License:Apache License

private static ASN1Primitive fromExtensionValue(byte[] encodedValue) throws IOException {
    ASN1OctetString octs = (ASN1OctetString) ASN1Primitive.fromByteArray(encodedValue);
    return ASN1Primitive.fromByteArray(octs.getOctets());
}