SecretKeyFactory
(私密密钥工厂)用对密钥(SecretKey类型的不透明密钥)和密钥规范(KeySpec类型的底层密钥密钥材料的透明表示)进行相互转换;也就是私密密钥工厂是双向的,可以把Key转换成KeySpec,也可以把KeySpec转换成SecretKey。另外对于同一个密钥可以存在多个兼容的密钥规范。
SecretKeyFactory
和 KeyFactory
的不同在于:KeyFactory用于非对称密钥加密时的密钥转换,而 SecretKeyFactory 用于对称密钥加密时的密钥转换。
实例化
SecretKeyFactory
没有公开的构造方法,只能使用 getInstance
方法进行实例化。这个方法有多个重载如下:
public static final SecretKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException
public static final SecretKeyFactory getInstance(String algorithm, Provider provider )
throws NoSuchAlgorithmException
public static final SecretKeyFactory getInstance(String algorithm, String provider )
throws NoSuchAlgorithmException, NoSuchProviderException
我们通常使用的是public static final SecretKeyFactory getInstance(String algorithm);此方法需要一个字符串作为参数,用于说明使用哪个密钥算法。
可用方法
SecretKeyFactory 用于密码转换的方法如下:
public final SecretKey generateSecret(KeySpec keySpec ) throws InvalidKeySpecException
public final KeySpec getKeySpec(SecretKey key, Class<?> clazz) throws InvalidKeySpecException
public final SecretKey translateKey(SecretKey key) throws InvalidKeyException
1.generateSecret
方法可根据给定的KeySpec对象,生成SecretKey(对称加密中的密钥)对象。
2.getKeySpec
方法中,参数中给定的SecretKey是待转换的密钥,而Class是需要转换成的目标KeySpec类。
此方法就是要把给定的SecretKey对象转换成目标KeySpec类对象。
3.translateKey
方法将参数中指定的SecretKey(密钥对象)转换为此密钥工厂所支持算法的SecretKey(密钥对象)。
支持的算法:
DES
DESede
PBE
PBEWithMD5AndDES
PBEWithMD5AndTripleDES
PBEWithSHA1AndDESede
PBEWithSHA1AndRC2_40
PBEWithSHA1AndRC2_128
PBEWithSHA1AndRC4_40
PBEWithSHA1AndRC4_128
PBEWithHmacSHA1AndAES_128
PBEWithHmacSHA224AndAES_128
PBEWithHmacSHA256AndAES_128
PBEWithHmacSHA384AndAES_128
PBEWithHmacSHA512AndAES_128
PBEWithHmacSHA1AndAES_256
PBEWithHmacSHA224AndAES_256
PBEWithHmacSHA256AndAES_256
PBEWithHmacSHA384AndAES_256
PBEWithHmacSHA512AndAES_256
PBKDF2WithHmacSHA1
PBKDF2WithHmacSHA224
PBKDF2WithHmacSHA256
PBKDF2WithHmacSHA384
PBKDF2WithHmacSHA512