Java Code Examples for sun.security.util.DerOutputStream#toByteArray()

The following examples show how to use sun.security.util.DerOutputStream#toByteArray() . 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: DSA.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sign all the data thus far updated. The signature is formatted
 * according to the Canonical Encoding Rules, returned as a DER
 * sequence of Integer, r and s.
 *
 * @return a signature block formatted according to the Canonical
 * Encoding Rules.
 *
 * @exception SignatureException if the signature object was not
 * properly initialized, or if another exception occurs.
 *
 * @see sun.security.DSA#engineUpdate
 * @see sun.security.DSA#engineVerify
 */
protected byte[] engineSign() throws SignatureException {
    BigInteger k = generateK(presetQ);
    BigInteger r = generateR(presetP, presetQ, presetG, k);
    BigInteger s = generateS(presetX, presetQ, r, k);

    try {
        DerOutputStream outseq = new DerOutputStream(100);
        outseq.putInteger(r);
        outseq.putInteger(s);
        DerValue result = new DerValue(DerValue.tag_Sequence,
                                       outseq.toByteArray());

        return result.toByteArray();

    } catch (IOException e) {
        throw new SignatureException("error encoding signature");
    }
}
 
Example 2
Source File: CertificateIssuerExtension.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encode this extension
 */
private void encodeThis() throws IOException {
    if (names == null || names.isEmpty()) {
        this.extensionValue = null;
        return;
    }
    DerOutputStream os = new DerOutputStream();
    names.encode(os);
    this.extensionValue = os.toByteArray();
}
 
Example 3
Source File: TSRequest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public byte[] encode() throws IOException {

        DerOutputStream request = new DerOutputStream();

        // encode version
        request.putInteger(version);

        // encode messageImprint
        DerOutputStream messageImprint = new DerOutputStream();
        hashAlgorithmId.encode(messageImprint);
        messageImprint.putOctetString(hashValue);
        request.write(DerValue.tag_Sequence, messageImprint);

        // encode optional elements

        if (policyId != null) {
            request.putOID(new ObjectIdentifier(policyId));
        }
        if (nonce != null) {
            request.putInteger(nonce);
        }
        if (returnCertificate) {
            request.putBoolean(true);
        }

        DerOutputStream out = new DerOutputStream();
        out.write(DerValue.tag_Sequence, request);
        return out.toByteArray();
    }
 
Example 4
Source File: X509CertPath.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encode the CertPath using PKIPATH format.
 *
 * @return a byte array containing the binary encoding of the PkiPath object
 * @exception CertificateEncodingException if an exception occurs
 */
private byte[] encodePKIPATH() throws CertificateEncodingException {

    ListIterator<X509Certificate> li = certs.listIterator(certs.size());
    try {
        DerOutputStream bytes = new DerOutputStream();
        // encode certs in reverse order (trust anchor to target)
        // according to PkiPath format
        while (li.hasPrevious()) {
            X509Certificate cert = li.previous();
            // check for duplicate cert
            if (certs.lastIndexOf(cert) != certs.indexOf(cert)) {
                throw new CertificateEncodingException
                    ("Duplicate Certificate");
            }
            // get encoded certificates
            byte[] encoded = cert.getEncoded();
            bytes.write(encoded);
        }

        // Wrap the data in a SEQUENCE
        DerOutputStream derout = new DerOutputStream();
        derout.write(DerValue.tag_SequenceOf, bytes);
        return derout.toByteArray();

    } catch (IOException ioe) {
       throw new CertificateEncodingException("IOException encoding " +
               "PkiPath data: " + ioe, ioe);
    }
}
 
Example 5
Source File: CertificateIssuerExtension.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encode this extension
 */
private void encodeThis() throws IOException {
    if (names == null || names.isEmpty()) {
        this.extensionValue = null;
        return;
    }
    DerOutputStream os = new DerOutputStream();
    names.encode(os);
    this.extensionValue = os.toByteArray();
}
 
Example 6
Source File: X509CertPath.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Encode the CertPath using PKIPATH format.
 *
 * @return a byte array containing the binary encoding of the PkiPath object
 * @exception CertificateEncodingException if an exception occurs
 */
private byte[] encodePKIPATH() throws CertificateEncodingException {

    ListIterator<X509Certificate> li = certs.listIterator(certs.size());
    try {
        DerOutputStream bytes = new DerOutputStream();
        // encode certs in reverse order (trust anchor to target)
        // according to PkiPath format
        while (li.hasPrevious()) {
            X509Certificate cert = li.previous();
            // check for duplicate cert
            if (certs.lastIndexOf(cert) != certs.indexOf(cert)) {
                throw new CertificateEncodingException
                    ("Duplicate Certificate");
            }
            // get encoded certificates
            byte[] encoded = cert.getEncoded();
            bytes.write(encoded);
        }

        // Wrap the data in a SEQUENCE
        DerOutputStream derout = new DerOutputStream();
        derout.write(DerValue.tag_SequenceOf, bytes);
        return derout.toByteArray();

    } catch (IOException ioe) {
       throw new CertificateEncodingException("IOException encoding " +
               "PkiPath data: " + ioe, ioe);
    }
}
 
Example 7
Source File: CRLDistributionPointsExtension.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void encodeThis() throws IOException {
    if (distributionPoints.isEmpty()) {
        this.extensionValue = null;
    } else {
        DerOutputStream pnts = new DerOutputStream();
        for (DistributionPoint point : distributionPoints) {
            point.encode(pnts);
        }
        DerOutputStream seq = new DerOutputStream();
        seq.write(DerValue.tag_Sequence, pnts);
        this.extensionValue = seq.toByteArray();
    }
}
 
Example 8
Source File: X509CertificatePair.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the DER encoded form of the certificate pair.
 *
 * @return The encoded form of the certificate pair.
 * @throws CerticateEncodingException If an encoding exception occurs.
 */
public byte[] getEncoded() throws CertificateEncodingException {
    try {
        if (encoded == null) {
            DerOutputStream tmp = new DerOutputStream();
            emit(tmp);
            encoded = tmp.toByteArray();
        }
    } catch (IOException ex) {
        throw new CertificateEncodingException(ex.toString());
    }
    return encoded;
}
 
Example 9
Source File: SubjectInfoAccessExtension.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void encodeThis() throws IOException {
    if (accessDescriptions.isEmpty()) {
        this.extensionValue = null;
    } else {
        DerOutputStream ads = new DerOutputStream();
        for (AccessDescription accessDescription : accessDescriptions) {
            accessDescription.encode(ads);
        }
        DerOutputStream seq = new DerOutputStream();
        seq.write(DerValue.tag_Sequence, ads);
        this.extensionValue = seq.toByteArray();
    }
}
 
Example 10
Source File: X509CertPath.java    From dragonwell8_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 11
Source File: DSAParameters.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
protected byte[] engineGetEncoded() throws IOException {
    DerOutputStream out = new DerOutputStream();
    DerOutputStream bytes = new DerOutputStream();

    bytes.putInteger(p);
    bytes.putInteger(q);
    bytes.putInteger(g);
    out.write(DerValue.tag_Sequence, bytes);
    return out.toByteArray();
}
 
Example 12
Source File: DSAParameters.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
protected byte[] engineGetEncoded() throws IOException {
    DerOutputStream out = new DerOutputStream();
    DerOutputStream bytes = new DerOutputStream();

    bytes.putInteger(p);
    bytes.putInteger(q);
    bytes.putInteger(g);
    out.write(DerValue.tag_Sequence, bytes);
    return out.toByteArray();
}
 
Example 13
Source File: PKCS12KeyStore.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private byte[] calculateMac(char[] passwd, byte[] data)
    throws IOException
{
    byte[] mData = null;
    String algName = "SHA1";

    try {
        // Generate a random salt.
        byte[] salt = getSalt();

        // generate MAC (MAC key is generated within JCE)
        Mac m = Mac.getInstance("HmacPBESHA1");
        PBEParameterSpec params =
                    new PBEParameterSpec(salt, iterationCount);
        SecretKey key = getPBEKey(passwd);
        m.init(key, params);
        m.update(data);
        byte[] macResult = m.doFinal();

        // encode as MacData
        MacData macData = new MacData(algName, macResult, salt,
                                            iterationCount);
        DerOutputStream bytes = new DerOutputStream();
        bytes.write(macData.getEncoded());
        mData = bytes.toByteArray();
    } catch (Exception e) {
        throw new IOException("calculateMac failed: " + e, e);
    }
    return mData;
}
 
Example 14
Source File: Oid.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Returns the full ASN.1 DER encoding for this oid object, which
 * includes the tag and length.
 *
 * @return byte array containing the DER encoding of this oid object.
 * @exception GSSException may be thrown when the oid can't be encoded
 */
public byte[] getDER() throws GSSException {

    if (derEncoding == null) {
        DerOutputStream dout = new DerOutputStream();
        try {
            dout.putOID(oid);
        } catch (IOException e) {
            throw new GSSException(GSSException.FAILURE, e.getMessage());
        }
        derEncoding = dout.toByteArray();
    }

    return derEncoding.clone();
}
 
Example 15
Source File: PKCS12KeyStore.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
private byte[] getBagAttributes(String alias, byte[] keyId,
    ObjectIdentifier[] trustedUsage,
    Set<KeyStore.Entry.Attribute> attributes) throws IOException {

    byte[] localKeyID = null;
    byte[] friendlyName = null;
    byte[] trustedKeyUsage = null;

    // return null if all three attributes are null
    if ((alias == null) && (keyId == null) && (trustedKeyUsage == null)) {
        return null;
    }

    // SafeBag Attributes
    DerOutputStream bagAttrs = new DerOutputStream();

    // Encode the friendlyname oid.
    if (alias != null) {
        DerOutputStream bagAttr1 = new DerOutputStream();
        bagAttr1.putOID(PKCS9FriendlyName_OID);
        DerOutputStream bagAttrContent1 = new DerOutputStream();
        DerOutputStream bagAttrValue1 = new DerOutputStream();
        bagAttrContent1.putBMPString(alias);
        bagAttr1.write(DerValue.tag_Set, bagAttrContent1);
        bagAttrValue1.write(DerValue.tag_Sequence, bagAttr1);
        friendlyName = bagAttrValue1.toByteArray();
    }

    // Encode the localkeyId oid.
    if (keyId != null) {
        DerOutputStream bagAttr2 = new DerOutputStream();
        bagAttr2.putOID(PKCS9LocalKeyId_OID);
        DerOutputStream bagAttrContent2 = new DerOutputStream();
        DerOutputStream bagAttrValue2 = new DerOutputStream();
        bagAttrContent2.putOctetString(keyId);
        bagAttr2.write(DerValue.tag_Set, bagAttrContent2);
        bagAttrValue2.write(DerValue.tag_Sequence, bagAttr2);
        localKeyID = bagAttrValue2.toByteArray();
    }

    // Encode the trustedKeyUsage oid.
    if (trustedUsage != null) {
        DerOutputStream bagAttr3 = new DerOutputStream();
        bagAttr3.putOID(TrustedKeyUsage_OID);
        DerOutputStream bagAttrContent3 = new DerOutputStream();
        DerOutputStream bagAttrValue3 = new DerOutputStream();
        for (ObjectIdentifier usage : trustedUsage) {
            bagAttrContent3.putOID(usage);
        }
        bagAttr3.write(DerValue.tag_Set, bagAttrContent3);
        bagAttrValue3.write(DerValue.tag_Sequence, bagAttr3);
        trustedKeyUsage = bagAttrValue3.toByteArray();
    }

    DerOutputStream attrs = new DerOutputStream();
    if (friendlyName != null) {
        attrs.write(friendlyName);
    }
    if (localKeyID != null) {
        attrs.write(localKeyID);
    }
    if (trustedKeyUsage != null) {
        attrs.write(trustedKeyUsage);
    }

    if (attributes != null) {
        for (KeyStore.Entry.Attribute attribute : attributes) {
            String attributeName = attribute.getName();
            // skip friendlyName, localKeyId and trustedKeyUsage
            if (CORE_ATTRIBUTES[0].equals(attributeName) ||
                CORE_ATTRIBUTES[1].equals(attributeName) ||
                CORE_ATTRIBUTES[2].equals(attributeName)) {
                continue;
            }
            attrs.write(((PKCS12Attribute) attribute).getEncoded());
        }
    }

    bagAttrs.write(DerValue.tag_Set, attrs);
    return bagAttrs.toByteArray();
}
 
Example 16
Source File: LocaleInTime.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    DerOutputStream out = new DerOutputStream();
    out.putUTCTime(new Date());
    DerValue val = new DerValue(out.toByteArray());
    System.out.println(val.getUTCTime());
}
 
Example 17
Source File: LocaleInTime.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    DerOutputStream out = new DerOutputStream();
    out.putUTCTime(new Date());
    DerValue val = new DerValue(out.toByteArray());
    System.out.println(val.getUTCTime());
}
 
Example 18
Source File: PKCS12KeyStore.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Stores this keystore to the given output stream, and protects its
 * integrity with the given password.
 *
 * @param stream the output stream to which this keystore is written.
 * @param password the password to generate the keystore integrity check
 *
 * @exception IOException if there was an I/O problem with data
 * @exception NoSuchAlgorithmException if the appropriate data integrity
 * algorithm could not be found
 * @exception CertificateException if any of the certificates included in
 * the keystore data could not be stored
 */
public synchronized void engineStore(OutputStream stream, char[] password)
    throws IOException, NoSuchAlgorithmException, CertificateException
{
    // password is mandatory when storing
    if (password == null) {
       throw new IllegalArgumentException("password can't be null");
    }

    // -- Create PFX
    DerOutputStream pfx = new DerOutputStream();

    // PFX version (always write the latest version)
    DerOutputStream version = new DerOutputStream();
    version.putInteger(VERSION_3);
    byte[] pfxVersion = version.toByteArray();
    pfx.write(pfxVersion);

    // -- Create AuthSafe
    DerOutputStream authSafe = new DerOutputStream();

    // -- Create ContentInfos
    DerOutputStream authSafeContentInfo = new DerOutputStream();

    // -- create safeContent Data ContentInfo
    if (privateKeyCount > 0 || secretKeyCount > 0) {

        if (debug != null) {
            debug.println("Storing " + (privateKeyCount + secretKeyCount) +
                " protected key(s) in a PKCS#7 data content-type");
        }

        byte[] safeContentData = createSafeContent();
        ContentInfo dataContentInfo = new ContentInfo(safeContentData);
        dataContentInfo.encode(authSafeContentInfo);
    }

    // -- create EncryptedContentInfo
    if (certificateCount > 0) {

        if (debug != null) {
            debug.println("Storing " + certificateCount +
                " certificate(s) in a PKCS#7 encryptedData content-type");
        }

        byte[] encrData = createEncryptedData(password);
        ContentInfo encrContentInfo =
            new ContentInfo(ContentInfo.ENCRYPTED_DATA_OID,
                            new DerValue(encrData));
        encrContentInfo.encode(authSafeContentInfo);
    }

    // wrap as SequenceOf ContentInfos
    DerOutputStream cInfo = new DerOutputStream();
    cInfo.write(DerValue.tag_SequenceOf, authSafeContentInfo);
    byte[] authenticatedSafe = cInfo.toByteArray();

    // Create Encapsulated ContentInfo
    ContentInfo contentInfo = new ContentInfo(authenticatedSafe);
    contentInfo.encode(authSafe);
    byte[] authSafeData = authSafe.toByteArray();
    pfx.write(authSafeData);

    // -- MAC
    byte[] macData = calculateMac(password, authenticatedSafe);
    pfx.write(macData);

    // write PFX to output stream
    DerOutputStream pfxout = new DerOutputStream();
    pfxout.write(DerValue.tag_Sequence, pfx);
    byte[] pfxData = pfxout.toByteArray();
    stream.write(pfxData);
    stream.flush();
}
 
Example 19
Source File: LocaleInTime.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
    DerOutputStream out = new DerOutputStream();
    out.putUTCTime(new Date());
    DerValue val = new DerValue(out.toByteArray());
    System.out.println(val.getUTCTime());
}
 
Example 20
Source File: KerberosTime.java    From hottub with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Encodes this object to a byte array.
 * @return a byte array of encoded data.
 * @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data.
 * @exception IOException if an I/O error occurs while reading encoded data.
 */
public byte[] asn1Encode() throws Asn1Exception, IOException {
    DerOutputStream out = new DerOutputStream();
    out.putGeneralizedTime(this.toDate());
    return out.toByteArray();
}