sun.security.pkcs.PKCS7 Java Examples

The following examples show how to use sun.security.pkcs.PKCS7. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TimestampCheck.java    From dragonwell8_jdk with GNU General Public License v2.0 7 votes vote down vote up
static void checkTimestamp(String file, String policyId, String digestAlg)
        throws Exception {
    try (JarFile jf = new JarFile(file)) {
        JarEntry je = jf.getJarEntry("META-INF/SIGNER.RSA");
        try (InputStream is = jf.getInputStream(je)) {
            byte[] content = IOUtils.readAllBytes(is);
            PKCS7 p7 = new PKCS7(content);
            SignerInfo[] si = p7.getSignerInfos();
            if (si == null || si.length == 0) {
                throw new Exception("Not signed");
            }
            PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes()
                    .getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
            PKCS7 tsToken = new PKCS7((byte[]) p9.getValue());
            TimestampToken tt =
                    new TimestampToken(tsToken.getContentInfo().getData());
            if (!tt.getHashAlgorithm().toString().equals(digestAlg)) {
                throw new Exception("Digest alg different");
            }
            if (!tt.getPolicyID().equals(policyId)) {
                throw new Exception("policyId different");
            }
        }
    }
}
 
Example #2
Source File: TimestampCheck.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void checkTimestamp(String file, String policyId, String digestAlg)
        throws Exception {
    try (JarFile jf = new JarFile(file)) {
        JarEntry je = jf.getJarEntry("META-INF/SIGNER.RSA");
        try (InputStream is = jf.getInputStream(je)) {
            byte[] content = IOUtils.readAllBytes(is);
            PKCS7 p7 = new PKCS7(content);
            SignerInfo[] si = p7.getSignerInfos();
            if (si == null || si.length == 0) {
                throw new Exception("Not signed");
            }
            PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes()
                    .getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
            PKCS7 tsToken = new PKCS7((byte[]) p9.getValue());
            TimestampToken tt =
                    new TimestampToken(tsToken.getContentInfo().getData());
            if (!tt.getHashAlgorithm().toString().equals(digestAlg)) {
                throw new Exception("Digest alg different");
            }
            if (!tt.getPolicyID().equals(policyId)) {
                throw new Exception("policyId different");
            }
        }
    }
}
 
Example #3
Source File: SignatureFileVerifier.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create the named SignatureFileVerifier.
 *
 * @param name the name of the signature block file (.DSA/.RSA/.EC)
 *
 * @param rawBytes the raw bytes of the signature block file
 */
public SignatureFileVerifier(ArrayList<CodeSigner[]> signerCache,
                             ManifestDigester md,
                             String name,
                             byte[] rawBytes)
    throws IOException, CertificateException
{
    // new PKCS7() calls CertificateFactory.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        block = new PKCS7(rawBytes);
        sfBytes = block.getContentInfo().getData();
        certificateFactory = CertificateFactory.getInstance("X509");
    } finally {
        Providers.stopJarVerification(obj);
    }
    this.name = name.substring(0, name.lastIndexOf('.'))
                                               .toUpperCase(Locale.ENGLISH);
    this.md = md;
    this.signerCache = signerCache;
}
 
Example #4
Source File: CertificateParser.java    From ApkToolPlus with Apache License 2.0 6 votes vote down vote up
/**
 * get certificate info
 *
 * @throws IOException
 * @throws CertificateEncodingException
 */
public void parse() throws IOException, CertificateException {

    PKCS7 pkcs7 = new PKCS7(Utils.toByteArray(in));
    X509Certificate[] certificates = pkcs7.getCertificates();
    certificateMetas = new ArrayList<>();
    for (X509Certificate certificate : certificates) {
        CertificateMeta certificateMeta = new CertificateMeta();
        certificateMetas.add(certificateMeta);

        byte[] bytes = certificate.getEncoded();
        String certMd5 = md5Digest(bytes);
        String publicKeyString = byteToHexString(bytes);
        String certBase64Md5 = md5Digest(publicKeyString);
        certificateMeta.setData(bytes);
        certificateMeta.setCertBase64Md5(certBase64Md5);
        certificateMeta.setCertMd5(certMd5);
        certificateMeta.setStartDate(certificate.getNotBefore());
        certificateMeta.setEndDate(certificate.getNotAfter());
        certificateMeta.setSignAlgorithm(certificate.getSigAlgName());
        certificateMeta.setSignAlgorithmOID(certificate.getSigAlgOID());
    }
}
 
Example #5
Source File: SignatureFileVerifier.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create the named SignatureFileVerifier.
 *
 * @param name the name of the signature block file (.DSA/.RSA/.EC)
 *
 * @param rawBytes the raw bytes of the signature block file
 */
public SignatureFileVerifier(ArrayList<CodeSigner[]> signerCache,
                             ManifestDigester md,
                             String name,
                             byte[] rawBytes)
    throws IOException, CertificateException
{
    // new PKCS7() calls CertificateFactory.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        block = new PKCS7(rawBytes);
        sfBytes = block.getContentInfo().getData();
        certificateFactory = CertificateFactory.getInstance("X509");
    } finally {
        Providers.stopJarVerification(obj);
    }
    this.name = name.substring(0, name.lastIndexOf('.'))
                                               .toUpperCase(Locale.ENGLISH);
    this.md = md;
    this.signerCache = signerCache;
}
 
Example #6
Source File: TimestampCheck.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static void checkTimestamp(String file, String policyId, String digestAlg)
        throws Exception {
    try (JarFile jf = new JarFile(file)) {
        JarEntry je = jf.getJarEntry("META-INF/OLD.RSA");
        try (InputStream is = jf.getInputStream(je)) {
            byte[] content = is.readAllBytes();
            PKCS7 p7 = new PKCS7(content);
            SignerInfo[] si = p7.getSignerInfos();
            if (si == null || si.length == 0) {
                throw new Exception("Not signed");
            }
            PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes()
                    .getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
            PKCS7 tsToken = new PKCS7((byte[]) p9.getValue());
            TimestampToken tt =
                    new TimestampToken(tsToken.getContentInfo().getData());
            if (!tt.getHashAlgorithm().toString().equals(digestAlg)) {
                throw new Exception("Digest alg different");
            }
            if (!tt.getPolicyID().equals(policyId)) {
                throw new Exception("policyId different");
            }
        }
    }
}
 
Example #7
Source File: SignatureFileVerifier.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create the named SignatureFileVerifier.
 *
 * @param name the name of the signature block file (.DSA/.RSA/.EC)
 *
 * @param rawBytes the raw bytes of the signature block file
 */
public SignatureFileVerifier(ArrayList<CodeSigner[]> signerCache,
                             ManifestDigester md,
                             String name,
                             byte[] rawBytes)
    throws IOException, CertificateException
{
    // new PKCS7() calls CertificateFactory.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        block = new PKCS7(rawBytes);
        sfBytes = block.getContentInfo().getData();
        certificateFactory = CertificateFactory.getInstance("X509");
    } finally {
        Providers.stopJarVerification(obj);
    }
    this.name = name.substring(0, name.lastIndexOf('.'))
                                               .toUpperCase(Locale.ENGLISH);
    this.md = md;
    this.signerCache = signerCache;
}
 
Example #8
Source File: SignatureFileVerifier.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create the named SignatureFileVerifier.
 *
 * @param name the name of the signature block file (.DSA/.RSA/.EC)
 *
 * @param rawBytes the raw bytes of the signature block file
 */
public SignatureFileVerifier(ArrayList<CodeSigner[]> signerCache,
                             ManifestDigester md,
                             String name,
                             byte[] rawBytes)
    throws IOException, CertificateException
{
    // new PKCS7() calls CertificateFactory.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        block = new PKCS7(rawBytes);
        sfBytes = block.getContentInfo().getData();
        certificateFactory = CertificateFactory.getInstance("X509");
    } finally {
        Providers.stopJarVerification(obj);
    }
    this.name = name.substring(0, name.lastIndexOf('.'))
                                               .toUpperCase(Locale.ENGLISH);
    this.md = md;
    this.signerCache = signerCache;
}
 
Example #9
Source File: SignatureFileVerifier.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Create the named SignatureFileVerifier.
 *
 * @param name the name of the signature block file (.DSA/.RSA/.EC)
 *
 * @param rawBytes the raw bytes of the signature block file
 */
public SignatureFileVerifier(ArrayList<CodeSigner[]> signerCache,
                             ManifestDigester md,
                             String name,
                             byte[] rawBytes)
    throws IOException, CertificateException
{
    // new PKCS7() calls CertificateFactory.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        block = new PKCS7(rawBytes);
        sfBytes = block.getContentInfo().getData();
        certificateFactory = CertificateFactory.getInstance("X509");
    } finally {
        Providers.stopJarVerification(obj);
    }
    this.name = name.substring(0, name.lastIndexOf('.'))
                                               .toUpperCase(Locale.ENGLISH);
    this.md = md;
    this.signerCache = signerCache;
}
 
Example #10
Source File: SignedJarBuilder.java    From javafxmobile-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Write the certificate file with a digital signature. */
private void writeSignatureBlock(Signature signature, X509Certificate publicKey,
        PrivateKey privateKey)
        throws IOException, GeneralSecurityException {
    SignerInfo signerInfo = new SignerInfo(
            new X500Name(publicKey.getIssuerX500Principal().getName()),
            publicKey.getSerialNumber(),
            AlgorithmId.get(DIGEST_ALGORITHM),
            AlgorithmId.get(privateKey.getAlgorithm()),
            signature.sign());

    PKCS7 pkcs7 = new PKCS7(
            new AlgorithmId[] { AlgorithmId.get(DIGEST_ALGORITHM) },
            new ContentInfo(ContentInfo.DATA_OID, null),
            new X509Certificate[] { publicKey },
            new SignerInfo[] { signerInfo });

    pkcs7.encodeSignedData(mOutputJar);
}
 
Example #11
Source File: SignatureFileVerifier.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create the named SignatureFileVerifier.
 *
 * @param name the name of the signature block file (.DSA/.RSA/.EC)
 *
 * @param rawBytes the raw bytes of the signature block file
 */
public SignatureFileVerifier(ArrayList<CodeSigner[]> signerCache,
                             ManifestDigester md,
                             String name,
                             byte[] rawBytes)
    throws IOException, CertificateException
{
    // new PKCS7() calls CertificateFactory.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        block = new PKCS7(rawBytes);
        sfBytes = block.getContentInfo().getData();
        certificateFactory = CertificateFactory.getInstance("X509");
    } finally {
        Providers.stopJarVerification(obj);
    }
    this.name = name.substring(0, name.lastIndexOf('.'))
                                               .toUpperCase(Locale.ENGLISH);
    this.md = md;
    this.signerCache = signerCache;
}
 
Example #12
Source File: SignedJarBuilder.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Write the certificate file with a digital signature.
 */
private void writeSignatureBlock(Signature signature, X509Certificate publicKey,
                                 PrivateKey privateKey)
        throws IOException, GeneralSecurityException {
    SignerInfo signerInfo = new SignerInfo(
            new X500Name(publicKey.getIssuerX500Principal().getName()),
            publicKey.getSerialNumber(),
            AlgorithmId.get(DIGEST_ALGORITHM),
            AlgorithmId.get(privateKey.getAlgorithm()),
            signature.sign());
    PKCS7 pkcs7 = new PKCS7(
            new AlgorithmId[]{AlgorithmId.get(DIGEST_ALGORITHM)},
            new ContentInfo(ContentInfo.DATA_OID, null),
            new X509Certificate[]{publicKey},
            new SignerInfo[]{signerInfo});
    pkcs7.encodeSignedData(mOutputJar);
}
 
Example #13
Source File: X509CertPath.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
 */
private byte[] encodePKCS7() throws CertificateEncodingException {
    PKCS7 p7 = new PKCS7(new AlgorithmId[0],
                         new ContentInfo(ContentInfo.DATA_OID, null),
                         certs.toArray(new X509Certificate[certs.size()]),
                         new SignerInfo[0]);
    DerOutputStream derout = new DerOutputStream();
    try {
        p7.encodeSignedData(derout);
    } catch (IOException ioe) {
        throw new CertificateEncodingException(ioe.getMessage());
    }
    return derout.toByteArray();
}
 
Example #14
Source File: TimestampedSigner.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generates a PKCS #7 signed data message that includes a signature
 * timestamp.
 * This method is used when a signature has already been generated.
 * The signature, a signature timestamp, the signer's certificate chain,
 * and optionally the content that was signed, are packaged into a PKCS #7
 * signed data message.
 *
 * @param params The non-null input parameters.
 * @param omitContent true if the content should be omitted from the
 *        signed data message. Otherwise the content is included.
 * @param applyTimestamp true if the signature should be timestamped.
 *        Otherwise timestamping is not performed.
 * @return A PKCS #7 signed data message including a signature timestamp.
 * @throws NoSuchAlgorithmException The exception is thrown if the signature
 *         algorithm is unrecognised.
 * @throws CertificateException The exception is thrown if an error occurs
 *         while processing the signer's certificate or the TSA's
 *         certificate.
 * @throws IOException The exception is thrown if an error occurs while
 *         generating the signature timestamp or while generating the signed
 *         data message.
 * @throws NullPointerException The exception is thrown if parameters is
 *         null.
 */
public byte[] generateSignedData(ContentSignerParameters params,
    boolean omitContent, boolean applyTimestamp)
        throws NoSuchAlgorithmException, CertificateException, IOException {

    if (params == null) {
        throw new NullPointerException();
    }

    // Parse the signature algorithm to extract the digest
    // algorithm. The expected format is:
    //     "<digest>with<encryption>"
    // or  "<digest>with<encryption>and<mgf>"
    String signatureAlgorithm = params.getSignatureAlgorithm();

    X509Certificate[] signerChain = params.getSignerCertificateChain();
    byte[] signature = params.getSignature();

    // Include or exclude content
    byte[] content = (omitContent == true) ? null : params.getContent();

    URI tsaURI = null;
    if (applyTimestamp) {
        tsaURI = params.getTimestampingAuthority();
        if (tsaURI == null) {
            // Examine TSA cert
            tsaURI = getTimestampingURI(
                params.getTimestampingAuthorityCertificate());
            if (tsaURI == null) {
                throw new CertificateException(
                    "Subject Information Access extension not found");
            }
        }
    }
    return PKCS7.generateSignedData(signature, signerChain, content,
                                    params.getSignatureAlgorithm(), tsaURI,
                                    params.getTSAPolicyID(),
                                    params.getTSADigestAlg());
}
 
Example #15
Source File: NonStandardNames.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example #16
Source File: X509CertPath.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
 */
private byte[] encodePKCS7() throws CertificateEncodingException {
    PKCS7 p7 = new PKCS7(new AlgorithmId[0],
                         new ContentInfo(ContentInfo.DATA_OID, null),
                         certs.toArray(new X509Certificate[certs.size()]),
                         new SignerInfo[0]);
    DerOutputStream derout = new DerOutputStream();
    try {
        p7.encodeSignedData(derout);
    } catch (IOException ioe) {
        throw new CertificateEncodingException(ioe.getMessage());
    }
    return derout.toByteArray();
}
 
Example #17
Source File: X509CertPath.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
 */
private byte[] encodePKCS7() throws CertificateEncodingException {
    PKCS7 p7 = new PKCS7(new AlgorithmId[0],
                         new ContentInfo(ContentInfo.DATA_OID, null),
                         certs.toArray(new X509Certificate[certs.size()]),
                         new SignerInfo[0]);
    DerOutputStream derout = new DerOutputStream();
    try {
        p7.encodeSignedData(derout);
    } catch (IOException ioe) {
        throw new CertificateEncodingException(ioe.getMessage());
    }
    return derout.toByteArray();
}
 
Example #18
Source File: SignatureFileVerifier.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given the PKCS7 block and SignerInfo[], create an array of
 * CodeSigner objects. We do this only *once* for a given
 * signature block file.
 */
private CodeSigner[] getSigners(SignerInfo[] infos, PKCS7 block)
    throws IOException, NoSuchAlgorithmException, SignatureException,
        CertificateException {

    ArrayList<CodeSigner> signers = null;

    for (int i = 0; i < infos.length; i++) {

        SignerInfo info = infos[i];
        ArrayList<X509Certificate> chain = info.getCertificateChain(block);
        CertPath certChain = certificateFactory.generateCertPath(chain);
        if (signers == null) {
            signers = new ArrayList<>();
        }
        // Append the new code signer
        signers.add(new CodeSigner(certChain, info.getTimestamp()));

        if (debug != null) {
            debug.println("Signature Block Certificate: " +
                chain.get(0));
        }
    }

    if (signers != null) {
        return signers.toArray(new CodeSigner[signers.size()]);
    } else {
        return null;
    }
}
 
Example #19
Source File: X509CertPath.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
 */
private byte[] encodePKCS7() throws CertificateEncodingException {
    PKCS7 p7 = new PKCS7(new AlgorithmId[0],
                         new ContentInfo(ContentInfo.DATA_OID, null),
                         certs.toArray(new X509Certificate[certs.size()]),
                         new SignerInfo[0]);
    DerOutputStream derout = new DerOutputStream();
    try {
        p7.encodeSignedData(derout);
    } catch (IOException ioe) {
        throw new CertificateEncodingException(ioe.getMessage());
    }
    return derout.toByteArray();
}
 
Example #20
Source File: NonStandardNames.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example #21
Source File: X509Factory.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private Collection<? extends java.security.cert.Certificate>
    parseX509orPKCS7Cert(InputStream is)
    throws CertificateException, IOException
{
    Collection<X509CertImpl> coll = new ArrayList<>();
    byte[] data = readOneBlock(is);
    if (data == null) {
        return new ArrayList<>(0);
    }
    try {
        PKCS7 pkcs7 = new PKCS7(data);
        X509Certificate[] certs = pkcs7.getCertificates();
        // certs are optional in PKCS #7
        if (certs != null) {
            return Arrays.asList(certs);
        } else {
            // no crls provided
            return new ArrayList<>(0);
        }
    } catch (ParsingException e) {
        while (data != null) {
            coll.add(new X509CertImpl(data));
            data = readOneBlock(is);
        }
    }
    return coll;
}
 
Example #22
Source File: X509CertPath.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
 */
private byte[] encodePKCS7() throws CertificateEncodingException {
    PKCS7 p7 = new PKCS7(new AlgorithmId[0],
                         new ContentInfo(ContentInfo.DATA_OID, null),
                         certs.toArray(new X509Certificate[certs.size()]),
                         new SignerInfo[0]);
    DerOutputStream derout = new DerOutputStream();
    try {
        p7.encodeSignedData(derout);
    } catch (IOException ioe) {
        throw new CertificateEncodingException(ioe.getMessage());
    }
    return derout.toByteArray();
}
 
Example #23
Source File: X509Factory.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private Collection<? extends java.security.cert.Certificate>
    parseX509orPKCS7Cert(InputStream is)
    throws CertificateException, IOException
{
    Collection<X509CertImpl> coll = new ArrayList<>();
    byte[] data = readOneBlock(is);
    if (data == null) {
        return new ArrayList<>(0);
    }
    try {
        PKCS7 pkcs7 = new PKCS7(data);
        X509Certificate[] certs = pkcs7.getCertificates();
        // certs are optional in PKCS #7
        if (certs != null) {
            return Arrays.asList(certs);
        } else {
            // no crls provided
            return new ArrayList<>(0);
        }
    } catch (ParsingException e) {
        while (data != null) {
            coll.add(new X509CertImpl(data));
            data = readOneBlock(is);
        }
    }
    return coll;
}
 
Example #24
Source File: NonStandardNames.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example #25
Source File: SignatureFileVerifier.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given the PKCS7 block and SignerInfo[], create an array of
 * CodeSigner objects. We do this only *once* for a given
 * signature block file.
 */
private CodeSigner[] getSigners(SignerInfo[] infos, PKCS7 block)
    throws IOException, NoSuchAlgorithmException, SignatureException,
        CertificateException {

    ArrayList<CodeSigner> signers = null;

    for (int i = 0; i < infos.length; i++) {

        SignerInfo info = infos[i];
        ArrayList<X509Certificate> chain = info.getCertificateChain(block);
        CertPath certChain = certificateFactory.generateCertPath(chain);
        if (signers == null) {
            signers = new ArrayList<>();
        }
        // Append the new code signer
        signers.add(new CodeSigner(certChain, info.getTimestamp()));

        if (debug != null) {
            debug.println("Signature Block Certificate: " +
                chain.get(0));
        }
    }

    if (signers != null) {
        return signers.toArray(new CodeSigner[signers.size()]);
    } else {
        return null;
    }
}
 
Example #26
Source File: SignatureFileVerifier.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create the named SignatureFileVerifier.
 *
 * @param name the name of the signature block file (.DSA/.RSA/.EC)
 *
 * @param rawBytes the raw bytes of the signature block file
 */
public SignatureFileVerifier(ArrayList<CodeSigner[]> signerCache,
                             ManifestDigester md,
                             String name,
                             byte rawBytes[])
    throws IOException, CertificateException
{
    // new PKCS7() calls CertificateFactory.getInstance()
    // need to use local providers here, see Providers class
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        block = new PKCS7(rawBytes);
        sfBytes = block.getContentInfo().getData();
        certificateFactory = CertificateFactory.getInstance("X509");
    } finally {
        Providers.stopJarVerification(obj);
    }
    this.name = name.substring(0, name.lastIndexOf("."))
                                               .toUpperCase(Locale.ENGLISH);
    this.md = md;
    this.signerCache = signerCache;
}
 
Example #27
Source File: X509CertPath.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
 */
private byte[] encodePKCS7() throws CertificateEncodingException {
    PKCS7 p7 = new PKCS7(new AlgorithmId[0],
                         new ContentInfo(ContentInfo.DATA_OID, null),
                         certs.toArray(new X509Certificate[certs.size()]),
                         new SignerInfo[0]);
    DerOutputStream derout = new DerOutputStream();
    try {
        p7.encodeSignedData(derout);
    } catch (IOException ioe) {
        throw new CertificateEncodingException(ioe.getMessage());
    }
    return derout.toByteArray();
}
 
Example #28
Source File: SignatureFileVerifier.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given the PKCS7 block and SignerInfo[], create an array of
 * CodeSigner objects. We do this only *once* for a given
 * signature block file.
 */
private CodeSigner[] getSigners(SignerInfo infos[], PKCS7 block)
    throws IOException, NoSuchAlgorithmException, SignatureException,
        CertificateException {

    ArrayList<CodeSigner> signers = null;

    for (int i = 0; i < infos.length; i++) {

        SignerInfo info = infos[i];
        ArrayList<X509Certificate> chain = info.getCertificateChain(block);
        CertPath certChain = certificateFactory.generateCertPath(chain);
        if (signers == null) {
            signers = new ArrayList<CodeSigner>();
        }
        // Append the new code signer
        signers.add(new CodeSigner(certChain, info.getTimestamp()));

        if (debug != null) {
            debug.println("Signature Block Certificate: " +
                chain.get(0));
        }
    }

    if (signers != null) {
        return signers.toArray(new CodeSigner[signers.size()]);
    } else {
        return null;
    }
}
 
Example #29
Source File: NonStandardNames.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        byte[] data = "Hello".getBytes();
        X500Name n = new X500Name("cn=Me");

        CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA");
        cakg.generate(1024);
        X509Certificate cert = cakg.getSelfCertificate(n, 1000);

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{
            new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID),
            new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)),
        });

        Signature s = Signature.getInstance("SHA256withRSA");
        s.initSign(cakg.getPrivateKey());
        s.update(authed.getDerEncoding());
        byte[] sig = s.sign();

        SignerInfo signerInfo = new SignerInfo(
                n,
                cert.getSerialNumber(),
                AlgorithmId.get("SHA-256"),
                authed,
                AlgorithmId.get("SHA256withRSA"),
                sig,
                null
                );

        PKCS7 pkcs7 = new PKCS7(
                new AlgorithmId[] {signerInfo.getDigestAlgorithmId()},
                new ContentInfo(data),
                new X509Certificate[] {cert},
                new SignerInfo[] {signerInfo});

        if (pkcs7.verify(signerInfo, data) == null) {
            throw new Exception("Not verified");
        }
    }
 
Example #30
Source File: X509Factory.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private Collection<? extends java.security.cert.CRL>
    parseX509orPKCS7CRL(InputStream is)
    throws CRLException, IOException
{
    Collection<X509CRLImpl> coll = new ArrayList<>();
    byte[] data = readOneBlock(is);
    if (data == null) {
        return new ArrayList<>(0);
    }
    try {
        PKCS7 pkcs7 = new PKCS7(data);
        X509CRL[] crls = pkcs7.getCRLs();
        // CRLs are optional in PKCS #7
        if (crls != null) {
            return Arrays.asList(crls);
        } else {
            // no crls provided
            return new ArrayList<>(0);
        }
    } catch (ParsingException e) {
        while (data != null) {
            coll.add(new X509CRLImpl(data));
            data = readOneBlock(is);
        }
    }
    return coll;
}