Search in sources :

Example 21 with ContentInfo

use of org.bouncycastle.asn1.pkcs.ContentInfo in project jruby-openssl by jruby.

the class PEMInputOutput method readPKCS7.

/**
 * Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
 * API.
 *
 * @return the X509Certificate
 * @throws IOException if an I/O error occured
 */
private static CMSSignedData readPKCS7(BufferedReader in, char[] p, String endMarker) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    String line;
    StringBuilder buffer = new StringBuilder();
    while ((line = in.readLine()) != null) {
        if (line.contains(endMarker))
            break;
        buffer.append(line.trim());
        final int len = buffer.length();
        Base64.decode(buffer.substring(0, (len / 4) * 4), bytes);
        buffer.delete(0, (len / 4) * 4);
    }
    if (buffer.length() != 0) {
        throw new IOException("base64 data appears to be truncated");
    }
    if (line == null)
        throw new IOException(endMarker + " not found");
    try {
        ASN1InputStream aIn = new ASN1InputStream(bytes.toByteArray());
        return new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
    } catch (CMSException e) {
        throw new IOException("problem parsing PKCS7 object: " + e, e);
    }
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ByteArrayOutputStream(org.jruby.ext.openssl.util.ByteArrayOutputStream) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DEROctetString(org.bouncycastle.asn1.DEROctetString) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSException(org.bouncycastle.cms.CMSException)

Example 22 with ContentInfo

use of org.bouncycastle.asn1.pkcs.ContentInfo in project jruby-openssl by jruby.

the class Signed method fromASN1.

/**
 * SignedData ::= SEQUENCE {
 *   version Version,
 *   digestAlgorithms DigestAlgorithmIdentifiers,
 *   contentInfo ContentInfo,
 *   certificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL,
 *   crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
 *   signerInfos SignerInfos }
 *
 * Version ::= INTEGER
 *
 * DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
 *
 * SignerInfos ::= SET OF SignerInfo
 */
public static Signed fromASN1(ASN1Encodable content) throws PKCS7Exception {
    ASN1Sequence sequence = (ASN1Sequence) content;
    ASN1Integer version = (ASN1Integer) sequence.getObjectAt(0);
    ASN1Set digestAlgos = (ASN1Set) sequence.getObjectAt(1);
    ASN1Encodable contentInfo = sequence.getObjectAt(2);
    ASN1Encodable certificates = null;
    ASN1Encodable crls = null;
    int index = 3;
    ASN1Encodable tmp = sequence.getObjectAt(index);
    if ((tmp instanceof ASN1TaggedObject) && ((ASN1TaggedObject) tmp).getTagNo() == 0) {
        certificates = ((ASN1TaggedObject) tmp).getObject();
        index++;
    }
    tmp = sequence.getObjectAt(index);
    if ((tmp instanceof ASN1TaggedObject) && ((ASN1TaggedObject) tmp).getTagNo() == 1) {
        crls = ((ASN1TaggedObject) tmp).getObject();
        index++;
    }
    ASN1Set signerInfos = (ASN1Set) sequence.getObjectAt(index);
    Signed signed = new Signed();
    signed.setVersion(version.getValue().intValue());
    signed.setMdAlgs(algorithmIdentifiersFromASN1Set(digestAlgos));
    signed.setContents(PKCS7.fromASN1(contentInfo));
    if (certificates != null) {
        signed.setCert(certificatesFromASN1Set(certificates));
    }
    if (crls != null) {
        throw new RuntimeException("TODO: implement CRL part");
    }
    signed.setSignerInfo(signerInfosFromASN1Set(signerInfos));
    return signed;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable)

Example 23 with ContentInfo

use of org.bouncycastle.asn1.pkcs.ContentInfo in project jruby-openssl by jruby.

the class PKCS7 method fromASN1.

/**
 * ContentInfo ::= SEQUENCE {
 *   contentType ContentType,
 *   content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
 *
 * ContentType ::= OBJECT IDENTIFIER
 */
public static PKCS7 fromASN1(ASN1Encodable obj) throws PKCS7Exception {
    PKCS7 p7 = new PKCS7();
    try {
        int size = ((ASN1Sequence) obj).size();
        if (size == 0) {
            return p7;
        }
        ASN1ObjectIdentifier contentType = (ASN1ObjectIdentifier) (((ASN1Sequence) obj).getObjectAt(0));
        if (EMPTY_PKCS7_OID.equals(contentType.getId())) {
            // OpenSSL behavior
            p7.setType(ASN1Registry.NID_undef);
        } else {
            final int nid = ASN1Registry.oid2nid(contentType);
            ASN1Encodable content = size == 1 ? (ASN1Encodable) null : ((ASN1Sequence) obj).getObjectAt(1);
            if (content != null && content instanceof ASN1TaggedObject && ((ASN1TaggedObject) content).getTagNo() == 0) {
                content = ((ASN1TaggedObject) content).getObject();
            }
            p7.initiateWith(nid, content);
        }
    }// somewhere the object does not obey to be PKCS7 object
     catch (ClassCastException e) {
        throw new IllegalArgumentException("not a PKCS7 Object");
    }
    return p7;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 24 with ContentInfo

use of org.bouncycastle.asn1.pkcs.ContentInfo in project jruby-openssl by jruby.

the class MiscPEMGenerator method createPemObject.

private PemObject createPemObject(Object o) throws IOException {
    String type;
    byte[] encoding;
    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509CertificateHolder) {
        type = "CERTIFICATE";
        encoding = ((X509CertificateHolder) o).getEncoded();
    } else if (o instanceof X509CRLHolder) {
        type = "X509 CRL";
        encoding = ((X509CRLHolder) o).getEncoded();
    } else if (o instanceof PrivateKeyInfo) {
        PrivateKeyInfo info = (PrivateKeyInfo) o;
        ASN1ObjectIdentifier algOID = info.getPrivateKeyAlgorithm().getAlgorithm();
        if (algOID.equals(PKCSObjectIdentifiers.rsaEncryption)) {
            type = "RSA PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (algOID.equals(dsaOids[0]) || algOID.equals(dsaOids[1])) {
            type = "DSA PRIVATE KEY";
            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new ASN1Integer(BigInteger.ZERO));
            v.add(new ASN1Integer(p.getP()));
            v.add(new ASN1Integer(p.getQ()));
            v.add(new ASN1Integer(p.getG()));
            BigInteger x = ASN1Integer.getInstance(info.parsePrivateKey()).getValue();
            BigInteger y = p.getG().modPow(x, p.getP());
            v.add(new ASN1Integer(y));
            v.add(new ASN1Integer(x));
            encoding = new DERSequence(v).getEncoded();
        } else if (algOID.equals(X9ObjectIdentifiers.id_ecPublicKey)) {
            type = "EC PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof SubjectPublicKeyInfo) {
        type = "PUBLIC KEY";
        encoding = ((SubjectPublicKeyInfo) o).getEncoded();
    } else if (o instanceof X509AttributeCertificateHolder) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificateHolder) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    } else // 
    if (// 1.47 compatibility
    o instanceof java.security.cert.X509Certificate) {
        type = "CERTIFICATE";
        try {
            encoding = ((java.security.cert.X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (// 1.47 compatibility
    o instanceof java.security.cert.X509CRL) {
        type = "X509 CRL";
        try {
            encoding = ((java.security.cert.X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (// 1.47 compatibility
    o instanceof java.security.KeyPair) {
        return createPemObject(((java.security.KeyPair) o).getPrivate());
    } else if (// 1.47 compatibility
    o instanceof java.security.PrivateKey) {
        PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(((java.security.Key) o).getEncoded()));
        if (o instanceof java.security.interfaces.RSAPrivateKey) {
            type = "RSA PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else if (o instanceof java.security.interfaces.DSAPrivateKey) {
            type = "DSA PRIVATE KEY";
            DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(p.getP()));
            v.add(new DERInteger(p.getQ()));
            v.add(new DERInteger(p.getG()));
            BigInteger x = ((java.security.interfaces.DSAPrivateKey) o).getX();
            BigInteger y = p.getG().modPow(x, p.getP());
            v.add(new DERInteger(y));
            v.add(new DERInteger(x));
            encoding = new DERSequence(v).getEncoded();
        } else if (((java.security.PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";
            encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (// 1.47 compatibility
    o instanceof java.security.PublicKey) {
        type = "PUBLIC KEY";
        encoding = ((java.security.PublicKey) o).getEncoded();
    } else if (// 1.47 compatibility
    o instanceof X509AttributeCertificate) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509AttributeCertificate) o).getEncoded();
    } else // 
    // 
    // 
    {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }
    if (// NEW STUFF (NOT IN OLD)
    encryptor != null) {
        String dekAlgName = Strings.toUpperCase(encryptor.getAlgorithm());
        // Note: For backward compatibility
        if (dekAlgName.equals("DESEDE")) {
            dekAlgName = "DES-EDE3-CBC";
        }
        byte[] iv = encryptor.getIV();
        byte[] encData = encryptor.encrypt(encoding);
        List<PemHeader> headers = new ArrayList<PemHeader>(2);
        headers.add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
        headers.add(new PemHeader("DEK-Info", dekAlgName + "," + getHexEncoded(iv)));
        return new PemObject(type, headers, encData);
    }
    return new PemObject(type, encoding);
}
Also used : ArrayList(java.util.ArrayList) X509AttributeCertificate(org.bouncycastle.x509.X509AttributeCertificate) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DERInteger(org.bouncycastle.asn1.DERInteger) PemObjectGenerator(org.bouncycastle.util.io.pem.PemObjectGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) CRLException(java.security.cert.CRLException) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) X509AttributeCertificateHolder(org.bouncycastle.cert.X509AttributeCertificateHolder) CertificateEncodingException(java.security.cert.CertificateEncodingException) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) PemObject(org.bouncycastle.util.io.pem.PemObject) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) BigInteger(java.math.BigInteger) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) PemHeader(org.bouncycastle.util.io.pem.PemHeader)

Example 25 with ContentInfo

use of org.bouncycastle.asn1.pkcs.ContentInfo in project certmgr by hdecarne.

the class PKCS12CertReaderWriter method readBinary.

@Override
@Nullable
public CertObjectStore readBinary(IOResource<InputStream> in, PasswordCallback password) throws IOException {
    LOG.debug("Trying to read PKCS#12 objects from: ''{0}''...", in);
    CertObjectStore certObjects = null;
    PKCS12PfxPdu pkcs12 = readPKCS12(in);
    if (pkcs12 != null) {
        certObjects = new CertObjectStore();
        for (ContentInfo contentInfo : pkcs12.getContentInfos()) {
            ASN1ObjectIdentifier contentType = contentInfo.getContentType();
            PKCS12SafeBagFactory safeBagFactory;
            if (contentType.equals(PKCSObjectIdentifiers.encryptedData)) {
                safeBagFactory = getSafeBagFactory(contentInfo, in.resource(), password);
            } else {
                safeBagFactory = getSafeBagFactory(contentInfo);
            }
            for (PKCS12SafeBag safeBag : safeBagFactory.getSafeBags()) {
                Object safeBagValue = safeBag.getBagValue();
                if (safeBagValue instanceof X509CertificateHolder) {
                    certObjects.addCRT(convertCRT((X509CertificateHolder) safeBagValue));
                } else if (safeBagValue instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PrivateKey privateKey = convertPrivateKey((PKCS8EncryptedPrivateKeyInfo) safeBagValue, in.resource(), password);
                    try {
                        certObjects.addKey(KeyHelper.rebuildKeyPair(privateKey));
                    } catch (IOException e) {
                        LOG.warning(e, "Unable to rebuild key pair for private key of type ''{1}''", privateKey.getClass().getName());
                    }
                } else if (safeBagValue instanceof PrivateKeyInfo) {
                    PrivateKey privateKey = convertPrivateKey((PrivateKeyInfo) safeBagValue);
                    try {
                        certObjects.addKey(KeyHelper.rebuildKeyPair(privateKey));
                    } catch (IOException e) {
                        LOG.warning(e, "Unable to rebuild key pair for private key of type ''{1}''", privateKey.getClass().getName());
                    }
                } else {
                    LOG.warning(CertIOI18N.STR_PKCS12_UNKNOWN_OBJECT, safeBagValue.getClass().getName());
                }
            }
        }
    }
    return certObjects;
}
Also used : PrivateKey(java.security.PrivateKey) PKCS12SafeBagFactory(org.bouncycastle.pkcs.PKCS12SafeBagFactory) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) CertObjectStore(de.carne.certmgr.certs.CertObjectStore) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) IOException(java.io.IOException) PKCS12SafeBag(org.bouncycastle.pkcs.PKCS12SafeBag) PKCS12PfxPdu(org.bouncycastle.pkcs.PKCS12PfxPdu) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) Nullable(de.carne.check.Nullable)

Aggregations

ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)24 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)22 IOException (java.io.IOException)20 X509Certificate (java.security.cert.X509Certificate)18 CMSSignedData (org.bouncycastle.cms.CMSSignedData)14 CertificateException (java.security.cert.CertificateException)12 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)12 BERSequence (org.bouncycastle.asn1.BERSequence)12 CertificateEncodingException (java.security.cert.CertificateEncodingException)11 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)9 ASN1Set (org.bouncycastle.asn1.ASN1Set)9 SignedData (org.bouncycastle.asn1.cms.SignedData)9 CMSException (org.bouncycastle.cms.CMSException)9 PrivateKey (java.security.PrivateKey)8 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)8 DERSet (org.bouncycastle.asn1.DERSet)8 ContentInfo (org.bouncycastle.asn1.pkcs.ContentInfo)8 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6