Search in sources :

Example 91 with ASN1OctetString

use of org.openecard.bouncycastle.asn1.ASN1OctetString in project jruby-openssl by jruby.

the class ASN1 method decodeObject.

// ObjectId
static IRubyObject decodeObject(final ThreadContext context, final RubyModule ASN1, final org.bouncycastle.asn1.ASN1Encodable obj) throws IOException, IllegalArgumentException {
    final Ruby runtime = context.runtime;
    if (obj instanceof ASN1Integer) {
        final BN val = BN.newBN(runtime, ((ASN1Integer) obj).getValue());
        return ASN1.getClass("Integer").callMethod(context, "new", val);
    }
    if (obj instanceof DERInteger) {
        final BN val = BN.newBN(runtime, ((DERInteger) obj).getValue());
        return ASN1.getClass("Integer").callMethod(context, "new", val);
    }
    if (obj instanceof DERBitString) {
        final DERBitString derObj = (DERBitString) obj;
        RubyString str = runtime.newString(new ByteList(derObj.getBytes(), false));
        IRubyObject bitString = ASN1.getClass("BitString").callMethod(context, "new", str);
        bitString.callMethod(context, "unused_bits=", runtime.newFixnum(derObj.getPadBits()));
        return bitString;
    }
    if (obj instanceof ASN1String) {
        final Integer typeId = typeId(obj.getClass());
        String type = typeId == null ? null : (String) (ASN1_INFO[typeId][2]);
        final ByteList bytes;
        if (obj instanceof DERUTF8String) {
            if (type == null)
                type = "UTF8String";
            bytes = new ByteList(((DERUTF8String) obj).getString().getBytes("UTF-8"), false);
        } else {
            if (type == null) {
                if (obj instanceof DERNumericString) {
                    type = "NumericString";
                } else if (obj instanceof DERPrintableString) {
                    type = "PrintableString";
                } else if (obj instanceof DERIA5String) {
                    type = "IA5String";
                } else if (obj instanceof DERT61String) {
                    type = "T61String";
                } else if (obj instanceof DERGeneralString) {
                    type = "GeneralString";
                } else if (obj instanceof DERUniversalString) {
                    type = "UniversalString";
                } else if (obj instanceof DERBMPString) {
                    type = "BMPString";
                } else {
                    // NOTE "VideotexString", "GraphicString", "ISO64String" not-handled in BC !
                    throw new IllegalArgumentException("could not handle ASN1 string type: " + obj + " (" + obj.getClass().getName() + ")");
                }
            }
            bytes = ByteList.create(((ASN1String) obj).getString());
        }
        return ASN1.getClass(type).callMethod(context, "new", runtime.newString(bytes));
    }
    if (obj instanceof ASN1OctetString) {
        final ByteList octets = new ByteList(((ASN1OctetString) obj).getOctets(), false);
        // final ByteList octets = new ByteList(((ASN1OctetString) obj).getEncoded(ASN1Encoding.DER), false);
        return ASN1.getClass("OctetString").callMethod(context, "new", runtime.newString(octets));
    }
    if (obj instanceof ASN1Null) {
        return ASN1.getClass("Null").callMethod(context, "new", runtime.getNil());
    }
    if (obj instanceof ASN1Boolean) {
        final boolean val = ((ASN1Boolean) obj).isTrue();
        return ASN1.getClass("Boolean").callMethod(context, "new", runtime.newBoolean(val));
    }
    // DERBoolean extends ASN1Boolean only since 1.51 (<= 1.50 the other way around)
    if (obj instanceof DERBoolean) {
        final boolean val = ((DERBoolean) obj).isTrue();
        return ASN1.getClass("Boolean").callMethod(context, "new", runtime.newBoolean(val));
    }
    if (obj instanceof ASN1UTCTime) {
        final Date adjustedTime;
        try {
            adjustedTime = ((ASN1UTCTime) obj).getAdjustedDate();
        } catch (ParseException e) {
            throw new IOException(e);
        }
        final RubyTime time = RubyTime.newTime(runtime, adjustedTime.getTime());
        return ASN1.getClass("UTCTime").callMethod(context, "new", time);
    }
    // NOTE: keep for BC versions compatibility ... extends ASN1UTCTime (since BC 1.51)
    if (obj instanceof DERUTCTime) {
        final Date adjustedTime;
        try {
            adjustedTime = ((DERUTCTime) obj).getAdjustedDate();
        } catch (ParseException e) {
            throw new IOException(e);
        }
        final RubyTime time = RubyTime.newTime(runtime, adjustedTime.getTime());
        return ASN1.getClass("UTCTime").callMethod(context, "new", time);
    }
    if (obj instanceof ASN1GeneralizedTime) {
        final Date generalTime;
        try {
            generalTime = ((ASN1GeneralizedTime) obj).getDate();
        } catch (ParseException e) {
            throw new IOException(e);
        }
        final RubyTime time = RubyTime.newTime(runtime, generalTime.getTime());
        return ASN1.getClass("GeneralizedTime").callMethod(context, "new", time);
    }
    // NOTE: keep for BC versions compatibility ... extends ASN1GeneralizedTime (since BC 1.51)
    if (obj instanceof DERGeneralizedTime) {
        final Date generalTime;
        try {
            generalTime = ((DERGeneralizedTime) obj).getDate();
        } catch (ParseException e) {
            throw new IOException(e);
        }
        final RubyTime time = RubyTime.newTime(runtime, generalTime.getTime());
        return ASN1.getClass("GeneralizedTime").callMethod(context, "new", time);
    }
    if (obj instanceof ASN1ObjectIdentifier) {
        final String objId = ((ASN1ObjectIdentifier) obj).getId();
        return ASN1.getClass("ObjectId").callMethod(context, "new", runtime.newString(objId));
    }
    // DERObjectIdentifier extends ASN1ObjectIdentifier = 1.51
    if (obj instanceof DERObjectIdentifier) {
        final String objId = ((DERObjectIdentifier) obj).getId();
        return ASN1.getClass("ObjectId").callMethod(context, "new", runtime.newString(objId));
    }
    if (obj instanceof ASN1TaggedObject) {
        final ASN1TaggedObject taggedObj = (ASN1TaggedObject) obj;
        IRubyObject val = decodeObject(context, ASN1, taggedObj.getObject());
        IRubyObject tag = runtime.newFixnum(taggedObj.getTagNo());
        IRubyObject tag_class = runtime.newSymbol("CONTEXT_SPECIFIC");
        final RubyArray valArr = runtime.newArray(val);
        return ASN1.getClass("ASN1Data").callMethod(context, "new", new IRubyObject[] { valArr, tag, tag_class });
    }
    if (obj instanceof DERApplicationSpecific) {
        final DERApplicationSpecific appSpecific = (DERApplicationSpecific) obj;
        IRubyObject tag = runtime.newFixnum(appSpecific.getApplicationTag());
        IRubyObject tag_class = runtime.newSymbol("APPLICATION");
        final ASN1Sequence sequence = (ASN1Sequence) appSpecific.getObject(SEQUENCE);
        @SuppressWarnings("unchecked") final RubyArray valArr = decodeObjects(context, ASN1, sequence.getObjects());
        return ASN1.getClass("ASN1Data").callMethod(context, "new", new IRubyObject[] { valArr, tag, tag_class });
    }
    if (obj instanceof ASN1Sequence) {
        @SuppressWarnings("unchecked") RubyArray arr = decodeObjects(context, ASN1, ((ASN1Sequence) obj).getObjects());
        return ASN1.getClass("Sequence").callMethod(context, "new", arr);
    }
    if (obj instanceof ASN1Set) {
        @SuppressWarnings("unchecked") RubyArray arr = decodeObjects(context, ASN1, ((ASN1Set) obj).getObjects());
        return ASN1.getClass("Set").callMethod(context, "new", arr);
    }
    if (obj instanceof ASN1Enumerated) {
        final RubyInteger value = RubyBignum.bignorm(runtime, ((ASN1Enumerated) obj).getValue());
        return ASN1.getClass("Enumerated").callMethod(context, "new", value);
    }
    throw new IllegalArgumentException("unable to decode object: " + obj + " (" + (obj == null ? "" : obj.getClass().getName()) + ")");
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) RubyTime(org.jruby.RubyTime) RubyArray(org.jruby.RubyArray) DERApplicationSpecific(org.bouncycastle.asn1.DERApplicationSpecific) RubyInteger(org.jruby.RubyInteger) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) ASN1UTCTime(org.bouncycastle.asn1.ASN1UTCTime) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DERGeneralString(org.bouncycastle.asn1.DERGeneralString) RubyString(org.jruby.RubyString) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERNumericString(org.bouncycastle.asn1.DERNumericString) DEROctetString(org.bouncycastle.asn1.DEROctetString) BEROctetString(org.bouncycastle.asn1.BEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERT61String(org.bouncycastle.asn1.DERT61String) DERVisibleString(org.bouncycastle.asn1.DERVisibleString) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) IRubyObject(org.jruby.runtime.builtin.IRubyObject) DERInteger(org.bouncycastle.asn1.DERInteger) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERGeneralizedTime(org.bouncycastle.asn1.DERGeneralizedTime) DERUTCTime(org.bouncycastle.asn1.DERUTCTime) ASN1Enumerated(org.bouncycastle.asn1.ASN1Enumerated) DERGeneralString(org.bouncycastle.asn1.DERGeneralString) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) Ruby(org.jruby.Ruby) DERBoolean(org.bouncycastle.asn1.DERBoolean) ByteList(org.jruby.util.ByteList) DERBMPString(org.bouncycastle.asn1.DERBMPString) RubyString(org.jruby.RubyString) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) Date(java.util.Date) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) BigInteger(java.math.BigInteger) RubyInteger(org.jruby.RubyInteger) DERInteger(org.bouncycastle.asn1.DERInteger) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ASN1Set(org.bouncycastle.asn1.ASN1Set) DERNumericString(org.bouncycastle.asn1.DERNumericString) DERT61String(org.bouncycastle.asn1.DERT61String) ASN1String(org.bouncycastle.asn1.ASN1String) ASN1Boolean(org.bouncycastle.asn1.ASN1Boolean) ParseException(java.text.ParseException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) ASN1Null(org.bouncycastle.asn1.ASN1Null)

Example 92 with ASN1OctetString

use of org.openecard.bouncycastle.asn1.ASN1OctetString in project jruby-openssl by jruby.

the class PKCS7 method dataDecode.

/**
 * c: PKCS7_dataDecode
 */
public BIO dataDecode(PrivateKey pkey, BIO inBio, X509AuxCertificate pcert) throws PKCS7Exception {
    BIO out = null;
    BIO btmp;
    BIO etmp;
    BIO bio;
    byte[] dataBody = null;
    Collection<AlgorithmIdentifier> mdSk = null;
    Collection<RecipInfo> rsk = null;
    AlgorithmIdentifier encAlg = null;
    Cipher evpCipher = null;
    RecipInfo ri = null;
    int i = getType();
    switch(i) {
        case ASN1Registry.NID_pkcs7_signed:
            dataBody = getSign().getContents().getOctetString().getOctets();
            mdSk = getSign().getMdAlgs();
            break;
        case ASN1Registry.NID_pkcs7_signedAndEnveloped:
            rsk = getSignedAndEnveloped().getRecipientInfo();
            mdSk = getSignedAndEnveloped().getMdAlgs();
            dataBody = getSignedAndEnveloped().getEncData().getEncData().getOctets();
            encAlg = getSignedAndEnveloped().getEncData().getAlgorithm();
            try {
                evpCipher = EVP.getCipher(encAlg.getAlgorithm());
            } catch (Exception e) {
                e.printStackTrace(System.err);
                throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNSUPPORTED_CIPHER_TYPE, e);
            }
            break;
        case ASN1Registry.NID_pkcs7_enveloped:
            rsk = getEnveloped().getRecipientInfo();
            dataBody = getEnveloped().getEncData().getEncData().getOctets();
            encAlg = getEnveloped().getEncData().getAlgorithm();
            try {
                evpCipher = EVP.getCipher(encAlg.getAlgorithm());
            } catch (Exception e) {
                e.printStackTrace(System.err);
                throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNSUPPORTED_CIPHER_TYPE, e);
            }
            break;
        default:
            throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNSUPPORTED_CONTENT_TYPE);
    }
    /* We will be checking the signature */
    if (mdSk != null) {
        for (AlgorithmIdentifier xa : mdSk) {
            try {
                MessageDigest evpMd = EVP.getDigest(xa.getAlgorithm());
                btmp = BIO.mdFilter(evpMd);
                if (out == null) {
                    out = btmp;
                } else {
                    out.push(btmp);
                }
            } catch (Exception e) {
                e.printStackTrace(System.err);
                throw new PKCS7Exception(F_PKCS7_DATADECODE, R_UNKNOWN_DIGEST_TYPE, e);
            }
        }
    }
    if (evpCipher != null) {
        /* Find the recipientInfo which matches the passed certificate
             * (if any)
             */
        if (pcert != null) {
            for (Iterator<RecipInfo> iter = rsk.iterator(); iter.hasNext(); ) {
                ri = iter.next();
                if (ri.compare(pcert)) {
                    break;
                }
                ri = null;
            }
            if (null == ri) {
                throw new PKCS7Exception(F_PKCS7_DATADECODE, R_NO_RECIPIENT_MATCHES_CERTIFICATE);
            }
        }
        byte[] tmp = null;
        /* If we haven't got a certificate try each ri in turn */
        if (null == pcert) {
            for (Iterator<RecipInfo> iter = rsk.iterator(); iter.hasNext(); ) {
                ri = iter.next();
                try {
                    tmp = EVP.decrypt(ri.getEncKey().getOctets(), pkey);
                    if (tmp != null) {
                        break;
                    }
                } catch (Exception e) {
                    tmp = null;
                }
                ri = null;
            }
            if (ri == null) {
                throw new PKCS7Exception(F_PKCS7_DATADECODE, R_NO_RECIPIENT_MATCHES_KEY);
            }
        } else {
            try {
                Cipher cipher = SecurityHelper.getCipher(CipherSpec.getWrappingAlgorithm(pkey.getAlgorithm()));
                cipher.init(Cipher.DECRYPT_MODE, pkey);
                tmp = cipher.doFinal(ri.getEncKey().getOctets());
            } catch (Exception e) {
                e.printStackTrace(System.err);
                throw new PKCS7Exception(F_PKCS7_DATADECODE, -1, e);
            }
        }
        ASN1Encodable params = encAlg.getParameters();
        try {
            String algo = org.jruby.ext.openssl.Cipher.Algorithm.getAlgorithmBase(evpCipher);
            if (params != null && params instanceof ASN1OctetString) {
                if (algo.startsWith("RC2")) {
                    // J9's IBMJCE needs this exceptional RC2 support.
                    // Giving IvParameterSpec throws 'Illegal parameter' on IBMJCE.
                    SecretKeySpec sks = new SecretKeySpec(tmp, algo);
                    RC2ParameterSpec s = new RC2ParameterSpec(tmp.length * 8, ((ASN1OctetString) params).getOctets());
                    evpCipher.init(Cipher.DECRYPT_MODE, sks, s);
                } else {
                    SecretKeySpec sks = new SecretKeySpec(tmp, algo);
                    IvParameterSpec iv = new IvParameterSpec(((ASN1OctetString) params).getOctets());
                    evpCipher.init(Cipher.DECRYPT_MODE, sks, iv);
                }
            } else {
                evpCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(tmp, algo));
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
            throw new PKCS7Exception(F_PKCS7_DATADECODE, -1, e);
        }
        etmp = BIO.cipherFilter(evpCipher);
        if (out == null) {
            out = etmp;
        } else {
            out.push(etmp);
        }
    }
    if (isDetached() || inBio != null) {
        bio = inBio;
    } else {
        if (dataBody != null && dataBody.length > 0) {
            bio = BIO.memBuf(dataBody);
        } else {
            bio = BIO.mem();
        }
    }
    out.push(bio);
    return out;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) RC2ParameterSpec(javax.crypto.spec.RC2ParameterSpec) MessageDigest(java.security.MessageDigest)

Example 93 with ASN1OctetString

use of org.openecard.bouncycastle.asn1.ASN1OctetString in project jruby-openssl by jruby.

the class PKCS7 method signatureVerify.

/* c: PKCS7_signatureVerify
     *
     */
public void signatureVerify(BIO bio, SignerInfoWithPkey si, X509AuxCertificate x509) throws PKCS7Exception {
    if (!isSigned() && !isSignedAndEnveloped()) {
        throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, R_WRONG_PKCS7_TYPE);
    }
    final int md_type = ASN1Registry.oid2nid(si.getDigestAlgorithm().getAlgorithm());
    BIO btmp = bio;
    MessageDigest mdc = null;
    for (; ; ) {
        if (btmp == null || (btmp = bio.findType(BIO.TYPE_MD)) == null) {
            throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, R_UNABLE_TO_FIND_MESSAGE_DIGEST);
        }
        mdc = ((MessageDigestBIOFilter) btmp).getMessageDigest();
        if (null == mdc) {
            throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, -1);
        }
        if (EVP.type(mdc) == md_type)
            break;
        btmp = btmp.next();
    }
    MessageDigest mdc_tmp = null;
    try {
        mdc_tmp = (MessageDigest) mdc.clone();
    } catch (Exception e) {
    }
    byte[] currentData = new byte[0];
    ASN1Set sk = si.getAuthenticatedAttributes();
    try {
        if (sk != null && sk.size() > 0) {
            byte[] md_dat = mdc_tmp.digest();
            ASN1OctetString message_digest = digestFromAttributes(sk);
            if (message_digest == null) {
                throw new PKCS7Exception(F_PKCS7_SIGNATUREVERIFY, R_UNABLE_TO_FIND_MESSAGE_DIGEST);
            }
            if (!Arrays.equals(md_dat, message_digest.getOctets())) {
                throw new NotVerifiedPKCS7Exception();
            }
            currentData = sk.getEncoded();
        }
        ASN1OctetString os = si.getEncryptedDigest();
        PublicKey pkey = x509.getPublicKey();
        Signature sign = SecurityHelper.getSignature(EVP.signatureAlgorithm(mdc_tmp, pkey));
        sign.initVerify(pkey);
        if (currentData.length > 0) {
            sign.update(currentData);
        }
        if (!sign.verify(os.getOctets())) {
            throw new NotVerifiedPKCS7Exception();
        }
    } catch (NotVerifiedPKCS7Exception e) {
        throw e;
    } catch (Exception e) {
        System.err.println("Other exception");
        e.printStackTrace(System.err);
        throw new NotVerifiedPKCS7Exception();
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1Set(org.bouncycastle.asn1.ASN1Set) PublicKey(java.security.PublicKey) Signature(java.security.Signature) MessageDigest(java.security.MessageDigest) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException)

Example 94 with ASN1OctetString

use of org.openecard.bouncycastle.asn1.ASN1OctetString in project jruby-openssl by jruby.

the class PKCS7 method dataInit.

/**
 * c: PKCS7_dataInit
 */
public BIO dataInit(BIO bio) throws PKCS7Exception {
    Collection<AlgorithmIdentifier> mdSk = null;
    ASN1OctetString os = null;
    int i = this.data.getType();
    Collection<RecipInfo> rsk = null;
    AlgorithmIdentifier xa = null;
    CipherSpec evpCipher = null;
    BIO out = null;
    BIO btmp = null;
    EncContent enc = null;
    switch(i) {
        case ASN1Registry.NID_pkcs7_signed:
            mdSk = getSign().getMdAlgs();
            os = getSign().getContents().getOctetString();
            break;
        case ASN1Registry.NID_pkcs7_signedAndEnveloped:
            rsk = getSignedAndEnveloped().getRecipientInfo();
            mdSk = getSignedAndEnveloped().getMdAlgs();
            enc = getSignedAndEnveloped().getEncData();
            evpCipher = getSignedAndEnveloped().getEncData().getCipher();
            if (null == evpCipher) {
                throw new PKCS7Exception(F_PKCS7_DATAINIT, R_CIPHER_NOT_INITIALIZED);
            }
            break;
        case ASN1Registry.NID_pkcs7_enveloped:
            rsk = getEnveloped().getRecipientInfo();
            enc = getEnveloped().getEncData();
            evpCipher = getEnveloped().getEncData().getCipher();
            if (null == evpCipher) {
                throw new PKCS7Exception(F_PKCS7_DATAINIT, R_CIPHER_NOT_INITIALIZED);
            }
            break;
        case ASN1Registry.NID_pkcs7_digest:
            xa = getDigest().getMd();
            os = getDigest().getContents().getOctetString();
            break;
        default:
            throw new PKCS7Exception(F_PKCS7_DATAINIT, R_UNSUPPORTED_CONTENT_TYPE);
    }
    if (mdSk != null) {
        for (AlgorithmIdentifier ai : mdSk) {
            if ((out = bioAddDigest(out, ai)) == null) {
                return null;
            }
        }
    }
    if (xa != null && (out = bioAddDigest(out, xa)) == null) {
        return null;
    }
    if (evpCipher != null) {
        byte[] tmp;
        btmp = BIO.cipherFilter(evpCipher.getCipher());
        String algoBase = evpCipher.getCipher().getAlgorithm();
        if (algoBase.indexOf('/') != -1) {
            algoBase = algoBase.split("/")[0];
        }
        try {
            KeyGenerator gen = SecurityHelper.getKeyGenerator(algoBase);
            gen.init(evpCipher.getKeyLenInBits(), SecurityHelper.getSecureRandom());
            SecretKey key = gen.generateKey();
            evpCipher.getCipher().init(Cipher.ENCRYPT_MODE, key);
            if (null != rsk) {
                for (RecipInfo ri : rsk) {
                    PublicKey pkey = ri.getCert().getPublicKey();
                    Cipher cipher = SecurityHelper.getCipher(CipherSpec.getWrappingAlgorithm(pkey.getAlgorithm()));
                    cipher.init(Cipher.ENCRYPT_MODE, pkey);
                    tmp = cipher.doFinal(key.getEncoded());
                    ri.setEncKey(new DEROctetString(tmp));
                }
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
            throw new PKCS7Exception(F_PKCS7_DATAINIT, R_ERROR_SETTING_CIPHER, e);
        }
        ASN1ObjectIdentifier encAlgo = ASN1Registry.sym2oid(evpCipher.getOsslName());
        if (encAlgo == null) {
            throw new PKCS7Exception(F_PKCS7_DATAINIT, R_CIPHER_HAS_NO_OBJECT_IDENTIFIER);
        }
        if (evpCipher.getCipher().getIV() != null) {
            enc.setAlgorithm(new AlgorithmIdentifier(encAlgo, new DEROctetString(evpCipher.getCipher().getIV())));
        } else {
            enc.setAlgorithm(new AlgorithmIdentifier(encAlgo));
        }
        if (out == null) {
            out = btmp;
        } else {
            out.push(btmp);
        }
    }
    if (bio == null) {
        if (isDetached()) {
            bio = BIO.nullSink();
        } else if (os != null && os.getOctets().length > 0) {
            bio = BIO.memBuf(os.getOctets());
        }
        if (bio == null) {
            bio = BIO.mem();
            bio.setMemEofReturn(0);
        }
    }
    if (out != null) {
        out.push(bio);
    } else {
        out = bio;
    }
    return out;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PublicKey(java.security.PublicKey) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) SecretKey(javax.crypto.SecretKey) Cipher(javax.crypto.Cipher) KeyGenerator(javax.crypto.KeyGenerator) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 95 with ASN1OctetString

use of org.openecard.bouncycastle.asn1.ASN1OctetString in project jruby-openssl by jruby.

the class PKCS7 method dataFinal.

/**
 * c: PKCS7_dataFinal
 */
public int dataFinal(BIO bio) throws PKCS7Exception {
    Collection<SignerInfoWithPkey> siSk = null;
    BIO btmp;
    byte[] buf;
    MessageDigest mdc = null;
    MessageDigest ctx_tmp = null;
    ASN1Set sk;
    int i = this.data.getType();
    switch(i) {
        case ASN1Registry.NID_pkcs7_signedAndEnveloped:
            siSk = getSignedAndEnveloped().getSignerInfo();
            break;
        case ASN1Registry.NID_pkcs7_signed:
            siSk = getSign().getSignerInfo();
            break;
        case ASN1Registry.NID_pkcs7_digest:
            break;
        default:
            break;
    }
    if (siSk != null) {
        for (SignerInfoWithPkey si : siSk) {
            if (si.getPkey() == null) {
                continue;
            }
            int j = ASN1Registry.oid2nid(si.getDigestAlgorithm().getAlgorithm());
            btmp = bio;
            MessageDigest[] _mdc = new MessageDigest[] { mdc };
            btmp = findDigest(_mdc, btmp, j);
            mdc = _mdc[0];
            if (btmp == null) {
                return 0;
            }
            try {
                ctx_tmp = (MessageDigest) mdc.clone();
            } catch (CloneNotSupportedException e) {
                throw new RuntimeException(e);
            }
            sk = si.getAuthenticatedAttributes();
            Signature sign = null;
            try {
                if (sk != null && sk.size() > 0) {
                    /* Add signing time if not already present */
                    if (null == si.getSignedAttribute(ASN1Registry.NID_pkcs9_signingTime)) {
                        DERUTCTime signTime = new DERUTCTime(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
                        si.addSignedAttribute(ASN1Registry.NID_pkcs9_signingTime, signTime);
                    }
                    byte[] md_data = ctx_tmp.digest();
                    ASN1OctetString digest = new DEROctetString(md_data);
                    si.addSignedAttribute(ASN1Registry.NID_pkcs9_messageDigest, digest);
                    sk = si.getAuthenticatedAttributes();
                    sign = SecurityHelper.getSignature(EVP.signatureAlgorithm(ctx_tmp, si.getPkey()));
                    sign.initSign(si.getPkey());
                    byte[] abuf = sk.getEncoded();
                    sign.update(abuf);
                }
                if (sign != null) {
                    byte[] out = sign.sign();
                    si.setEncryptedDigest(new DEROctetString(out));
                }
            } catch (Exception e) {
                throw new PKCS7Exception(F_PKCS7_DATAFINAL, -1, e);
            }
        }
    } else if (i == ASN1Registry.NID_pkcs7_digest) {
        int nid = ASN1Registry.oid2nid(getDigest().getMd().getAlgorithm());
        MessageDigest[] _mdc = new MessageDigest[] { mdc };
        bio = findDigest(_mdc, bio, nid);
        mdc = _mdc[0];
        byte[] md_data = mdc.digest();
        ASN1OctetString digest = new DEROctetString(md_data);
        getDigest().setDigest(digest);
    }
    if (!isDetached()) {
        btmp = bio.findType(BIO.TYPE_MEM);
        if (null == btmp) {
            throw new PKCS7Exception(F_PKCS7_DATAFINAL, R_UNABLE_TO_FIND_MEM_BIO);
        }
        buf = ((MemBIO) btmp).getMemCopy();
        switch(i) {
            case ASN1Registry.NID_pkcs7_signedAndEnveloped:
                getSignedAndEnveloped().getEncData().setEncData(new DEROctetString(buf));
                break;
            case ASN1Registry.NID_pkcs7_enveloped:
                getEnveloped().getEncData().setEncData(new DEROctetString(buf));
                break;
            case ASN1Registry.NID_pkcs7_signed:
                if (getSign().getContents().isData() && getDetached() != 0) {
                    getSign().getContents().setData(null);
                } else {
                    getSign().getContents().setData(new DEROctetString(buf));
                }
                break;
            case ASN1Registry.NID_pkcs7_digest:
                if (getDigest().getContents().isData() && getDetached() != 0) {
                    getDigest().getContents().setData(null);
                } else {
                    getDigest().getContents().setData(new DEROctetString(buf));
                }
                break;
        }
    }
    return 1;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) ASN1Set(org.bouncycastle.asn1.ASN1Set) DERUTCTime(org.bouncycastle.asn1.DERUTCTime) Signature(java.security.Signature) MessageDigest(java.security.MessageDigest)

Aggregations

ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)84 IOException (java.io.IOException)37 DEROctetString (org.bouncycastle.asn1.DEROctetString)25 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)23 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)22 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)19 ByteArrayInputStream (java.io.ByteArrayInputStream)16 X509Certificate (java.security.cert.X509Certificate)15 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)15 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)14 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)14 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)13 Enumeration (java.util.Enumeration)12 DERBitString (org.bouncycastle.asn1.DERBitString)12 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)11 CertificateException (java.security.cert.CertificateException)11 DERBMPString (org.bouncycastle.asn1.DERBMPString)11 DERIA5String (org.bouncycastle.asn1.DERIA5String)11 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)11 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)10