Example usage for org.bouncycastle.asn1 DEROctetString DEROctetString

List of usage examples for org.bouncycastle.asn1 DEROctetString DEROctetString

Introduction

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

Prototype

public DEROctetString(ASN1Encodable obj) throws IOException 

Source Link

Document

Constructor from the encoding of an ASN.1 object.

Usage

From source file:org.jmrtd.lds.SignedDataUtil.java

License:Open Source License

public static SignerInfo createSignerInfo(String digestAlgorithm, String digestEncryptionAlgorithm,
        String contentTypeOID, ContentInfo contentInfo, byte[] encryptedDigest,
        X509Certificate docSigningCertificate) throws NoSuchAlgorithmException {
    /* Get the issuer name (CN, O, OU, C) from the cert and put it in a SignerIdentifier struct. */
    X500Principal docSignerPrincipal = ((X509Certificate) docSigningCertificate).getIssuerX500Principal();
    X500Name docSignerName = new X500Name(docSignerPrincipal.getName(X500Principal.RFC2253));
    BigInteger serial = ((X509Certificate) docSigningCertificate).getSerialNumber();
    SignerIdentifier sid = new SignerIdentifier(new IssuerAndSerialNumber(docSignerName, serial));

    AlgorithmIdentifier digestAlgorithmObject = new AlgorithmIdentifier(
            new ASN1ObjectIdentifier(SignedDataUtil.lookupOIDByMnemonic(digestAlgorithm)));
    AlgorithmIdentifier digestEncryptionAlgorithmObject = new AlgorithmIdentifier(
            new ASN1ObjectIdentifier(SignedDataUtil.lookupOIDByMnemonic(digestEncryptionAlgorithm)));

    ASN1Set authenticatedAttributes = createAuthenticatedAttributes(digestAlgorithm, contentTypeOID,
            contentInfo); // struct containing the hash of content
    ASN1OctetString encryptedDigestObject = new DEROctetString(encryptedDigest); // this is the signature
    ASN1Set unAuthenticatedAttributes = null; // should be empty set?
    return new SignerInfo(sid, digestAlgorithmObject, authenticatedAttributes, digestEncryptionAlgorithmObject,
            encryptedDigestObject, unAuthenticatedAttributes);
}

From source file:org.jmrtd.lds.SignedDataUtil.java

License:Open Source License

public static ASN1Set createAuthenticatedAttributes(String digestAlgorithm, String contentTypeOID,
        ContentInfo contentInfo) throws NoSuchAlgorithmException {
    /* Check bug found by Paulo Assumpco. */
    if ("SHA256".equals(digestAlgorithm)) {
        digestAlgorithm = "SHA-256";
    }//from   www  .  j  av a 2s  .  c  om
    MessageDigest dig = MessageDigest.getInstance(digestAlgorithm);
    byte[] contentBytes = ((DEROctetString) contentInfo.getContent()).getOctets();
    byte[] digestedContentBytes = dig.digest(contentBytes);
    ASN1OctetString digestedContent = new DEROctetString(digestedContentBytes);
    Attribute contentTypeAttribute = new Attribute(
            new ASN1ObjectIdentifier(SignedDataUtil.RFC_3369_CONTENT_TYPE_OID),
            createSingletonSet(new ASN1ObjectIdentifier(contentTypeOID)));
    Attribute messageDigestAttribute = new Attribute(
            new ASN1ObjectIdentifier(SignedDataUtil.RFC_3369_MESSAGE_DIGEST_OID),
            createSingletonSet(digestedContent));
    ASN1Object[] result = { contentTypeAttribute.toASN1Primitive(), messageDigestAttribute.toASN1Primitive() };
    return new DLSet(result);
}

From source file:org.jmrtd.lds.SODFile.java

License:Open Source License

private static ContentInfo toContentInfo(String contentTypeOID, String digestAlgorithm,
        Map<Integer, byte[]> dataGroupHashes, String ldsVersion, String unicodeVersion)
        throws NoSuchAlgorithmException, IOException {
    DataGroupHash[] dataGroupHashesArray = new DataGroupHash[dataGroupHashes.size()];
    int i = 0;/*from   w w  w . j  av  a  2s .  co  m*/
    for (int dataGroupNumber : dataGroupHashes.keySet()) {
        byte[] hashBytes = dataGroupHashes.get(dataGroupNumber);
        DataGroupHash hash = new DataGroupHash(dataGroupNumber, new DEROctetString(hashBytes));
        dataGroupHashesArray[i++] = hash;
    }
    AlgorithmIdentifier digestAlgorithmIdentifier = new AlgorithmIdentifier(
            new ASN1ObjectIdentifier(SignedDataUtil.lookupOIDByMnemonic(digestAlgorithm)));
    LDSSecurityObject securityObject = null;
    if (ldsVersion == null) {
        securityObject = new LDSSecurityObject(digestAlgorithmIdentifier, dataGroupHashesArray);
    } else {
        securityObject = new LDSSecurityObject(digestAlgorithmIdentifier, dataGroupHashesArray,
                new LDSVersionInfo(ldsVersion, unicodeVersion));
    }

    return new ContentInfo(new ASN1ObjectIdentifier(contentTypeOID), new DEROctetString(securityObject));
}

From source file:org.jmrtd.lds.TerminalAuthenticationInfo.java

License:Open Source License

private static ASN1Sequence constructEFCVCA(short fileId, byte shortFileId) {
    if (shortFileId != -1) {
        return new DLSequence(new ASN1Encodable[] {
                new DEROctetString(new byte[] { (byte) ((fileId & 0xFF00) >> 8), (byte) (fileId & 0xFF) }),
                new DEROctetString(new byte[] { (byte) (shortFileId & 0xFF) }) });
    } else {//from  ww  w.j a v  a 2 s .c  o m
        return new DLSequence(new ASN1Encodable[] {
                new DEROctetString(new byte[] { (byte) ((fileId & 0xFF00) >> 8), (byte) (fileId & 0xFF) }) });
    }
}

From source file:org.jnotary.dvcs.SimpleRequestTest.java

License:Open Source License

@Test
public void cpd() throws IOException {

    DEROctetString message = new DEROctetString(testData.getBytes());
    Data data = new Data(message);

    DVCSRequestInformation requestInformation = new DVCSRequestInformation(ServiceType.CPD);

    requestInformation.setNonce(new DERInteger(random.nextLong()));

    DVCSTime requestTime = new DVCSTime(new DERGeneralizedTime(new java.util.Date()));
    requestInformation.setRequestTime(requestTime);

    DVCSRequest reqOut = new DVCSRequest(requestInformation, data);

    DVCSRequest reqIn = DVCSRequest.getInstance(reqOut.getEncoded());
    assertTrue("Service type is incorrect", reqIn.getRequestInformation().getService() == ServiceType.CPD);
    assertTrue("Nonce is incorrect",
            reqIn.getRequestInformation().getNonce().equals(reqOut.getRequestInformation().getNonce()));
    assertTrue("Request Time is incorrect", reqIn.getRequestInformation().getRequestTime()
            .equals(reqOut.getRequestInformation().getRequestTime()));
    assertTrue("Data is incorrect", reqIn.getData().getMessage().equals(reqOut.getData().getMessage()));
}

From source file:org.jnotary.dvcs.util.DvcsHelper.java

License:Open Source License

private static DVCSRequest createRequestWithOctets(int serviceType, byte[] reqdata, Long nonce) {
    DEROctetString message = new DEROctetString(reqdata);
    Data data = new Data(message);
    DVCSRequestInformation requestInformation = new DVCSRequestInformation(serviceType);
    requestInformation.setNonce(new DERInteger(nonce));
    DVCSTime requestTime = new DVCSTime(new DERGeneralizedTime(new java.util.Date()));
    requestInformation.setRequestTime(requestTime);
    return new DVCSRequest(requestInformation, data);
}

From source file:org.jruby.ext.openssl.impl.EncContent.java

License:LGPL

/**
 * EncryptedContentInfo ::= SEQUENCE {/*from  w w w . j a  v a  2  s  .co  m*/
 *   contentType ContentType,
 *   contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
 *   encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL }
 *
 * EncryptedContent ::= OCTET STRING
 */
public static EncContent fromASN1(ASN1Encodable content) {
    ASN1Sequence sequence = (ASN1Sequence) content;
    ASN1ObjectIdentifier contentType = (ASN1ObjectIdentifier) (sequence.getObjectAt(0));
    int nid = ASN1Registry.obj2nid(contentType);

    EncContent ec = new EncContent();
    ec.setContentType(nid);
    ec.setAlgorithm(AlgorithmIdentifier.getInstance(sequence.getObjectAt(1)));
    if (sequence.size() > 2 && sequence.getObjectAt(2) instanceof ASN1TaggedObject
            && ((ASN1TaggedObject) (sequence.getObjectAt(2))).getTagNo() == 0) {
        ASN1Encodable ee = ((ASN1TaggedObject) (sequence.getObjectAt(2))).getObject();
        if (ee instanceof ASN1Sequence && ((ASN1Sequence) ee).size() > 0) {
            ByteList combinedOctets = new ByteList();
            Enumeration enm = ((ASN1Sequence) ee).getObjects();
            while (enm.hasMoreElements()) {
                byte[] octets = ((ASN1OctetString) enm.nextElement()).getOctets();
                combinedOctets.append(octets);
            }
            ec.setEncData(new DEROctetString(combinedOctets.bytes()));
        } else {
            ec.setEncData((ASN1OctetString) ee);
        }
    }
    return ec;
}

From source file:org.jruby.ext.openssl.impl.PKCS7.java

License:LGPL

/** c: PKCS7_dataInit
 *
 *//*from w ww  .  j  a v a  2  s.c o m*/
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 = KeyGenerator.getInstance(algoBase);
            gen.init(evpCipher.getKeyLenInBits(), new SecureRandom());
            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 = Cipher.getInstance(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);
        }
        btmp = null;
    }

    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;
    }
    bio = null;
    return out;
}

From source file:org.jruby.ext.openssl.impl.PKCS7.java

License:LGPL

/** c: PKCS7_dataFinal
 *
 *///from   ww  w. j  a  va  2 s. c  o  m
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.obj2nid(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 = Signature.getInstance(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.obj2nid(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;
}

From source file:org.jruby.ext.openssl.impl.PKCS7DataData.java

License:LGPL

public PKCS7DataData() {
    this(new DEROctetString(new byte[0]));
}