本文整理匯總了Java中javax.crypto.SecretKeyFactory類的典型用法代碼示例。如果您正苦於以下問題:Java SecretKeyFactory類的具體用法?Java SecretKeyFactory怎麽用?Java SecretKeyFactory使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
SecretKeyFactory類屬於javax.crypto包,在下文中一共展示了SecretKeyFactory類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: encrypt
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
/**
* 加密
* @param datasource byte[]
* @param password String
* @return byte[]
*/
public static String encrypt(String datasource, String password) {
try {
if(StringUtils.trimToNull(datasource) == null){
return null;
}
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(password.getBytes());
// 創建一個密匙工廠,然後用它把DESKeySpec轉換成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher對象實際完成加密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher對象
cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
// 現在,獲取數據並加密
// 正式執行加密操作
return new BASE64Encoder().encode(cipher.doFinal(datasource.getBytes()));
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
示例2: calculatePbeMac
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
private static byte[] calculatePbeMac(
DERObjectIdentifier oid,
byte[] salt,
int itCount,
char[] password,
byte[] data,
String provider)
throws Exception
{
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(oid.getId(), provider);
PBEParameterSpec defParams = new PBEParameterSpec(salt, itCount);
PBEKeySpec pbeSpec = new PBEKeySpec(password);
SecretKey key = keyFact.generateSecret(pbeSpec);
Mac mac = Mac.getInstance(oid.getId(), provider);
mac.init(key, defParams);
mac.update(data);
return mac.doFinal();
}
示例3: generateKeyFromPassword
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
/**
* A function that generates password-based AES & HMAC keys. It prints out exceptions but
* doesn't throw them since none should be encountered. If they are
* encountered, the return value is null.
*
* @param password The password to derive the keys from.
* @return The AES & HMAC keys.
* @throws GeneralSecurityException if AES is not implemented on this system,
* or a suitable RNG is not available
*/
public static SecretKeys generateKeyFromPassword(String password, byte[] salt) throws GeneralSecurityException {
fixPrng();
//Get enough random bytes for both the AES key and the HMAC key:
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt,
PBE_ITERATION_COUNT, AES_KEY_LENGTH_BITS + HMAC_KEY_LENGTH_BITS);
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance(PBE_ALGORITHM);
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
// Split the random bytes into two parts:
byte[] confidentialityKeyBytes = copyOfRange(keyBytes, 0, AES_KEY_LENGTH_BITS /8);
byte[] integrityKeyBytes = copyOfRange(keyBytes, AES_KEY_LENGTH_BITS /8, AES_KEY_LENGTH_BITS /8 + HMAC_KEY_LENGTH_BITS /8);
//Generate the AES key
SecretKey confidentialityKey = new SecretKeySpec(confidentialityKeyBytes, CIPHER);
//Generate the HMAC key
SecretKey integrityKey = new SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM);
return new SecretKeys(confidentialityKey, integrityKey);
}
示例4: PBKDF2
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
private static byte[] PBKDF2(char[] secret, byte[] salt,
int count, int keyLength) throws GeneralSecurityException {
PBEKeySpec keySpec = new PBEKeySpec(secret, salt, count, keyLength);
SecretKeyFactory skf =
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey key = skf.generateSecret(keySpec);
byte[] result = key.getEncoded();
return result;
}
示例5: getEncodedPrivateKeySpec
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
public PKCS8EncodedKeySpec getEncodedPrivateKeySpec(String key, String password) throws Exception {
String privateKeyPEM = key
.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "")
.replace("-----END ENCRYPTED PRIVATE KEY-----", "")
.replaceAll("\\s", "");
// decode to get the binary DER representation
byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM);
EncryptedPrivateKeyInfo epkInfo = new EncryptedPrivateKeyInfo(privateKeyDER);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);
Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
cipher.init(Cipher.DECRYPT_MODE, pbeKey, epkInfo.getAlgParameters());
return epkInfo.getKeySpec(cipher);
}
示例6: decrypt
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
/**
* 數據解密,算法(DES)
*
* @param cryptData
* 加密數據
* @param desKey DES密鑰
* @return 解密後的數據
*/
public static String decrypt(String cryptData, byte[] desKey) {
String decryptedData = null;
try {
// DES算法要求有一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
DESKeySpec deskey = new DESKeySpec(desKey);
// 創建一個密匙工廠,然後用它把DESKeySpec轉換成一個SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(deskey);
// 解密對象
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key, sr);
// 把字符串解碼為字節數組,並解密
decryptedData = new String(cipher.doFinal(Base64.getDecoder().decode(cryptData)));
} catch (Exception e) {
// log.error("解密錯誤,錯誤信息:", e);
throw new RuntimeException("解密錯誤,錯誤信息:", e);
}
return decryptedData;
}
示例7: decrypt
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
/**
* DES
* @param src
* @param password
* @return
*/
public static byte[] decrypt(byte []src, String password) {
try {
// DES算法要求有一個可信任的隨機數源
SecureRandom random = new SecureRandom();
// 創建一個DESKeySpec對象
DESKeySpec desKey = new DESKeySpec(password.getBytes());
// 創建一個密匙工廠
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 將DESKeySpec對象轉換成SecretKey對象
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher對象實際完成解密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher對象
cipher.init(Cipher.DECRYPT_MODE, securekey, random);
// 真正開始解密操作
return cipher.doFinal(src);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
示例8: encrypt
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
/**
* DES加密
*
* @author : chenssy
* @date : 2016年5月20日 下午5:51:37
*
* @param data
* 待加密字符串
* @param key
* 校驗位
* @return
*/
@SuppressWarnings("restriction")
protected static String encrypt(String data,String key) {
String encryptedData = null;
try {
// DES算法要求有一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
DESKeySpec deskey = new DESKeySpec(key.getBytes());
// 創建一個密匙工廠,然後用它把DESKeySpec轉換成一個SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(deskey);
// 加密對象
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);
// 加密,並把字節數組編碼成字符串
encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
} catch (Exception e) {
throw new RuntimeException("加密錯誤,錯誤信息:", e);
}
return encryptedData;
}
示例9: getPBEKey
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
private SecretKey getPBEKey(char[] password) throws IOException
{
SecretKey skey = null;
try {
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKeyFactory skFac = SecretKeyFactory.getInstance("PBE");
skey = skFac.generateSecret(keySpec);
keySpec.clearPassword();
} catch (Exception e) {
throw new IOException("getSecretKey failed: " +
e.getMessage(), e);
}
return skey;
}
示例10: decrypt
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
/**
* 解密
* @param src byte[]
* @param password String
* @return String
* @throws Exception
*/
public static String decrypt(String decodeStr, String password) throws Exception {
byte[] str=new BASE64Decoder().decodeBuffer(decodeStr);
// DES算法要求有一個可信任的隨機數源
SecureRandom random = new SecureRandom();
// 創建一個DESKeySpec對象
DESKeySpec desKey = new DESKeySpec(password.getBytes());
// 創建一個密匙工廠
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 將DESKeySpec對象轉換成SecretKey對象
SecretKey securekey = keyFactory.generateSecret(desKey);
// Cipher對象實際完成解密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher對象
cipher.init(Cipher.DECRYPT_MODE, securekey, random);
// 真正開始解密操作
byte[] passByte=cipher.doFinal(str);
return new String(passByte);
}
示例11: AESObfuscator
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
/**
* @param salt an array of random bytes to use for each (un)obfuscation
* @param applicationId application identifier, e.g. the package name
* @param deviceId device identifier. Use as many sources as possible to
* create this unique identifier.
*/
public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
KeySpec keySpec =
new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
} catch (GeneralSecurityException e) {
// This can't happen on a compatible Android device.
throw new RuntimeException("Invalid environment", e);
}
}
示例12: MyPBKDF2SecretKey
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
/**
* 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);
}
示例13: passwordsMatch
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
public boolean passwordsMatch(Object submittedPlaintext, String encrypted) {
ByteSource plaintextBytes = ByteSource.Util.bytes(submittedPlaintext);
if (encrypted == null || encrypted.length() == 0) {
return plaintextBytes == null || plaintextBytes.isEmpty();
} else {
if (plaintextBytes == null || plaintextBytes.isEmpty()) {
return false;
}
}
String plaintext = new String(plaintextBytes.getBytes());
String[] tokens = encrypted.split("\\$");
int iterations = Integer.parseInt(tokens[1]);
byte[] salt = tokens[2].getBytes();
String hash = tokens[3];
KeySpec spec = new PBEKeySpec(plaintext.toCharArray(), salt, iterations, 256);
try {
String algorithmName = getAlgorithmFullName(tokens[0]);
SecretKeyFactory f = SecretKeyFactory.getInstance(algorithmName);
return hash.equals(Base64.encodeToString(f.generateSecret(spec).getEncoded()));
} catch (Exception e) {
log.error(e.getMessage());
return false;
}
}
示例14: getEncodedPrivateKeySpec
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
public static PKCS8EncodedKeySpec getEncodedPrivateKeySpec(String key, String password) throws Exception {
String privateKeyPEM = key
.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "")
.replace("-----END ENCRYPTED PRIVATE KEY-----", "")
.replaceAll("\\s", "");
// decode to get the binary DER representation
byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM);
EncryptedPrivateKeyInfo epkInfo = new EncryptedPrivateKeyInfo(privateKeyDER);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName());
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);
Cipher cipher = Cipher.getInstance(epkInfo.getAlgName());
cipher.init(Cipher.DECRYPT_MODE, pbeKey, epkInfo.getAlgParameters());
return epkInfo.getKeySpec(cipher);
}
示例15: readPrivateKey
import javax.crypto.SecretKeyFactory; //導入依賴的package包/類
private static PKCS8EncodedKeySpec readPrivateKey(File keyFile, Optional<String> keyPassword)
throws IOException, GeneralSecurityException
{
String content = Files.toString(keyFile, US_ASCII);
Matcher matcher = KEY_PATTERN.matcher(content);
if (!matcher.find()) {
throw new KeyStoreException("found no private key: " + keyFile);
}
byte[] encodedKey = base64Decode(matcher.group(1));
if (!keyPassword.isPresent()) {
return new PKCS8EncodedKeySpec(encodedKey);
}
EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(encodedKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
SecretKey secretKey = keyFactory.generateSecret(new PBEKeySpec(keyPassword.get().toCharArray()));
Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
cipher.init(DECRYPT_MODE, secretKey, encryptedPrivateKeyInfo.getAlgParameters());
return encryptedPrivateKeyInfo.getKeySpec(cipher);
}