當前位置: 首頁>>代碼示例>>Java>>正文


Java SecretKeyFactory.generateSecret方法代碼示例

本文整理匯總了Java中javax.crypto.SecretKeyFactory.generateSecret方法的典型用法代碼示例。如果您正苦於以下問題:Java SecretKeyFactory.generateSecret方法的具體用法?Java SecretKeyFactory.generateSecret怎麽用?Java SecretKeyFactory.generateSecret使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.crypto.SecretKeyFactory的用法示例。


在下文中一共展示了SecretKeyFactory.generateSecret方法的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;
}
 
開發者ID:noseparte,項目名稱:Spring-Boot-Server,代碼行數:30,代碼來源:DES.java

示例2: wrapperPBEKeyTest

import javax.crypto.SecretKeyFactory; //導入方法依賴的package包/類
private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException,
        InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException {
    for (String alg : PBE_ALGORITHM_AR) {
        String baseAlgo = alg.split("/")[0].toUpperCase();
        // only run the tests on longer key lengths if unlimited version
        // of JCE jurisdiction policy files are installed

        if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE
                && (baseAlgo.endsWith("TRIPLEDES") || alg
                        .endsWith("AES_256"))) {
            out.println("keyStrength > 128 within " + alg
                    + " will not run under global policy");
            continue;
        }
        SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
        SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover"
                .toCharArray()));
        wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true);
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:23,代碼來源:TestCipherKeyWrapperTest.java

示例3: cryptData

import javax.crypto.SecretKeyFactory; //導入方法依賴的package包/類
protected byte[] cryptData(
    boolean forEncryption,
    AlgorithmIdentifier algId,
    char[] password,
    boolean wrongPKCS12Zero,
    byte[] data)
    throws IOException
{
    String algorithm = algId.getAlgorithm().getId();
    PKCS12PBEParams pbeParams = PKCS12PBEParams.getInstance(algId.getParameters());
    PBEKeySpec pbeSpec = new PBEKeySpec(password);

    try
    {
        SecretKeyFactory keyFact = SecretKeyFactory.getInstance(algorithm, bcProvider);
        PBEParameterSpec defParams = new PBEParameterSpec(
            pbeParams.getIV(),
            pbeParams.getIterations().intValue());
        BCPBEKey key = (BCPBEKey)keyFact.generateSecret(pbeSpec);

        key.setTryWrongPKCS12Zero(wrongPKCS12Zero);

        Cipher cipher = Cipher.getInstance(algorithm, bcProvider);
        int mode = forEncryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE;
        cipher.init(mode, key, defParams);
        return cipher.doFinal(data);
    }
    catch (Exception e)
    {
        throw new IOException("exception decrypting data - " + e.toString());
    }
}
 
開發者ID:Appdome,項目名稱:ipack,代碼行數:33,代碼來源:PKCS12KeyStoreSpi.java

示例4: decrypt

import javax.crypto.SecretKeyFactory; //導入方法依賴的package包/類
/**
 * DES解密
 * 
 * @param src
 * @param key
 * @return
 * @throws Exception
 */
public static byte[] decrypt(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.DECRYPT_MODE, securekey, sr);
    // 現在,獲取數據並解密
    // 正式執行解密操作
    return cipher.doFinal(src);
}
 
開發者ID:by-syk,項目名稱:SchTtableServer,代碼行數:26,代碼來源:DESBase64Util.java

示例5: encode

import javax.crypto.SecretKeyFactory; //導入方法依賴的package包/類
/**
 * 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;
    }
}
 
開發者ID:gaolhjy,項目名稱:cniao5,代碼行數:31,代碼來源:DESUtil.java

示例6: desEncrypt

import javax.crypto.SecretKeyFactory; //導入方法依賴的package包/類
/**
 * DES加密
 */
public static String desEncrypt(String source, String desKey) throws Exception {
	try {
		// 從原始密匙數據創建DESKeySpec對象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(new DESKeySpec(desKey.getBytes()));
		// Cipher對象實際完成加密操作
		Cipher cipher = Cipher.getInstance("DES");
		// 用密匙初始化Cipher對象
		cipher.init(Cipher.ENCRYPT_MODE, securekey);
		// 現在,獲取數據並加密
		byte[] destBytes = cipher.doFinal(source.getBytes());
		StringBuilder hexRetSB = new StringBuilder();
		for (byte b : destBytes) {
			String hexString = Integer.toHexString(0x00ff & b);
			hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString);
		}
		return hexRetSB.toString();
	} catch (Exception e) {
		throw new Exception("DES加密發生錯誤", e);
	}
}
 
開發者ID:yi-jun,項目名稱:aaden-pay,代碼行數:25,代碼來源:BaofooSecurityUtil.java

示例7: 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);
}
 
開發者ID:gahana,項目名稱:edge-jwt-sample,代碼行數:20,代碼來源:JWTValidatorTest.java

示例8: 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 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:37,代碼來源:PBKDF2Translate.java

示例9: 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);
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:26,代碼來源:PBKDF2TranslateTest.java

示例10: encryptByCBC

import javax.crypto.SecretKeyFactory; //導入方法依賴的package包/類
/**
 * 
 * (根據CBC 加密模式、指定加密key輸出對應的BASE64編碼加密串)<br>
 *
 * @param content
 * @param encryptKey
 * @return
 * @throws Exception
 * String
 * @Author fanyaowu
 * @data 2015年2月2日
 * @exception 
 * @version
 *
 */
public static String encryptByCBC(String content, String encryptKey)  throws Exception
{
	try
	{
		DESKeySpec dks = new DESKeySpec(encryptKey.getBytes());

		// 創建一個密匙工廠,然後用它把DESKeySpec轉換成
		// 一個SecretKey對象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ENCRYPT_TYPE);
		SecretKey secretKey = keyFactory.generateSecret(dks);

		// Cipher對象實際完成加密操作
		Cipher cipher = Cipher.getInstance(CBC_ALGORITHM);

		// 用密匙初始化Cipher對象
		IvParameterSpec param = new IvParameterSpec(iv);
		
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, param);

		// 執行加密操作
		byte encryptedData[] = cipher.doFinal(content.getBytes());
		
		return Base64.encodeBase64String(encryptedData);
	}
	catch (Exception e)
	{
		throw new EncryptException("Failed to encrypt for content: "
				+ content + ", encrypt key: " + encryptKey, e);
	}
	
}
 
開發者ID:marlonwang,項目名稱:raven,代碼行數:47,代碼來源:DESUtils.java

示例11: getKey

import javax.crypto.SecretKeyFactory; //導入方法依賴的package包/類
private static Key getKey(String password) {
	try {
		// ��Կ����
		PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
		// ��Կ����
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
		// ������Կ
		SecretKey secretKey = keyFactory.generateSecret(keySpec);
		return secretKey;

	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
開發者ID:coding-dream,項目名稱:Notebook,代碼行數:16,代碼來源:PBECoder.java

示例12: secret

import javax.crypto.SecretKeyFactory; //導入方法依賴的package包/類
private static SecretKey secret() throws NoSuchAlgorithmException, InvalidKeySpecException {
	byte salt[] = new byte[] { (byte)0x33, (byte)0x7b, (byte)0x09, (byte)0x0e, (byte)0xcf, (byte)0x5a, (byte)0x58, (byte)0xd9 };
	SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
	KeySpec spec = new PBEKeySpec(ApplicationProperty.UrlEncoderSecret.value().toCharArray(), salt, 1024, 128);
	SecretKey key = factory.generateSecret(spec);
	return new SecretKeySpec(key.getEncoded(), "AES");
}
 
開發者ID:Jenner4S,項目名稱:unitimes,代碼行數:8,代碼來源:UsersApiToken.java

示例13: encrypt

import javax.crypto.SecretKeyFactory; //導入方法依賴的package包/類
/**
 * Encrypts the message using password based encryption.
 * @param algo
 *        the encryption algorithm
 * @param plaintext
 *        the message to be encrypted
 * @param password
 *        the password
 * @param iterationCount
 *        the iteration count
 * @param salt
 *        the salt
 * @return iv and the cipher text in form of
 *         len(iv) of 1 byte | iv of len(iv) bytes | cipher text.
 * @throws GeneralSecurityException
 *         if error occurs.
 */
public static byte[] encrypt(PBEAlgo algo, byte[] plaintext, char[] password,
        int iterationCount, byte[] salt) throws GeneralSecurityException {
    ParamUtil.requireNonNull("plaintext", plaintext);
    ParamUtil.requireNonNull("password", password);
    ParamUtil.requireMin("iterationCount", iterationCount, 1);
    ParamUtil.requireNonNull("salt", salt);

    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algo.algoName());

    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey pbeKey = secretKeyFactory.generateSecret(pbeKeySpec);

    Cipher cipher = Cipher.getInstance(algo.algoName());
    PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, iterationCount);
    cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParameterSpec);
    pbeKeySpec.clearPassword();

    byte[] iv = cipher.getIV();
    int ivLen = (iv == null) ? 0 : iv.length;
    if (ivLen > 255) {
        throw new GeneralSecurityException("IV too long: " + ivLen);
    }

    byte[] cipherText = cipher.doFinal(plaintext);
    byte[] ret = new byte[1 + ivLen + cipherText.length];
    // length of IV
    ret[0] = (byte) (ivLen & 0xFF);
    if (ivLen > 0) {
        System.arraycopy(iv, 0, ret, 1, ivLen);
    }

    System.arraycopy(cipherText, 0, ret, 1 + ivLen, cipherText.length);
    return ret;
}
 
開發者ID:xipki,項目名稱:xitk,代碼行數:52,代碼來源:PasswordBasedEncryption.java

示例14: decrypt

import javax.crypto.SecretKeyFactory; //導入方法依賴的package包/類
protected String decrypt(String value){
    try {
        final byte[] bytes = value!=null ? Base64Support.decode(value,Base64Support.DEFAULT) : new byte[0];
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(
                Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes(UTF8), 20));
        return new String(pbeCipher.doFinal(bytes),UTF8);
    } catch( Exception e) {
        Log.e(this.getClass().getName(), "Warning, could not decrypt the value.  It may be stored in plaintext.  "+e.getMessage());
        value = "error";
        return value;
    }
}
 
開發者ID:schul-cloud,項目名稱:schulcloud-mobile-android,代碼行數:16,代碼來源:ObscuredSharedPreferences.java

示例15: desDecode

import javax.crypto.SecretKeyFactory; //導入方法依賴的package包/類
/**
 * 3DES解密
 * 
 * @param encryptText 加密文本 pk 密鑰
 * @return 解密的結果
 * @throws Exception
 */
public static String desDecode(String encryptText, String pk) throws Exception {
	Key deskey = null;
	DESedeKeySpec spec = new DESedeKeySpec(pk.getBytes());
	SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
	deskey = keyfactory.generateSecret(spec);
	Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
	IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
	cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
	byte[] decryptData = cipher.doFinal(hexStringToBytes(encryptText));
	return new String(decryptData, encoding);
}
 
開發者ID:butter-fly,項目名稱:belling-spring-rabbitmq,代碼行數:19,代碼來源:ThreeDesUtils.java


注:本文中的javax.crypto.SecretKeyFactory.generateSecret方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。