下面列出了怎么用javax.crypto.SecretKeyFactory的API类实例代码及写法,或者点击链接到github查看源代码。
protected Cipher getCipher(byte[] key, byte[] ivec, int mode)
throws GeneralSecurityException {
// NoSuchAlgorithException
SecretKeyFactory factory = SecretKeyFactory.getInstance("desede");
// InvalidKeyException
KeySpec spec = new DESedeKeySpec(key, 0);
// InvalidKeySpecException
SecretKey secretKey = factory.generateSecret(spec);
// IV
if (ivec == null) {
ivec = ZERO_IV;
}
// NoSuchAlgorithmException, NoSuchPaddingException
// NoSuchProviderException
Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);
// InvalidKeyException, InvalidAlgorithParameterException
cipher.init(mode, secretKey, encIv);
return cipher;
}
/**
* The key is generating by SecretKeyFactory and its value just copying in
* the key field of MySecretKey class. So, this is real key derived using
* the given algorithm.
*
* @param passPhrase some string intended to be a password
* @param algo PBKDF2 algorithm
* @param salt slat for PBKDF2
* @param iterationCount iteration count
* @param keySize key size in bits
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt,
int iterationCount, int keySize)
throws InvalidKeySpecException, NoSuchAlgorithmException {
this.algorithm = algo;
this.salt = salt;
this.itereationCount = iterationCount;
this.keySize = keySize;
this.pass = passPhrase;
PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(),
this.salt, iterationCount, this.keySize);
SecretKeyFactory keyFactory
= SecretKeyFactory.getInstance(algo);
SecretKey realKey = keyFactory.generateSecret(spec);
this.keyLength = realKey.getEncoded().length;
this.key = new byte[this.keyLength];
System.arraycopy(realKey.getEncoded(), 0, this.key, 0,
this.keyLength);
}
/**
* Generate secret key.
*
* @return the key
* @throws IntegrationModuleException the integration module exception
*/
public Key generateSecretKey() throws IntegrationModuleException {
try {
if (propertyHandler.hasProperty(SYMM_KEY_PROPERTY)) {
String base64key = propertyHandler.getProperty(SYMM_KEY_PROPERTY);
DESedeKeySpec keyspec = new DESedeKeySpec(Base64.decode(base64key));
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
return keyfactory.generateSecret(keyspec);
}
KeyGenerator keyGen = KeyGenerator.getInstance("DESede");
return keyGen.generateKey();
} catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException e) {
throw new IntegrationModuleException(e);
}
}
private byte[] encryptPassword(VncAuthSecurityMessage msg) throws ProtocolException {
if (msg.getChallenge().length != 16)
throw new ProtocolException("invalid challenge length " + msg.getChallenge().length);
try {
byte[] keyBytes = new byte[DESKeySpec.DES_KEY_LEN];
byte[] pwdBytes = String.valueOf(msg.getPassword()).getBytes(StandardCharsets.US_ASCII);
for (int i = 0; i < keyBytes.length; i++) {
keyBytes[i] = i < pwdBytes.length ? reverseBitsByte(pwdBytes[i]) : 0;
}
KeySpec desKeySpec = new DESKeySpec(keyBytes);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(msg.getChallenge());
} catch (Exception e) {
throw new ProtocolException("encrypt password failed", e);
}
}
/**
* Encode password using DES encryption with given challenge.
*
* @param challenge a random set of bytes.
* @param password a password
* @return DES hash of password and challenge
*/
public byte[] encodePassword(final byte[] challenge, final String password) throws Exception {
// VNC password consist of up to eight ASCII characters.
final byte[] key = {0, 0, 0, 0, 0, 0, 0, 0}; // Padding
final byte[] passwordAsciiBytes = password.getBytes(RfbConstants.CHARSET);
System.arraycopy(passwordAsciiBytes, 0, key, 0, Math.min(password.length(), 8));
// Flip bytes (reverse bits) in key
for (int i = 0; i < key.length; i++) {
key[i] = flipByte(key[i]);
}
final KeySpec desKeySpec = new DESKeySpec(key);
final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
final SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);
final Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
final byte[] response = cipher.doFinal(challenge);
return response;
}
private byte[] calculatePbeMac(
ASN1ObjectIdentifier oid,
byte[] salt,
int itCount,
char[] password,
boolean wrongPkcs12Zero,
byte[] data)
throws Exception
{
SecretKeyFactory keyFact = helper.createSecretKeyFactory(oid.getId());
PBEParameterSpec defParams = new PBEParameterSpec(salt, itCount);
PBEKeySpec pbeSpec = new PBEKeySpec(password);
BCPBEKey key = (BCPBEKey)keyFact.generateSecret(pbeSpec);
key.setTryWrongPKCS12Zero(wrongPkcs12Zero);
Mac mac = helper.createMac(oid.getId());
mac.init(key, defParams);
mac.update(data);
return mac.doFinal();
}
protected Cipher getCipher(byte[] key, byte[] ivec, int mode)
throws GeneralSecurityException {
// NoSuchAlgorithException
SecretKeyFactory factory = SecretKeyFactory.getInstance("desede");
// InvalidKeyException
KeySpec spec = new DESedeKeySpec(key, 0);
// InvalidKeySpecException
SecretKey secretKey = factory.generateSecret(spec);
// IV
if (ivec == null) {
ivec = ZERO_IV;
}
// NoSuchAlgorithmException, NoSuchPaddingException
// NoSuchProviderException
Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);
// InvalidKeyException, InvalidAlgorithParameterException
cipher.init(mode, secretKey, encIv);
return cipher;
}
/**
*
* @param plainText 普通文本
* @param secretKey 密钥
* @param iv 向量
* @return 加密后的文本,失败返回null
*/
public static String encode(String plainText, String secretKey, String iv) {
String result = null;
try {
DESedeKeySpec deSedeKeySpec = new DESedeKeySpec(secretKey.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("desede");
Key desKey = secretKeyFactory.generateSecret(deSedeKeySpec);
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, desKey, ips);
byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
result = Base64Utils.encodeToString(encryptData);
} catch (Exception e) {
log.error("DesCbcUtil encode error : {}", e);
}
return result;
}
/**
* DES算法,加密
* @param data 待加密字符串
* @param key 加密私钥,长度不能够小于8位
* @return 加密后的字节数组,一般结合Base64编码使用
* @throws Exception
*/
public static String encode(String key, String data) {
if (data == null)
return null;
try {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// key的长度不能够小于8位字节
Key secretKey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
AlgorithmParameterSpec paramSpec = iv;
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] bytes = cipher.doFinal(data.getBytes());
return byte2String(bytes);
} catch (Exception e) {
e.printStackTrace();
return data;
}
}
/**
* Description 根据键值进行加密
*/
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
/**
* DES����
*
* @param HexString
* �ַ�����16λ16�����ַ�����
* @param keyStr
* ��Կ16��1
* @param keyENCODED
* Keybyteת������
* @param HexStringENCODED
* Ҫ����ֵ��ת��byte����
* @param CipherInstanceType
* ��Ҫ��������
* @return
* @throws Exception
*/
public static String ENCRYPTMethod(String HexString, String keyStr,
String keyENCODED, String HexStringENCODED,
String CipherInstanceType) throws Exception {
String jmstr = "";
try {
byte[] theKey = null;
String jqstr = getstrByte(keyStr).substring(0, 8).toUpperCase();
theKey = jqstr.getBytes(keyENCODED);
Cipher cipher = Cipher.getInstance(CipherInstanceType);
DESKeySpec desKeySpec = new DESKeySpec(theKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(theKey);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] theCph = cipher
.doFinal(HexString.getBytes(HexStringENCODED));
jmstr = toHexString(theCph).toUpperCase();
jmstr = toHexString(theCph);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return jmstr;
}
/**
* The test case scenario implemented in the method: - create my own secret
* Key2 as an instance of a class implements PBEKey - spoil the key (set
* iteration count to 0, for example) - try to translate key -
* InvalidKeyException is expected.
*/
public void translateSpoiledKey(byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
// derive the key
SecretKey key1 = getMyOwnSecretKey(salt);
// spoil the key
((MyPBKDF2SecretKey) key1).spoil();
// translate key
SecretKeyFactory skf = SecretKeyFactory.getInstance(algoForTest);
try {
skf.translateKey(key1);
throw new RuntimeException(
"translateSpoiledKey test case failed, should throw"
+ " InvalidKeyException when spoil the key");
} catch (InvalidKeyException ike) {
out.println("Expected exception when spoil the key");
}
}
/**
* DES加密
*
* @param src
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密匙数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
// 现在,获取数据并加密
// 正式执行加密操作
return cipher.doFinal(src);
}
/**
* generates a secret key from the passed in raw key value
* we create a 256 bit key that is salted using our example
* salt value above
*
* @param key input key in a char array
* @return a salted key of the type SECRET_KEY_TYPE
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
* @throws InvalidKeySpecException
*/
private static SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException,
UnsupportedEncodingException,
InvalidKeySpecException,
NoSuchProviderException
{
SecretKeyFactory factory = null;
factory = SecretKeyFactory.getInstance(SECRET_KEY_TYPE,
SECURITY_PROVIDER);
KeySpec spec = new PBEKeySpec(key,
salt.getBytes("UTF-8"),
ITERATION_COUNT,
KEY_LENGTH);
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), AES);
}
/**
* The test case scenario implemented in the method: - derive PBKDF2 key
* using the given algorithm; - translate the key - check if the translated
* and original keys have the same key value.
*
*/
public void generateAndTranslateKey(byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException,
InvalidKeyException {
// derive PBKDF2 key
SecretKey key1 = getSecretKeyForPBKDF2(algoForTest, salt);
// translate key
SecretKeyFactory skf = SecretKeyFactory.getInstance(algoForTest);
SecretKey key2 = skf.translateKey(key1);
// Check if it still the same after translation
if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
System.out.println("Key1=" + new String(key1.getEncoded())
+ " key2=" + new String(key2.getEncoded()) + " salt="
+ new String(salt));
throw new RuntimeException(
"generateAndTranslateKey test case failed: the key1 and"
+ " key2 values in its primary encoding format are"
+ " not the same for " + algoForTest
+ " algorithm.");
}
}
/**
* DES加密
* @param HexString 字符串(16位16进制字符串)
* @param keyStr 密钥16个1
* @param keyENCODED Keybyte转换编码
* @param HexStringENCODED 要加密值的转换byte编码
* @param CipherInstanceType 需要加密类型
* @return
* @throws Exception
*/
public static String ENCRYPTMethod(String HexString, String keyStr,String keyENCODED,String HexStringENCODED,String CipherInstanceType)
throws Exception {
String jmstr = "";
try {
byte[] theKey = null;
String jqstr = getstrByte(keyStr).substring(0,8).toUpperCase();
theKey = jqstr.getBytes(keyENCODED);
Cipher cipher = Cipher.getInstance(CipherInstanceType);
DESKeySpec desKeySpec = new DESKeySpec(theKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(theKey);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] theCph = cipher.doFinal(HexString.getBytes(HexStringENCODED));
jmstr = toHexString(theCph).toUpperCase();
jmstr = toHexString(theCph);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return jmstr;
}
public static void main(String[] args) throws Exception
{
if( args.length != 4 )
{
System.err.println(msm.getString("pbeUtilsMessage"));
}
byte[] salt = args[0].substring(0, 8).getBytes();
int count = Integer.parseInt(args[1]);
char[] password = args[2].toCharArray();
byte[] passwordToEncode = args[3].getBytes("UTF-8");
PBEParameterSpec cipherSpec = new PBEParameterSpec(salt, count);
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEwithMD5andDES");
SecretKey cipherKey = factory.generateSecret(keySpec);
String encodedPassword = encode64(passwordToEncode, "PBEwithMD5andDES",
cipherKey, cipherSpec);
System.err.println("Encoded password: "+encodedPassword);
}
public static boolean validatePassword(char[] originalPassword, String storedPassword) throws NoSuchAlgorithmException, InvalidKeySpecException
{
String[] parts = storedPassword.split(":");
int iterations = Integer.parseInt(parts[0]);
byte[] salt = fromHex(parts[1]);
byte[] hash = fromHex(parts[2]);
PBEKeySpec spec = new PBEKeySpec(originalPassword, salt, iterations, hash.length * 8);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] testHash = skf.generateSecret(spec).getEncoded();
int diff = hash.length ^ testHash.length;
for(int i = 0; i < hash.length && i < testHash.length; i++)
{
diff |= hash[i] ^ testHash[i];
}
return diff == 0;
}
public static void main(String[] argv) throws Exception {
EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(
Base64.getMimeDecoder().decode(PKCS8PrivateKey));
PBEKeySpec pks = new PBEKeySpec(password.toCharArray());
SecretKeyFactory skf = SecretKeyFactory.getInstance(epki.getAlgName());
SecretKey sk = skf.generateSecret(pks);
PKCS8EncodedKeySpec keySpec = epki.getKeySpec(sk);
// Get the key algorithm and make sure it's what we expect
String alg = keySpec.getAlgorithm();
if (!alg.equals(keyAlg)) {
throw new Exception("Expected: " + keyAlg + ", Got: " + alg);
}
System.out.println("Test passed");
}
/**
* Generates a key specification for an (encrypted) private key.
*
* @param password characters, if {@code null} or empty an unencrypted key is assumed
* @param key bytes of the DER encoded private key
*
* @return a key specification
*
* @throws IOException if parsing {@code key} fails
* @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unkown
* @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is unkown
* @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be generated
* @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to decrypt
* {@code key}
* @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow faulty
*/
protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key)
throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
InvalidKeyException, InvalidAlgorithmParameterException {
if (password == null || password.length == 0) {
return new PKCS8EncodedKeySpec(key);
}
EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);
Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());
return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
/**
* The key is generating by SecretKeyFactory and its value just copying in
* the key field of MySecretKey class. So, this is real key derived using
* the given algorithm.
*
* @param passPhrase some string intended to be a password
* @param algo PBKDF2 algorithm
* @param salt slat for PBKDF2
* @param iterationCount iteration count
* @param keySize key size in bits
* @throws InvalidKeySpecException
* @throws NoSuchAlgorithmException
*/
public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt,
int iterationCount, int keySize)
throws InvalidKeySpecException, NoSuchAlgorithmException {
this.algorithm = algo;
this.salt = salt;
this.itereationCount = iterationCount;
this.keySize = keySize;
this.pass = passPhrase;
PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(),
this.salt, iterationCount, this.keySize);
SecretKeyFactory keyFactory
= SecretKeyFactory.getInstance(algo);
SecretKey realKey = keyFactory.generateSecret(spec);
this.keyLength = realKey.getEncoded().length;
this.key = new byte[this.keyLength];
System.arraycopy(realKey.getEncoded(), 0, this.key, 0,
this.keyLength);
}
@Override
@SneakyThrows
public byte[] encrypt(byte[] message) {
// create Key
final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
byte[] salt = saltGenerator.generateSalt(8);
final PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterations);
SecretKey key = factory.generateSecret(keySpec);
// Build cipher.
final Cipher cipherEncrypt = Cipher.getInstance(algorithm);
cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);
// Save parameters
byte[] params = cipherEncrypt.getParameters().getEncoded();
// Encrypted message
byte[] encryptedMessage = cipherEncrypt.doFinal(message);
return ByteBuffer
.allocate(1 + params.length + encryptedMessage.length)
.put((byte) params.length)
.put(params)
.put(encryptedMessage)
.array();
}
/**
* 解密
*
* @param content
* 待解密内容
* @param key
* 解密的密钥
* @return
*/
public static String decrypt(byte[] content, String key) {
try {
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, securekey, random);
byte[] result = cipher.doFinal(content);
System.out.println(result.length);
return new String(result);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
/**
* Description 根据键值进行加密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
/**
* The key is generating by SecretKeyFactory and its value just copying
* in the key field of MySecretKey class. So, this is real key derived
* using the given algo.
*/
public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt1,
int iterationCount, int keySize)
throws InvalidKeySpecException, NoSuchAlgorithmException {
algorithm = algo;
salt = salt1;
itereationCount = iterationCount;
pass = passPhrase;
PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt,
iterationCount, keySize);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo);
SecretKey realKey = keyFactory.generateSecret(spec);
keyLength = realKey.getEncoded().length;
key = new byte[keyLength];
System.arraycopy(realKey.getEncoded(), 0, key, 0, keyLength);
}
/**
* The test case scenario implemented in the method: - create my own secret
* Key2 as an instance of a class implements PBEKey - spoil the key (set
* iteration count to 0, for example) - try to translate key -
* InvalidKeyException is expected.
*/
public void translateSpoiledKey(byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
// derive the key
SecretKey key1 = getMyOwnSecretKey(salt);
// spoil the key
((MyPBKDF2SecretKey) key1).spoil();
// translate key
SecretKeyFactory skf = SecretKeyFactory.getInstance(algoForTest);
try {
skf.translateKey(key1);
throw new RuntimeException(
"translateSpoiledKey test case failed, should throw"
+ " InvalidKeyException when spoil the key");
} catch (InvalidKeyException ike) {
out.println("Expected exception when spoil the key");
}
}
private String encryptPassword(String clearText) {
try {
DESKeySpec keySpec = new DESKeySpec(
PASSWORD_ENC_SECRET.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
String encrypedPwd = Base64.encodeToString(cipher.doFinal(clearText
.getBytes("UTF-8")), Base64.DEFAULT);
return encrypedPwd;
} catch (Exception e) {
}
return clearText;
}
/**
* 根据PBE密码生成一把密钥
*
* @param password
* 生成密钥时所使用的密码
* @return Key PBE算法密钥
* */
private static Key getPBEKey(String password) {
// 实例化使用的算法
SecretKeyFactory keyFactory;
SecretKey secretKey = null;
try {
keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
// 设置PBE密钥参数
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
// 生成密钥
secretKey = keyFactory.generateSecret(keySpec);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return secretKey;
}
/**
* The test case scenario implemented in the method: - derive PBKDF2 key
* using the given algorithm; - translate the key - check if the translated
* and original keys have the same key value.
*
* @return true if the test case passed; false - otherwise.
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws InvalidKeyException
*/
public boolean generateAndTranslateKey() throws NoSuchAlgorithmException,
InvalidKeySpecException, InvalidKeyException {
// derive PBKDF2 key
SecretKey key1 = getSecretKeyForPBKDF2(algoToTest);
// translate key
SecretKeyFactory skf = SecretKeyFactory.getInstance(algoToTest);
SecretKey key2 = skf.translateKey(key1);
// check if it still the same after translation
if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
System.err.println("generateAndTranslateKey test case failed: the "
+ "key1 and key2 values in its primary encoding format are "
+ "not the same for " + algoToTest + "algorithm.");
return false;
}
return true;
}
/**
* The test case scenario implemented in the method: - derive PBKDF2 key
* using the given algorithm; - translate the key - check if the translated
* and original keys have the same key value.
*
*/
public void generateAndTranslateKey(byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException,
InvalidKeyException {
// derive PBKDF2 key
SecretKey key1 = getSecretKeyForPBKDF2(algoForTest, salt);
// translate key
SecretKeyFactory skf = SecretKeyFactory.getInstance(algoForTest);
SecretKey key2 = skf.translateKey(key1);
// Check if it still the same after translation
if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
System.out.println("Key1=" + new String(key1.getEncoded())
+ " key2=" + new String(key2.getEncoded()) + " salt="
+ new String(salt));
throw new RuntimeException(
"generateAndTranslateKey test case failed: the key1 and"
+ " key2 values in its primary encoding format are"
+ " not the same for " + algoForTest
+ " algorithm.");
}
}