Example usage for org.bouncycastle.asn1 ASN1OutputStream ASN1OutputStream

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

Introduction

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

Prototype

public ASN1OutputStream(OutputStream os) 

Source Link

Usage

From source file:org.ccnx.ccn.impl.security.keystore.AESKeyStoreSpi.java

License:Open Source License

/**
 * Store the key from _id into a keystore file
 *//*from w w  w .  j  a va  2 s.  co  m*/
@Override
public void engineStore(OutputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException {
    if (null == _id)
        throw new IOException("Key not entered yet");
    ASN1OutputStream aos = new ASN1OutputStream(stream);
    Tuple<SecretKeySpec, SecretKeySpec> keys = initializeForAES(password);
    try {
        byte[] iv = new byte[IV_SIZE];
        _random.nextBytes(iv);
        byte[] aesCBC = null;
        Cipher cipher = Cipher.getInstance(AES_CRYPTO_ALGORITHM);
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, keys.first(), ivspec);
        aesCBC = cipher.doFinal(_id);
        _macKeyMac.init(keys.second());
        byte[] checkbuf = new byte[iv.length + aesCBC.length];
        System.arraycopy(iv, 0, checkbuf, 0, iv.length);
        System.arraycopy(aesCBC, 0, checkbuf, iv.length, aesCBC.length);
        byte[] part3 = _macKeyMac.doFinal(checkbuf);
        // TODO might be a better way to do this but am not sure how
        // (and its not really that important anyway)
        byte[] asn1buf = new byte[iv.length + aesCBC.length + part3.length];
        System.arraycopy(checkbuf, 0, asn1buf, 0, checkbuf.length);
        System.arraycopy(part3, 0, asn1buf, iv.length + aesCBC.length, part3.length);
        ASN1OctetString os = new DEROctetString(asn1buf);
        ASN1Encodable[] ae = new ASN1Encodable[3];
        ae[0] = _version;
        ae[1] = _oid;
        ae[2] = os;
        DERSequence ds = new DERSequence(ae);
        aos.writeObject(ds);
        aos.flush();
        aos.close();
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.ejbca.core.protocol.cmp.BaseCmpMessage.java

License:Open Source License

public void setRecipient(GeneralName recipient) {
    this.recipient = recipient;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ASN1OutputStream aos = new ASN1OutputStream(baos);
    try {/*from   w  ww  .j av a  2  s  .c  om*/
        aos.writeObject(recipient);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    recipientBytes = baos.toByteArray();
}

From source file:org.ejbca.core.protocol.cmp.BaseCmpMessage.java

License:Open Source License

public void setSender(GeneralName sender) {
    this.sender = sender;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ASN1OutputStream aos = new ASN1OutputStream(baos);
    try {//  www.  j a  v a2 s .com
        aos.writeObject(sender);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    senderBytes = baos.toByteArray();
}

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

License:Open Source License

protected static PKIMessage genCertReq(String issuerDN, X500Name userDN, String altNames, KeyPair keys,
        Certificate cacert, byte[] nonce, byte[] transid, boolean raVerifiedPopo, Extensions extensions,
        Date notBefore, Date notAfter, BigInteger customCertSerno, AlgorithmIdentifier pAlg,
        DEROctetString senderKID) throws NoSuchAlgorithmException, NoSuchProviderException, IOException,
        InvalidKeyException, SignatureException {
    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    if (notBefore != null) {
        nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    }// ww w  .j a  v a 2s  . c  o m
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    if (notAfter != null) {
        na = new org.bouncycastle.asn1.x509.Time(notAfter);
    }
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    if (issuerDN != null) {
        myCertTemplate.setIssuer(new X500Name(issuerDN));
    }
    myCertTemplate.setSubject(userDN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
    dIn.close();
    myCertTemplate.setPublicKey(keyInfo);
    // If we did not pass any extensions as parameter, we will create some of our own, standard ones
    Extensions exts = extensions;
    if (exts == null) {

        // SubjectAltName
        // Some altNames
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ASN1OutputStream dOut = new ASN1OutputStream(bOut);
        ExtensionsGenerator extgen = new ExtensionsGenerator();
        if (altNames != null) {
            GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames);
            dOut.writeObject(san);
            byte[] value = bOut.toByteArray();
            extgen.addExtension(Extension.subjectAlternativeName, false, value);
        }

        // KeyUsage
        int bcku = 0;
        bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation;
        KeyUsage ku = new KeyUsage(bcku);
        extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku));

        // Make the complete extension package
        exts = extgen.generate();
    }
    myCertTemplate.setExtensions(exts);
    if (customCertSerno != null) {
        // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order
        // to request a custom certificate serial number (something not standard anyway)
        myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno));
    }

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (raVerifiedPopo) {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg, "BC");
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);
        DERBitString bs = new DERBitString(sig.sign());
        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    }

    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String("foo123"));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(
            new X500Name(issuerDN != null ? issuerDN : ((X509Certificate) cacert).getSubjectDN().getName())));

    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(pAlg);
    myPKIHeader.setSenderKID(senderKID);

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization
                                                           // request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

From source file:org.ejbca.ui.cmpclient.commands.CrmfRequestCommand.java

License:Open Source License

@Override
public PKIMessage generatePKIMessage(final ParameterContainer parameters) throws Exception {

    final boolean verbose = parameters.containsKey(VERBOSE_KEY);

    final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY));
    final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY));

    String authmodule = parameters.get(AUTHENTICATION_MODULE_KEY);
    String endentityPassword = "";
    if (authmodule != null && StringUtils.equals(authmodule, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD)) {
        endentityPassword = parameters.containsKey(AUTHENTICATION_PARAM_KEY)
                ? parameters.get(AUTHENTICATION_PARAM_KEY)
                : "foo123";
    }/* ww  w.  j av  a2s . c om*/

    String altNames = parameters.get(ALTNAME_KEY);
    String serno = parameters.get(SERNO_KEY);
    BigInteger customCertSerno = null;
    if (serno != null) {
        customCertSerno = new BigInteger(serno, 16);
    }
    boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY);

    if (verbose) {
        log.info("Creating CRMF request with: SubjectDN=" + userDN.toString());
        log.info("Creating CRMF request with: IssuerDN=" + issuerDN.toString());
        log.info("Creating CRMF request with: AuthenticationModule=" + authmodule);
        log.info("Creating CRMF request with: EndEntityPassword=" + endentityPassword);
        log.info("Creating CRMF request with: SubjectAltName=" + altNames);
        log.info("Creating CRMF request with: CustomCertSerno="
                + (customCertSerno == null ? "" : customCertSerno.toString(16)));
        log.info("Creating CRMF request with: IncludePopo=" + includePopo);
    }

    final KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    final byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce();
    final byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce();

    // We should be able to back date the start time when allow validity
    // override is enabled in the certificate profile
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_WEEK, -1);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    // in validity
    Date notBefore = cal.getTime();
    cal.add(Calendar.DAY_OF_WEEK, 3);
    cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(notBefore);
    // in validity
    Date notAfter = cal.getTime();
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(notAfter);

    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    if (issuerDN != null) {
        myCertTemplate.setIssuer(issuerDN);
    }
    myCertTemplate.setSubject(userDN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
    dIn.close();
    myCertTemplate.setPublicKey(keyInfo);

    // Create standard extensions
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream dOut = new ASN1OutputStream(bOut);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    if (altNames != null) {
        GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames);
        dOut.writeObject(san);
        byte[] value = bOut.toByteArray();
        extgen.addExtension(Extension.subjectAlternativeName, false, value);
    }

    // KeyUsage
    int bcku = 0;
    bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation;
    KeyUsage ku = new KeyUsage(bcku);
    extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku));

    // Make the complete extension package
    Extensions exts = extgen.generate();

    myCertTemplate.setExtensions(exts);
    if (customCertSerno != null) {
        // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order
        // to request a custom certificate serial number (something not standard anyway)
        myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno));
    }

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    // POPO
    /*
     * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8,
     * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 }));
     * 
     * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new
     * byte[] { 44 }), 2); //take choice pos tag 2
     * 
     * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput(
     * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new
     * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2,
     * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 }));
     */
    ProofOfPossession myProofOfPossession = null;
    if (includePopo) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DEROutputStream mout = new DEROutputStream(baos);
        mout.writeObject(myCertRequest);
        mout.close();
        byte[] popoProtectionBytes = baos.toByteArray();
        String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm())
                .getId();
        Signature sig = Signature.getInstance(sigalg, "BC");
        sig.initSign(keys.getPrivate());
        sig.update(popoProtectionBytes);
        DERBitString bs = new DERBitString(sig.sign());
        POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null,
                new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs);
        myProofOfPossession = new ProofOfPossession(myPOPOSigningKey);
    } else {
        // raVerified POPO (meaning there is no POPO)
        myProofOfPossession = new ProofOfPossession();
    }

    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String(endentityPassword));
    AttributeTypeAndValue[] avs = { av };

    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN));

    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    myPKIHeader.setProtectionAlg(null);
    myPKIHeader.setSenderKID(new byte[0]);

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization
    // request
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);

    return myPKIMessage;
}

From source file:org.glite.voms.PKIUtils.java

License:Open Source License

/**
 * Checks if a certificate issued another certificate, according to RFC 3280.
 *
 * @param issuer The candidate issuer certificate.
 * @param issued The candidate issued certificate.
 *
 * @return true if <em>issuer</em> issued <em>issued</em>, false othersie.
 *///from   w w  w  .java2 s .  co  m
static public boolean checkIssued(X509Certificate issuer, X509Certificate issued) {
    X500Principal issuerSubject = issuer.getSubjectX500Principal();
    X500Principal issuedIssuer = issued.getIssuerX500Principal();

    if (logger.isDebugEnabled()) {
        logger.debug("Is: " + issued.getSubjectDN().getName() + " issued by " + issuer.getSubjectDN().getName()
                + "?");

        logger.debug("Is: " + issuedIssuer.getName() + " issued by " + issuerSubject.getName() + "?");
        logger.debug(
                "Is: " + issued.getSubjectDN().getName() + " issued by " + issuer.getSubjectDN().getName());
        logger.debug("[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[");
    }
    //        try {
    boolean b = issuerSubject.equals(issuedIssuer);
    //        }
    //        catch(Exception e) {
    //            System.out.println("Caught: " + e.getMessage() + " " + e.getClass());
    //        }

    if (issuerSubject.equals(issuedIssuer)) {
        logger.debug("================================");
        logger.debug("issuersSubject = issuedIssuer");

        AuthorityKeyIdentifier akid = PKIUtils.getAKID(issued);
        if (logger.isDebugEnabled())
            logger.debug("akid = " + akid);

        if (akid != null) {
            logger.debug("Authority Key Identifier extension found in issued certificate.");

            logger.debug("Entered.");
            SubjectKeyIdentifier skid = PKIUtils.getSKID(issuer);

            if (logger.isDebugEnabled())
                logger.debug("sid = " + skid);

            if (skid != null) {
                logger.debug("subject Key Identifier extensions found in issuer certificate.");
                logger.debug("comparing skid to akid");

                byte[] skidValue = skid.getKeyIdentifier();
                if (logger.isDebugEnabled()) {
                    logger.debug("skid");

                    String str = "";
                    for (int i = 0; i < skidValue.length; i++)
                        str += Integer.toHexString(skidValue[i]) + " ";
                    logger.debug(str);
                }

                byte[] akidValue = akid.getKeyIdentifier();
                if (logger.isDebugEnabled()) {
                    logger.debug("akid");

                    String str = "";
                    for (int i = 0; i < akidValue.length; i++)
                        str += Integer.toHexString(akidValue[i]) + " ";
                    logger.debug(str);
                }

                logger.debug("skid/akid checking.");
                if (!Arrays.equals(skidValue, akidValue))
                    return false;

                logger.debug("skid/akid check passed.");
            }

            if (false) {
                // The following should be skipped if the previous check passed.
                // And code cannot reach here unless the previous step passed.
                BigInteger sn = getAuthorityCertificateSerialNumber(akid);
                //
                //                if (sn == null) {
                //                    logger.error("Serial number missing from Authority Key Identifier");
                //                    return false;
                //                }
                //
                //                if (!sn.equals(issuer.getSerialNumber())) {
                //                    logger.error("Serial number in Authority Key Identifier and in issuer certificate do not match");
                //                    logger.error("From akid              : " + sn.toString());
                //                    logger.error("From issuer certificate: " + issuer.getSerialNumber());
                //                    return false;
                //                }

                if (sn != null && !sn.equals(issuer.getSerialNumber())) {
                    logger.error(
                            "Serial number in Authority Key Identifier and in issuer certificate do not match");
                    logger.error("From akid              : " + sn.toString());
                    logger.error("From issuer certificate: " + issuer.getSerialNumber());
                    return false;
                }

                GeneralNames gns = getAuthorityCertIssuer(akid);

                if (gns != null) {
                    GeneralName names[] = getNames(gns);

                    //                System.out.println("GOT CERTISSUER");

                    int i = 0;
                    //                System.out.println("SIZE = " + names.length);
                    while (i < names.length) {
                        //                    System.out.println("NAME = " + names[i].getName());
                        //                    System.out.println("TAG IS: " + names[i].getTagNo());
                        if (names[i].getTagNo() == 4) {
                            ASN1Primitive dobj = names[i].getName().toASN1Primitive();
                            ByteArrayOutputStream baos = null;
                            ASN1OutputStream aos = null;
                            //                        System.out.println("Inside tag 4");
                            try {
                                baos = new ByteArrayOutputStream();
                                aos = new ASN1OutputStream(baos);
                                aos.writeObject(dobj);
                                aos.flush();
                            } catch (IOException e) {
                                logger.error("Error in encoding of Authority Key Identifier." + e.getMessage());
                                return false;
                            }
                            X500Principal principal = new X500Principal(baos.toByteArray());
                            //                        System.out.println("PRINCIPAL: " + principal);
                            X500Principal issuerIssuer = issuer.getIssuerX500Principal();

                            if (issuerIssuer.equals(principal)) {
                                logger.debug("PASSED");
                                break;
                            } else {
                                logger.error(
                                        "Issuer Issuer not found among Authority Key Identifier's Certifiacte Issuers.");
                                return false;
                            }
                        }
                    }
                }
            }
        }
        logger.debug("]]]]]]]]]]]]]]]]]]]]]]]]");

        boolean keyUsage[] = issuer.getKeyUsage();
        if (!PKIUtils.isCA(issuer)) {
            if ((keyUsage != null && !keyUsage[digitalSignature]) || !PKIUtils.isProxy(issued))
                return false;
        }

        logger.debug("CHECK ISSUED PASSED");
        return true;

    }
    logger.debug("Check Issued failed.");
    return false;
}

From source file:org.jclouds.crypto.Pems.java

License:Apache License

static byte[] getEncoded(RSAPrivateCrtKey key) {
    RSAPrivateKeyStructure keyStruct = new RSAPrivateKeyStructure(key.getModulus(), key.getPublicExponent(),
            key.getPrivateExponent(), key.getPrimeP(), key.getPrimeQ(), key.getPrimeExponentP(),
            key.getPrimeExponentQ(), key.getCrtCoefficient());

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

    try {//from   ww  w.  j av a2s.c o m
        aOut.writeObject(keyStruct);
        aOut.close();
    } catch (IOException e) {
        Throwables.propagate(e);
    }

    return bOut.toByteArray();
}

From source file:org.jruby.ext.openssl.PKeyEC.java

License:Open Source License

@JRubyMethod(name = "dsa_sign_asn1")
public IRubyObject dsa_sign_asn1(final ThreadContext context, final IRubyObject data) {
    try {/*www  . j  a  v  a2  s.  c om*/
        ECNamedCurveParameterSpec params = ECNamedCurveTable.getParameterSpec(getCurveName());
        ASN1ObjectIdentifier oid = getCurveOID(getCurveName());
        ECNamedDomainParameters domainParams = new ECNamedDomainParameters(oid, params.getCurve(),
                params.getG(), params.getN(), params.getH(), params.getSeed());

        final ECDSASigner signer = new ECDSASigner();
        final ECPrivateKey privKey = (ECPrivateKey) this.privateKey;
        signer.init(true, new ECPrivateKeyParameters(privKey.getS(), domainParams));

        final byte[] message = data.convertToString().getBytes();
        BigInteger[] signature = signer.generateSignature(message); // [r, s]

        //            final byte[] r = signature[0].toByteArray();
        //            final byte[] s = signature[1].toByteArray();
        //            // ASN.1 encode as: 0x30 len 0x02 rlen (r) 0x02 slen (s)
        //            final int len = 1 + (1 + r.length) + 1 + (1 + s.length);
        //
        //            final byte[] encoded = new byte[1 + 1 + len]; int i;
        //            encoded[0] = 0x30;
        //            encoded[1] = (byte) len;
        //            encoded[2] = 0x20;
        //            encoded[3] = (byte) r.length;
        //            System.arraycopy(r, 0, encoded, i = 4, r.length); i += r.length;
        //            encoded[i++] = 0x20;
        //            encoded[i++] = (byte) s.length;
        //            System.arraycopy(s, 0, encoded, i, s.length);

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        ASN1OutputStream asn1 = new ASN1OutputStream(bytes);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1Integer(signature[0])); // r
        v.add(new ASN1Integer(signature[1])); // s

        asn1.writeObject(new DLSequence(v));

        return StringHelper.newString(context.runtime, bytes.buffer(), bytes.size());
    } catch (IOException ex) {
        throw newECError(context.runtime, ex.toString());
    } catch (RuntimeException ex) {
        throw newECError(context.runtime, ex.toString());
    }
}

From source file:org.jruby.ext.openssl.x509store.BouncyCastleASN1FormatHandler.java

License:LGPL

@Override
public void writeDSAPrivateKey(Writer _out, DSAPrivateKey obj, String algo, char[] f) throws IOException {
    BufferedWriter out = makeBuffered(_out);
    ByteArrayInputStream bIn = new ByteArrayInputStream(getEncoded(obj));
    ASN1InputStream aIn = new ASN1InputStream(bIn);
    PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) aIn.readObject());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

    DSAParameter p = DSAParameter.getInstance(info.getAlgorithmId().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 = obj.getX();/*w  ww.  j a v  a2  s . c o  m*/
    BigInteger y = p.getG().modPow(x, p.getP());

    v.add(new DERInteger(y));
    v.add(new DERInteger(x));

    aOut.writeObject(new DERSequence(v));
    byte[] encoding = bOut.toByteArray();

    if (algo != null && f != null) {
        byte[] salt = new byte[8];
        byte[] encData = null;
        random.nextBytes(salt);
        OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();
        pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(f), salt);
        SecretKey secretKey = null;
        if (algo.equalsIgnoreCase("DESede/CBC/PKCS5Padding")) {
            // generate key
            int keyLength = 24;
            KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(keyLength * 8);
            secretKey = new SecretKeySpec(param.getKey(), "DESede");
        } else {
            throw new IOException("unknown algorithm in write_DSAPrivateKey: " + algo);
        }

        // cipher  
        try {
            Cipher c = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            c.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(salt));
            encData = c.doFinal(encoding);
        } catch (Exception e) {
            throw new IOException("exception using cipher: " + e.toString());
        }

        // write the data
        out.write(BEF_G + PEM_STRING_DSA + AFT);
        out.newLine();
        out.write("Proc-Type: 4,ENCRYPTED");
        out.newLine();
        out.write("DEK-Info: DES-EDE3-CBC,");
        writeHexEncoded(out, salt);
        out.newLine();
        out.newLine();
        writeEncoded(out, encData);
        out.write(BEF_E + PEM_STRING_DSA + AFT);
        out.flush();
    } else {
        out.write(BEF_G + PEM_STRING_DSA + AFT);
        out.newLine();
        writeEncoded(out, encoding);
        out.write(BEF_E + PEM_STRING_DSA + AFT);
        out.newLine();
        out.flush();
    }
}

From source file:org.jruby.ext.openssl.x509store.BouncyCastleASN1FormatHandler.java

License:LGPL

@Override
public void writeRSAPrivateKey(Writer _out, RSAPrivateCrtKey obj, String algo, char[] f) throws IOException {
    assert (obj != null);
    BufferedWriter out = makeBuffered(_out);
    RSAPrivateKeyStructure keyStruct = new RSAPrivateKeyStructure(obj.getModulus(), obj.getPublicExponent(),
            obj.getPrivateExponent(), obj.getPrimeP(), obj.getPrimeQ(), obj.getPrimeExponentP(),
            obj.getPrimeExponentQ(), obj.getCrtCoefficient());

    // convert to bytearray
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

    aOut.writeObject(keyStruct);/*from   w  w w  .j a  v a2s  .  c  om*/
    aOut.close();

    byte[] encoding = bOut.toByteArray();

    if (algo != null && f != null) {
        byte[] salt = new byte[8];
        byte[] encData = null;
        random.nextBytes(salt);
        OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();
        pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(f), salt);
        SecretKey secretKey = null;

        if (algo.startsWith("DES")) {
            // generate key
            int keyLength = 24;
            if (algo.equalsIgnoreCase("DESEDE")) {
                algo = "DESede/CBC/PKCS5Padding";
            }
            KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(keyLength * 8);
            secretKey = new SecretKeySpec(param.getKey(), algo.split("/")[0]);
        } else {
            throw new IOException("unknown algorithm `" + algo + "' in write_DSAPrivateKey");
        }

        // cipher  
        try {
            Cipher c = Cipher.getInstance(algo);
            c.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(salt));
            encData = c.doFinal(encoding);
        } catch (Exception e) {
            throw new IOException("exception using cipher: " + e.toString());
        }

        // write the data
        out.write(BEF_G + PEM_STRING_RSA + AFT);
        out.newLine();
        out.write("Proc-Type: 4,ENCRYPTED");
        out.newLine();
        out.write("DEK-Info: DES-EDE3-CBC,");
        writeHexEncoded(out, salt);
        out.newLine();
        out.newLine();
        writeEncoded(out, encData);
        out.write(BEF_E + PEM_STRING_RSA + AFT);
        out.flush();
    } else {
        out.write(BEF_G + PEM_STRING_RSA + AFT);
        out.newLine();
        writeEncoded(out, encoding);
        out.write(BEF_E + PEM_STRING_RSA + AFT);
        out.newLine();
        out.flush();
    }
}