{
PemReader reader = new PemReader(rdr);
PemObject pemObj = reader.readPemObject();
if (pemObj == null) {
throw new CryptoException("Not a valid PEM file");
}
if (!DSA_TYPE.equals(pemObj.getType())) {
throw new CryptoException("PEM file does not contain a DSA private key");
}
ASN1InputStream asnIn = new ASN1InputStream(pemObj.getContent());
ASN1Primitive ao = asnIn.readObject();
if (ao == null) {
throw new CryptoException("PEM file does not contain an ASN.1 object");
}
if (!(ao instanceof ASN1Sequence)) {
throw new CryptoException("PEM file does not contain a sequence");
}
ASN1Sequence seq = (ASN1Sequence)ao;
if (seq.size() != 6) {
throw new CryptoException("ASN.1 sequence is the wrong length for a DSA key");
}
DERInteger p = (DERInteger)seq.getObjectAt(1);
DERInteger q = (DERInteger)seq.getObjectAt(2);
DERInteger g = (DERInteger)seq.getObjectAt(3);
DERInteger y = (DERInteger)seq.getObjectAt(4);
DERInteger x = (DERInteger)seq.getObjectAt(5);
try {
KeyFactory factory = KeyFactory.getInstance("DSA");
DSAPublicKeySpec pubSpec = new DSAPublicKeySpec(
y.getValue(),
p.getValue(),
q.getValue(),
g.getValue());
PublicKey pub = factory.generatePublic(pubSpec);
DSAPrivateKeySpec keySpec = new DSAPrivateKeySpec(
x.getValue(),
p.getValue(),
q.getValue(),
g.getValue());
PrivateKey key = factory.generatePrivate(keySpec);
return new KeyPair(pub, key);
} catch (GeneralSecurityException gse) {
throw new CryptoException(gse);
}
}