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:com.goodvikings.cryptim.api.KeyRing.java

License:BEER-WARE LICENSE

private byte[] ASN1EncodeKeys() throws IOException, PGPException {
    JcaPGPKeyConverter converter = new JcaPGPKeyConverter();

    PrivateKey priv = converter.getPrivateKey(kp.getPrivateKey());
    PublicKey pub = converter.getPublicKey(kp.getPublicKey());

    ASN1EncodableVector pubSeq = new ASN1EncodableVector();

    for (String jid : keys.keySet()) {
        pubSeq.add(new DERSequence(new ASN1Encodable[] { new DERUTF8String(jid),
                new DERUTF8String(nicks.get(jid)), new DERUTCTime(keys.get(jid).getCreationTime()),
                new DEROctetString(converter.getPublicKey(keys.get(jid)).getEncoded()) }));
    }/*  w ww.j  a va2s . c  o  m*/

    DERSequence seq = new DERSequence(new ASN1Encodable[] {
            new DERSequence(new ASN1Encodable[] { new DERUTCTime(kp.getPublicKey().getCreationTime()),
                    new DEROctetString(pub.getEncoded()) }),
            new DEROctetString(priv.getEncoded()), new DERSequence(pubSeq) });

    return seq.getEncoded();
}

From source file:com.google.bitcoin.core.ECKey.java

License:Apache License

/**
 * Output this ECKey as an ASN.1 encoded private key, as understood by OpenSSL or used by the BitCoin reference
 * implementation in its wallet storage format.
 *//*w  w  w.  j  a v  a2  s . co m*/
public byte[] toASN1() {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(400);

        // ASN1_SEQUENCE(EC_PRIVATEKEY) = {
        //   ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
        //   ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
        //   ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
        //   ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
        // } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
        DERSequenceGenerator seq = new DERSequenceGenerator(baos);
        seq.addObject(new ASN1Integer(1)); // version
        seq.addObject(new DEROctetString(priv.toByteArray()));
        seq.addObject(new DERTaggedObject(0, SECNamedCurves.getByName("secp256k1").toASN1Primitive()));
        seq.addObject(new DERTaggedObject(1, new DERBitString(getPubKey())));
        seq.close();
        return baos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e); // Cannot happen, writing to memory stream.
    }
}

From source file:com.guardtime.asn1.Asn1Util.java

License:Apache License

/**
 * Extends the given content info with data from the given certification
 * token./*  w  w w  .j  a v  a 2 s .co  m*/
 *
 * @param contentInfo
 *            the original timestamp encoded in a CMS {@code ContentInfo}
 *            structure.
 * @param certToken
 *            the {@code CertToken} from the GuardTime online verification
 *            service.
 * @return updated (extended) timestamp encoded in a new CMS
 *         {@code ContentInfo} structure.
 */
static org.bouncycastle.asn1.cms.ContentInfo extend(org.bouncycastle.asn1.cms.ContentInfo contentInfo,
        Asn1CertToken certToken) throws Asn1FormatException {
    ASN1EncodableVector v;

    // Extract signed data
    ASN1Encodable asn1SignedData = contentInfo.getContent();
    org.bouncycastle.asn1.cms.SignedData content = org.bouncycastle.asn1.cms.SignedData
            .getInstance(asn1SignedData);

    // Extract signer info
    ASN1Encodable asn1SignerInfo = content.getSignerInfos().getObjectAt(0);
    org.bouncycastle.asn1.cms.SignerInfo signerInfo = org.bouncycastle.asn1.cms.SignerInfo
            .getInstance(asn1SignerInfo);

    // Extract time signature
    ASN1Primitive asn1TimeSignature = null;
    try {
        asn1TimeSignature = ASN1Primitive.fromByteArray(signerInfo.getEncryptedDigest().getOctets());
    } catch (IOException e) {
        throw new Asn1FormatException("time signature has invalid format");
    }
    Asn1TimeSignature timeSignature = Asn1TimeSignature.getInstance(asn1TimeSignature);

    // Extend TimeSignature
    v = new ASN1EncodableVector();
    v.add(timeSignature.getLocation());
    v.add(certToken.getHistory());
    v.add(certToken.getPublishedData());
    // Skip PK signature <- updated
    v.add(new DERTaggedObject(false, 1, certToken.getPubReference()));
    timeSignature = Asn1TimeSignature.getInstance(new DERSequence(v));

    // Extend SignerInfo
    v = new ASN1EncodableVector();
    v.add(signerInfo.getVersion());
    v.add(signerInfo.getSID());
    v.add(signerInfo.getDigestAlgorithm());

    ASN1Set signedAttrs = signerInfo.getAuthenticatedAttributes();
    if (signedAttrs != null) {
        v.add(new DERTaggedObject(false, 0, signedAttrs));
    }

    v.add(signerInfo.getDigestEncryptionAlgorithm());
    try {
        v.add(new DEROctetString(timeSignature)); // <- updated
    } catch (IOException e) {
        throw new Asn1FormatException(e);
    }

    ASN1Set unsignedAttrs = signerInfo.getUnauthenticatedAttributes();
    if (unsignedAttrs != null) {
        v.add(new DERTaggedObject(false, 1, unsignedAttrs));
    }

    signerInfo = org.bouncycastle.asn1.cms.SignerInfo.getInstance(new DERSequence(v));

    // Extend SignedData
    v = new ASN1EncodableVector();
    v.add(content.getVersion());
    v.add(content.getDigestAlgorithms());
    v.add(content.getEncapContentInfo());
    // Skipping certificates <- updated
    // Skipping CRLs <- updated
    v.add(new DERSet(signerInfo)); // <- updated
    content = org.bouncycastle.asn1.cms.SignedData.getInstance(new DERSequence(v));

    // Extend ContentInfo
    v = new ASN1EncodableVector();
    v.add(contentInfo.getContentType());
    v.add(new DERTaggedObject(true, 0, content)); // <- updated
    contentInfo = org.bouncycastle.asn1.cms.ContentInfo.getInstance(new DERSequence(v));

    return contentInfo;
}

From source file:com.hierynomus.spnego.NegTokenInit.java

License:Apache License

private void addMechToken(ASN1EncodableVector negTokenInit) {
    if (mechToken != null && mechToken.length > 0) {
        ASN1Primitive token = new DERTaggedObject(true, 0x02, new DEROctetString(mechToken));
        negTokenInit.add(token);/*from ww w  .j  av  a  2  s .c  om*/
    }
}

From source file:com.hierynomus.spnego.NegTokenTarg.java

License:Apache License

public void write(Buffer<?> buffer) throws SpnegoException {
    try {//from  w  w  w . j av a 2s. c  o  m
        ASN1EncodableVector negTokenTarg = new ASN1EncodableVector();
        if (negotiationResult != null) {
            negTokenTarg.add(new DERTaggedObject(0x0, new ASN1Enumerated(negotiationResult)));
        }
        if (supportedMech != null) {
            negTokenTarg.add(new DERTaggedObject(0x01, supportedMech));
        }
        if (responseToken != null && responseToken.length > 0) {
            negTokenTarg.add(new DERTaggedObject(0x02, new DEROctetString(responseToken)));
        }
        if (mechListMic != null && mechListMic.length > 0) {
            negTokenTarg.add(new DERTaggedObject(0x03, new DEROctetString(mechListMic)));
        }

        writeGss(buffer, negTokenTarg);
    } catch (IOException e) {
        throw new SpnegoException("Could not write NegTokenTarg to buffer", e);
    }
}

From source file:com.itextpdf.kernel.crypto.securityhandler.PubKeySecurityHandler.java

License:Open Source License

private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert)
        throws IOException, GeneralSecurityException {
    EncryptionUtils.DERForRecipientParams parameters = EncryptionUtils.calculateDERForRecipientParams(in);

    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, parameters.abyte0);
    DEROctetString deroctetstring = new DEROctetString(parameters.abyte1);
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data,
            parameters.algorithmIdentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (ASN1Set) null);
    ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.toASN1Primitive();
}

From source file:com.itextpdf.kernel.crypto.securityhandler.PubKeySecurityHandler.java

License:Open Source License

private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
        throws GeneralSecurityException, IOException {
    ASN1InputStream asn1inputstream = new ASN1InputStream(
            new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure
            .getInstance(asn1inputstream.readObject());
    assert tbscertificatestructure != null;
    AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithm();
    IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(),
            tbscertificatestructure.getSerialNumber().getValue());
    byte[] cipheredBytes = EncryptionUtils.cipherBytes(x509certificate, abyte0, algorithmidentifier);
    DEROctetString deroctetstring = new DEROctetString(cipheredBytes);
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
}

From source file:com.itextpdf.signatures.LtvVerification.java

License:Open Source License

private static byte[] buildOCSPResponse(byte[] BasicOCSPResponse) throws IOException {
    DEROctetString doctet = new DEROctetString(BasicOCSPResponse);
    ASN1EncodableVector v2 = new ASN1EncodableVector();
    v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
    v2.add(doctet);/*w w  w  .j a va  2 s  . co  m*/
    ASN1Enumerated den = new ASN1Enumerated(0);
    ASN1EncodableVector v3 = new ASN1EncodableVector();
    v3.add(den);
    v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
    DERSequence seq = new DERSequence(v3);
    return seq.getEncoded();
}

From source file:com.itextpdf.signatures.PdfPKCS7.java

License:Open Source License

/**
 * Gets the bytes for the PKCS#1 object.
 *
 * @return a byte array//ww w  .  java  2  s. co  m
 */
public byte[] getEncodedPKCS1() {
    try {
        if (externalDigest != null)
            digest = externalDigest;
        else
            digest = sig.sign();
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        ASN1OutputStream dout = new ASN1OutputStream(bOut);
        dout.writeObject(new DEROctetString(digest));
        dout.close();

        return bOut.toByteArray();
    } catch (Exception e) {
        throw new PdfException(e);
    }
}

From source file:com.itextpdf.signatures.PdfPKCS7.java

License:Open Source License

/**
 * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
 * in the signerInfo can also be set, OR a time-stamp-authority client
 * may be provided./*from   w  w w .java2s . co  m*/
 *
 * @param secondDigest the digest in the authenticatedAttributes
 * @param tsaClient    TSAClient - null or an optional time stamp authority client
 * @return byte[] the bytes for the PKCS7SignedData object
 */
public byte[] getEncodedPKCS7(byte[] secondDigest, ITSAClient tsaClient, byte[] ocsp,
        Collection<byte[]> crlBytes, PdfSigner.CryptoStandard sigtype) {
    try {
        if (externalDigest != null) {
            digest = externalDigest;
            if (RSAdata != null)
                RSAdata = externalRSAdata;
        } else if (externalRSAdata != null && RSAdata != null) {
            RSAdata = externalRSAdata;
            sig.update(RSAdata);
            digest = sig.sign();
        } else {
            if (RSAdata != null) {
                RSAdata = messageDigest.digest();
                sig.update(RSAdata);
            }
            digest = sig.sign();
        }

        // Create the set of Hash algorithms
        ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector();
        for (Object element : digestalgos) {
            ASN1EncodableVector algos = new ASN1EncodableVector();
            algos.add(new ASN1ObjectIdentifier((String) element));
            algos.add(DERNull.INSTANCE);
            digestAlgorithms.add(new DERSequence(algos));
        }

        // Create the contentInfo.
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA));
        if (RSAdata != null)
            v.add(new DERTaggedObject(0, new DEROctetString(RSAdata)));
        DERSequence contentinfo = new DERSequence(v);

        // Get all the certificates
        //
        v = new ASN1EncodableVector();
        for (Object element : certs) {
            ASN1InputStream tempstream = new ASN1InputStream(
                    new ByteArrayInputStream(((X509Certificate) element).getEncoded()));
            v.add(tempstream.readObject());
        }

        DERSet dercertificates = new DERSet(v);

        // Create signerinfo structure.
        //
        ASN1EncodableVector signerinfo = new ASN1EncodableVector();

        // Add the signerInfo version
        //
        signerinfo.add(new ASN1Integer(signerversion));

        v = new ASN1EncodableVector();
        v.add(CertificateInfo.getIssuer(signCert.getTBSCertificate()));
        v.add(new ASN1Integer(signCert.getSerialNumber()));
        signerinfo.add(new DERSequence(v));

        // Add the digestAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestAlgorithmOid));
        v.add(DERNull.INSTANCE);
        signerinfo.add(new DERSequence(v));

        // add the authenticated attribute if present
        if (secondDigest != null) {
            signerinfo.add(new DERTaggedObject(false, 0,
                    getAuthenticatedAttributeSet(secondDigest, ocsp, crlBytes, sigtype)));
        }
        // Add the digestEncryptionAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestEncryptionAlgorithmOid));
        v.add(DERNull.INSTANCE);
        signerinfo.add(new DERSequence(v));

        // Add the digest
        signerinfo.add(new DEROctetString(digest));

        // When requested, go get and add the timestamp. May throw an exception.
        // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
        // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
        if (tsaClient != null) {
            byte[] tsImprint = tsaClient.getMessageDigest().digest(digest);
            byte[] tsToken = tsaClient.getTimeStampToken(tsImprint);
            if (tsToken != null) {
                ASN1EncodableVector unauthAttributes = buildUnauthenticatedAttributes(tsToken);
                if (unauthAttributes != null) {
                    signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unauthAttributes)));
                }
            }
        }

        // Finally build the body out of all the components above
        ASN1EncodableVector body = new ASN1EncodableVector();
        body.add(new ASN1Integer(version));
        body.add(new DERSet(digestAlgorithms));
        body.add(contentinfo);
        body.add(new DERTaggedObject(false, 0, dercertificates));

        // Only allow one signerInfo
        body.add(new DERSet(new DERSequence(signerinfo)));

        // Now we have the body, wrap it in it's PKCS7Signed shell
        // and return it
        //
        ASN1EncodableVector whole = new ASN1EncodableVector();
        whole.add(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA));
        whole.add(new DERTaggedObject(0, new DERSequence(body)));

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        ASN1OutputStream dout = new ASN1OutputStream(bOut);
        dout.writeObject(new DERSequence(whole));
        dout.close();

        return bOut.toByteArray();
    } catch (Exception e) {
        throw new PdfException(e);
    }
}