The KeyFactory
Class
The KeyFactory
class is an engine class designed
to provide conversions between opaque cryptographic keys (of type Key
) and key specifications (transparent representations
of the underlying key material).
Key factories are bidirectional. They allow you to build an opaque key object from a given key specification (key material), or to retrieve the underlying key material of a key object in a suitable format.
Multiple compatible key specifications can exist for the same key.
For example, a DSA public key can be specified by its components y
, p
, q
,
and g
(see DSAPublicKeySpec
),
or it can be specified using its DER encoding according to the X.509
standard (see X509EncodedKeySpec
).
A key factory can be used to translate between compatible key specifications.
Key parsing can be achieved through translation between compatible
key specifications, for example, when you translate from X509EncodedKeySpec
to DSAPublicKeySpec
,
you basically parse the encoded key into its components. For an example,
see the end of the Generating/Verifying
Signatures Using Key Specifications and KeyFactory
section.
- Creating a
KeyFactory
Object - As with all engine classes, the way to get a
KeyFactory
object for a particular type of key algorithm is to call thegetInstance
static factory method on theKeyFactory
class:static KeyFactory getInstance(String algorithm)
Note: The algorithm name is not case-sensitive.A caller can optionally specify the name of a provider or theProvider
class, which will guarantee that the implementation of the key factory requested is from the named provider.static KeyFactory getInstance(String algorithm, String provider) static KeyFactory getInstance(String algorithm, Provider provider)
- Converting between a Key Specification and a Key Object
- If you have a key specification for a public key, you can obtain an opaque
PublicKey
object from the specification by using thegeneratePublic
method:PublicKey generatePublic(KeySpec keySpec)
Similarly, if you have a key specification for a private key, you can obtain an opaquePrivateKey
object from the specification by using thegeneratePrivate
method:PrivateKey generatePrivate(KeySpec keySpec)
- Converting between a Key Object and a Key Specification
- If you have a
Key
object, you can get a corresponding key specification object by calling thegetKeySpec
method:KeySpec getKeySpec(Key key, Class keySpec)
keySpec
identifies the specification class in which the key material should be returned. It could, for example, beDSAPublicKeySpec.class
, to indicate that the key material should be returned in an instance of theDSAPublicKeySpec
class.See the Examples section for more details.