public static void writeRSAPrivateKey(
      Writer _out, RSAPrivateCrtKey obj, CipherSpec cipher, char[] passwd) 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());

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);
    aOut.writeObject(keyStruct);
    aOut.close();
    byte[] encoding = bOut.toByteArray();

    if (cipher != null && passwd != null) {
      writePemEncrypted(out, PEM_STRING_RSA, encoding, cipher, passwd);
    } else {
      writePemPlain(out, PEM_STRING_RSA, encoding);
    }
  }
  public static void writeDSAPrivateKey(
      Writer _out, DSAPrivateKey obj, CipherSpec cipher, char[] passwd) throws IOException {
    BufferedWriter out = makeBuffered(_out);
    PrivateKeyInfo info =
        new PrivateKeyInfo((ASN1Sequence) new ASN1InputStream(getEncoded(obj)).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();
    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 (cipher != null && passwd != null) {
      writePemEncrypted(out, PEM_STRING_DSA, encoding, cipher, passwd);
    } else {
      writePemPlain(out, PEM_STRING_DSA, encoding);
    }
  }