PrivateKey key = (PrivateKey) ks.getKey(alias, password);
Certificate[] chain = ks.getCertificateChain(alias);
byte[] pkcs8DerBytes = null;
if (key instanceof RSAPrivateCrtKey) {
RSAPrivateCrtKey rsa = (RSAPrivateCrtKey) key;
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(new DERInteger(BigInteger.ZERO));
vec.add(new DERInteger(rsa.getModulus()));
vec.add(new DERInteger(rsa.getPublicExponent()));
vec.add(new DERInteger(rsa.getPrivateExponent()));
vec.add(new DERInteger(rsa.getPrimeP()));
vec.add(new DERInteger(rsa.getPrimeQ()));
vec.add(new DERInteger(rsa.getPrimeExponentP()));
vec.add(new DERInteger(rsa.getPrimeExponentQ()));
vec.add(new DERInteger(rsa.getCrtCoefficient()));
DERSequence seq = new DERSequence(vec);
byte[] derBytes = PKCS8Key.encode(seq);
PKCS8Key pkcs8 = new PKCS8Key(derBytes, null);
pkcs8DerBytes = pkcs8.getDecryptedBytes();
} else if (key instanceof DSAPrivateKey) {
DSAPrivateKey dsa = (DSAPrivateKey) key;
DSAParams params = dsa.getParams();
BigInteger g = params.getG();
BigInteger p = params.getP();
BigInteger q = params.getQ();
BigInteger x = dsa.getX();
BigInteger y = q.modPow(x, p);
ASN1EncodableVector vec = new ASN1EncodableVector();
vec.add(new DERInteger(BigInteger.ZERO));
vec.add(new DERInteger(p));
vec.add(new DERInteger(q));
vec.add(new DERInteger(g));
vec.add(new DERInteger(y));
vec.add(new DERInteger(x));
DERSequence seq = new DERSequence(vec);
byte[] derBytes = PKCS8Key.encode(seq);
PKCS8Key pkcs8 = new PKCS8Key(derBytes, null);
pkcs8DerBytes = pkcs8.getDecryptedBytes();
}