Search in sources :

Example 1 with ByteArrayOutputStream

use of org.jruby.ext.openssl.util.ByteArrayOutputStream in project jruby-openssl by jruby.

the class PEMUtils method generatePKCS12.

public static byte[] generatePKCS12(final Reader keyReader, final byte[] cert, final String aliasName, final char[] password) throws IOException, GeneralSecurityException {
    final Collection<? extends Certificate> certChain = SecurityHelper.getCertificateFactory("X.509").generateCertificates(new ByteArrayInputStream(cert));
    final PEMKeyPair pemKeyPair = readInternal(keyReader, null);
    final KeyFactory keyFactory = getKeyFactory(pemKeyPair.getPrivateKeyInfo().getPrivateKeyAlgorithm());
    Key privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(pemKeyPair.getPrivateKeyInfo().getEncoded()));
    final KeyStore keyStore = SecurityHelper.getKeyStore("PKCS12");
    keyStore.load(null, null);
    keyStore.setKeyEntry(aliasName, privateKey, null, certChain.toArray(new Certificate[certChain.size()]));
    final ByteArrayOutputStream pkcs12Out = new ByteArrayOutputStream();
    keyStore.store(pkcs12Out, password == null ? new char[0] : password);
    return pkcs12Out.toByteArray();
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) PEMKeyPair(org.jruby.ext.openssl.impl.pem.PEMKeyPair) ByteArrayOutputStream(org.jruby.ext.openssl.util.ByteArrayOutputStream) KeyStore(java.security.KeyStore) KeyFactory(java.security.KeyFactory) PEMInputOutput.getKeyFactory(org.jruby.ext.openssl.x509store.PEMInputOutput.getKeyFactory) Key(java.security.Key) SecretKey(javax.crypto.SecretKey) Certificate(java.security.cert.Certificate)

Example 2 with ByteArrayOutputStream

use of org.jruby.ext.openssl.util.ByteArrayOutputStream in project jruby-openssl by jruby.

the class PKeyEC method dsa_sign_asn1.

@JRubyMethod(name = "dsa_sign_asn1")
public IRubyObject dsa_sign_asn1(final ThreadContext context, final IRubyObject data) {
    try {
        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();
        // [r, s]
        BigInteger[] signature = signer.generateSignature(message);
        // 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();
        // r
        v.add(new ASN1Integer(signature[0]));
        // s
        v.add(new ASN1Integer(signature[1]));
        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());
    }
}
Also used : PKey.readECPrivateKey(org.jruby.ext.openssl.impl.PKey.readECPrivateKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) ECDSASigner(org.bouncycastle.crypto.signers.ECDSASigner) ECNamedDomainParameters(org.bouncycastle.crypto.params.ECNamedDomainParameters) ByteArrayOutputStream(org.jruby.ext.openssl.util.ByteArrayOutputStream) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IOException(java.io.IOException) ASN1OutputStream(org.bouncycastle.asn1.ASN1OutputStream) ECPrivateKeyParameters(org.bouncycastle.crypto.params.ECPrivateKeyParameters) DLSequence(org.bouncycastle.asn1.DLSequence) ECNamedCurveParameterSpec(org.bouncycastle.jce.spec.ECNamedCurveParameterSpec) BigInteger(java.math.BigInteger) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) JRubyMethod(org.jruby.anno.JRubyMethod)

Example 3 with ByteArrayOutputStream

use of org.jruby.ext.openssl.util.ByteArrayOutputStream in project jruby-openssl by jruby.

the class Base64 method encodeObject.

// end encodeObject
/**
 * Serializes an object and returns the Base64-encoded
 * version of that serialized object.
 *
 * <p>As of v 2.3, if the object
 * cannot be serialized or there is another error,
 * the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
 * In earlier versions, it just returned a null value, but
 * in retrospect that's a pretty poor way to handle it.</p>
 *
 * The object is not GZip-compressed before being encoded.
 * <p>
 * Example options:<pre>
 *   GZIP: gzip-compresses object before encoding it.
 *   DO_BREAK_LINES: break lines at 76 characters
 * </pre>
 * <p>
 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
 * <p>
 * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
 *
 * @param serializableObject The object to encode
 * @param options Specified options
 * @return The Base64-encoded object
 * @see Base64#GZIP
 * @see Base64#DO_BREAK_LINES
 * @throws java.io.IOException if there is an error
 * @since 2.0
 */
public static String encodeObject(java.io.Serializable serializableObject, int options) throws java.io.IOException {
    if (serializableObject == null) {
        throw new NullPointerException("Cannot serialize a null object.");
    }
    // end if: null
    // Streams
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    java.io.OutputStream b64os = null;
    java.util.zip.GZIPOutputStream gzos = null;
    java.io.ObjectOutputStream oos = null;
    try {
        // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
        b64os = new Base64.OutputStream(baos, ENCODE | options);
        if ((options & GZIP) != 0) {
            // Gzip
            gzos = new java.util.zip.GZIPOutputStream(b64os);
            oos = new java.io.ObjectOutputStream(gzos);
        } else {
            // Not gzipped
            oos = new java.io.ObjectOutputStream(b64os);
        }
        oos.writeObject(serializableObject);
    }// end try
     catch (java.io.IOException e) {
        // the finally{} block is called for cleanup.
        throw e;
    } finally // end catch
    {
        try {
            oos.close();
        } catch (Exception e) {
        }
        try {
            gzos.close();
        } catch (Exception e) {
        }
        try {
            b64os.close();
        } catch (Exception e) {
        }
    // try{ baos.close();  } catch( Exception e ){}
    }
    // Return value according to relevant encoding.
    try {
        return new String(baos.buffer(), 0, baos.size(), PREFERRED_ENCODING);
    }// end try
     catch (java.io.UnsupportedEncodingException uue) {
        // Fall back to some Java default
        return new String(baos.buffer(), 0, baos.size());
    }
// end catch
}
Also used : ByteArrayOutputStream(org.jruby.ext.openssl.util.ByteArrayOutputStream)

Example 4 with ByteArrayOutputStream

use of org.jruby.ext.openssl.util.ByteArrayOutputStream in project jruby-openssl by jruby.

the class Base64 method encodeBytesToBytes.

/**
 * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns
 * a byte array instead of instantiating a String. This is more efficient
 * if you're working with I/O streams and have large data sets to encode.
 *
 * @param source The data to convert
 * @param off Offset in array where conversion should begin
 * @param len Length of data to convert
 * @param options Specified options
 * @return The Base64-encoded data as a String
 * @see Base64#GZIP
 * @see Base64#DO_BREAK_LINES
 * @throws java.io.IOException if there is an error
 * @throws NullPointerException if source array is null
 * @throws IllegalArgumentException if source array, offset, or length are invalid
 * @since 2.3.1
 */
public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int options) throws java.io.IOException {
    if (source == null) {
        throw new NullPointerException("Cannot serialize a null array.");
    }
    if (off < 0) {
        throw new IllegalArgumentException("Cannot have negative offset: " + off);
    }
    if (len < 0) {
        throw new IllegalArgumentException("Cannot have length offset: " + len);
    }
    if (off + len > source.length) {
        throw new IllegalArgumentException(String.format("Cannot have offset of %d and length of %d with array of length %d", off, len, source.length));
    }
    // Compress?
    if ((options & GZIP) != 0) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        java.util.zip.GZIPOutputStream gzos = null;
        Base64.OutputStream b64os = null;
        try {
            // GZip -> Base64 -> ByteArray
            b64os = new Base64.OutputStream(baos, ENCODE | options);
            gzos = new java.util.zip.GZIPOutputStream(b64os);
            gzos.write(source, off, len);
            gzos.close();
        }// end try
         catch (java.io.IOException e) {
            // the finally{} block is called for cleanup.
            throw e;
        } finally // end catch
        {
            try {
                gzos.close();
            } catch (Exception e) {
            }
            try {
                b64os.close();
            } catch (Exception e) {
            }
        // try{ baos.close();  } catch( Exception e ){}
        }
        return baos.toByteArray();
    } else // end if: compress
    // Else, don't compress. Better not to use streams at all then.
    {
        boolean breakLines = (options & DO_BREAK_LINES) != 0;
        // int    len43   = len * 4 / 3;
        // byte[] outBuff = new byte[   ( len43 )                      // Main 4:3
        // + ( (len % 3) > 0 ? 4 : 0 )      // Account for padding
        // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
        // Try to determine more precisely how big the array needs to be.
        // If we get it right, we don't have to do an array copy, and
        // we save a bunch of memory.
        // Bytes needed for actual encoding
        int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0);
        if (breakLines) {
            // Plus extra newline characters
            encLen += encLen / MAX_LINE_LENGTH;
        }
        byte[] outBuff = new byte[encLen];
        int d = 0;
        int e = 0;
        int len2 = len - 2;
        int lineLength = 0;
        for (; d < len2; d += 3, e += 4) {
            encode3to4(source, d + off, 3, outBuff, e, options);
            lineLength += 4;
            if (breakLines && lineLength >= MAX_LINE_LENGTH) {
                outBuff[e + 4] = NEW_LINE;
                e++;
                lineLength = 0;
            }
        // end if: end of line
        }
        if (d < len) {
            encode3to4(source, d + off, len - d, outBuff, e, options);
            e += 4;
        }
        // Only resize array if we didn't guess it right.
        if (e <= outBuff.length - 1) {
            // If breaking lines and the last byte falls right at
            // the line length (76 bytes per line), there will be
            // one extra byte, and the array will need to be resized.
            // Not too bad of an estimate on array size, I'd say.
            byte[] finalOut = new byte[e];
            System.arraycopy(outBuff, 0, finalOut, 0, e);
            // System.err.println("Having to resize array from " + outBuff.length + " to " + e );
            return finalOut;
        } else {
            // System.err.println("No need to resize array.");
            return outBuff;
        }
    }
// end else: don't compress
}
Also used : ByteArrayOutputStream(org.jruby.ext.openssl.util.ByteArrayOutputStream)

Example 5 with ByteArrayOutputStream

use of org.jruby.ext.openssl.util.ByteArrayOutputStream in project jruby-openssl by jruby.

the class PEMInputOutput method readPKCS7.

/**
 * Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
 * API.
 *
 * @return the X509Certificate
 * @throws IOException if an I/O error occured
 */
private static CMSSignedData readPKCS7(BufferedReader in, char[] p, String endMarker) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    String line;
    StringBuilder buffer = new StringBuilder();
    while ((line = in.readLine()) != null) {
        if (line.contains(endMarker))
            break;
        buffer.append(line.trim());
        final int len = buffer.length();
        Base64.decode(buffer.substring(0, (len / 4) * 4), bytes);
        buffer.delete(0, (len / 4) * 4);
    }
    if (buffer.length() != 0) {
        throw new IOException("base64 data appears to be truncated");
    }
    if (line == null)
        throw new IOException(endMarker + " not found");
    try {
        ASN1InputStream aIn = new ASN1InputStream(bytes.toByteArray());
        return new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
    } catch (CMSException e) {
        throw new IOException("problem parsing PKCS7 object: " + e, e);
    }
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ByteArrayOutputStream(org.jruby.ext.openssl.util.ByteArrayOutputStream) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DEROctetString(org.bouncycastle.asn1.DEROctetString) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

ByteArrayOutputStream (org.jruby.ext.openssl.util.ByteArrayOutputStream)8 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)4 DLSequence (org.bouncycastle.asn1.DLSequence)4 BufferedWriter (java.io.BufferedWriter)3 IOException (java.io.IOException)3 BigInteger (java.math.BigInteger)3 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)3 ASN1OutputStream (org.bouncycastle.asn1.ASN1OutputStream)3 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)2 DEROctetString (org.bouncycastle.asn1.DEROctetString)2 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 Key (java.security.Key)1 KeyFactory (java.security.KeyFactory)1 KeyStore (java.security.KeyStore)1 Certificate (java.security.cert.Certificate)1 CertificateEncodingException (java.security.cert.CertificateEncodingException)1 ECPrivateKey (java.security.interfaces.ECPrivateKey)1