# Generating or Verifying Signatures Using Key Specifications
and `KeyFactory`

Suppose that, rather than having a public-private key pair (as,
for example, was generated in the key
pair example), you simply have the components of your DSA private
key: `x`

(the private key), `p`

(the
prime), `q`

(the sub-prime), and `g`

(the
base).

`someData`

.
You would do the following steps, which also illustrate creating a
key specification and using a key factory to obtain a `PrivateKey`

from
the key specification (`initSign`

requires a `PrivateKey`

): ```
DSAPrivateKeySpec dsaPrivKeySpec = new DSAPrivateKeySpec(x, p, q, g);
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PrivateKey privKey = keyFactory.generatePrivate(dsaPrivKeySpec);
Signature sig = Signature.getInstance("SHA1withDSA");
sig.initSign(privKey);
sig.update(someData);
byte[] signature = sig.sign();
```

- the data,
- the signature, and
- the public key corresponding to the private key you used to sign the data.

You can store the `someData`

bytes in one file,
and the `signature`

bytes in another, and send those
to Alice.

`DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec(y, p, q, g);`

`generatePublic`

method
on the DSA key factory already created in the last example: `PublicKey pubKey = keyFactory.generatePublic(dsaPubKeySpec);`

`byte[] encKey = pubKey.getEncoded();`

You can now store these bytes in a file, and send it to Alice along with the files that contain the data and the signature.

Now, assume Alice has received these files, and that she copied
the data bytes from the data file to a byte array named `data`

,
the signature bytes from the signature file to a byte array named `signature`

,
and the encoded public key bytes from the public key file to a byte
array named `encodedPubKey`

.

`initVerify`

requires
a `PublicKey`

). ```
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encodedPubKey);
KeyFactory keyFactory = KeyFactory.getInstance("DSA");
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
Signature sig = Signature.getInstance("SHA1withDSA");
sig.initVerify(pubKey);
sig.update(data);
sig.verify(signature);
```

`PublicKey`

from the
encoded key bits, because `initVerify`

requires a `PublicKey`

. After
she has a `PublicKey`

, she could also use the `KeyFactory`

`getKeySpec`

method to convert it to a `DSAPublicKeySpec`

so that she
can access the components, if desired, as in:
```
DSAPublicKeySpec dsaPubKeySpec =
(DSAPublicKeySpec)keyFactory.getKeySpec(pubKey, DSAPublicKeySpec.class)
```

Now she can access the DSA public key components `y`

, `p`

,
`q`

, and `g`

through the corresponding get methods
on the `DSAPublicKeySpec`

class (`getY`

, `getP`

,
`getQ`

, and `getG`

).