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


Java SecretKeySpec類代碼示例

本文整理匯總了Java中javax.crypto.spec.SecretKeySpec的典型用法代碼示例。如果您正苦於以下問題:Java SecretKeySpec類的具體用法?Java SecretKeySpec怎麽用?Java SecretKeySpec使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


SecretKeySpec類屬於javax.crypto.spec包,在下文中一共展示了SecretKeySpec類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: decipherText

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
/**
 * Decipher a text.
 * 
 * @param textToDecipher
 * @param key
 * @throws GeneralSecurityException
 * @throws IOException
 */
private byte[] decipherText(byte[] textToDecipher, SecretKeySpec key) throws GeneralSecurityException, IOException {

	try {
		Cipher dcipher = Cipher.getInstance(AES_MODE);

		// Read random initialization vector.
		final byte[] iv = Arrays.copyOfRange(textToDecipher, 0, BLOCK_SIZE);
		final IvParameterSpec ivSpec = new IvParameterSpec(iv);

		// Configure the cipher with the key and the iv.
		dcipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
		final byte[] textToDecipherWithoutIv = Arrays.copyOfRange(textToDecipher, BLOCK_SIZE,
				textToDecipher.length);

		final byte[] outputBytes = dcipher.doFinal(textToDecipherWithoutIv);
		return outputBytes;

	} catch (final GeneralSecurityException exc) {
		throw exc;
	}
}
 
開發者ID:Mikiya83,項目名稱:hbs_decipher,代碼行數:30,代碼來源:QNAPFileDecrypterEngine.java

示例2: decrypt

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
/**
     * Implementation of AES decryption
     */
    public static String decrypt(String method, byte[] key, Key keyType, byte[] vector, byte[] message) throws Exception       {

//        generate Key
        byte[] keyBytes = generateKey(key, keyType.type);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, Method.AES.getMethod());

//        generate Initialization Vector
        byte[] keyBytesIv = generateVector(vector, VECTOR_LEGHT);
        IvParameterSpec ivSpec = new IvParameterSpec(keyBytesIv);

        Cipher cipher = Cipher.getInstance(method);

        if(hasInitVector(method)){
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
        }

        byte[] cipherText = cipher.doFinal(Base64.decode(message, Base64.DEFAULT));

        return new String(cipherText);
    }
 
開發者ID:BullyBoo,項目名稱:Encryption,代碼行數:26,代碼來源:AES.java

示例3: encrypt

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
/**
 * AES加密字符串
 *
 * @param content  需要被加密的字符串
 * @param password 加密需要的密碼
 * @return 密文
 */
public static byte[] encrypt(String content, String password) {
    try {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");// 創建AES的Key生產者
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
        secureRandom.setSeed(password.getBytes());
        kgen.init(128, secureRandom);// 利用用戶密碼作為隨機數初始化出
        // 128位的key生產者
        //加密沒關係,SecureRandom是生成安全隨機數序列,password.getBytes()是種子,隻要種子相同,序列就一樣,所以解密隻要有password就行
        SecretKey secretKey = kgen.generateKey();// 根據用戶密碼,生成一個密鑰
        byte[] enCodeFormat = secretKey.getEncoded();// 返回基本編碼格式的密鑰,如果此密鑰不支持編碼,則返回null。
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 轉換為AES專用密鑰
        Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
        byte[] byteContent = content.getBytes("utf-8");
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化為加密模式的密碼器
        return cipher.doFinal(byteContent);
    } catch (NoSuchPaddingException | NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
        e.printStackTrace();
    }
    return null;
}
 
開發者ID:Leibnizhu,項目名稱:AlipayWechatPlatform,代碼行數:28,代碼來源:AESUtils.java

示例4: encode

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
public static byte[] encode(byte[] secret, String data) throws Exception {
	if (secret == null || StringUtils.isEmpty(data)) {
		throw new IllegalArgumentException("Secret and Data must be supplied.");
	}

	Mac mac = Mac.getInstance("HmacSHA256");
	byte[] dataBytes = data.getBytes("UTF-8");
	SecretKey secretKey = new SecretKeySpec(secret, "HmacSHA256");

	mac.init(secretKey);
	byte[] doFinal = mac.doFinal(dataBytes);
	return doFinal;
}
 
開發者ID:melthaw,項目名稱:spring-backend-boilerplate,代碼行數:14,代碼來源:HmacUtils.java

示例5: encryptAesCtr

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
private byte[] encryptAesCtr(byte[] passwordBytes, byte[] iv) throws EncryptionException {
    try {
        SecretKey key = new SecretKeySpec(DatatypeConverter.parseHexBinary(keyProvider.getKeyHex()), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance(AESCTR_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
        byte[] result = cipher.doFinal(DatatypeConverter.parseHexBinary(DatatypeConverter.printHexBinary(passwordBytes)));

        Arrays.fill(passwordBytes, (byte)0);

        return result;
    } catch (Exception ex) {
        LOG.error("Error encrypting plainText", ex);
        throw new EncryptionException("Failed to encrypt cipher with AES-CTR", ex);
    }
}
 
開發者ID:opensecuritycontroller,項目名稱:osc-core,代碼行數:17,代碼來源:AESCTREncryption.java

示例6: decryptAESCBC

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
/**
 * Decrypt the provided data using AES in CBC mode with the specified key and initial vector. No padding will be
 * removed from the decrypted data.
 * @param data the data to be decrypted
 * @param keyBytes the bytes of the AES key to use for the decryption
 * @return the decrypted data
 * @throws IllegalStateException if there was a problem during decryption
 * @throws NullPointerException if any of the input parameters are null
 * @throws IllegalArgumentException if any of the input parameters are invalid
 */
public static byte[] decryptAESCBC(byte[] data, byte[] keyBytes)
{
    Preconditions.checkForNull("Data", data);
    Preconditions.check(data.length >= 16, "Data must be at least 16 bytes");
    Preconditions.check((data.length % 16) == 0, "Data length not multiple of 16");
    Preconditions.checkForNull("Key bytes", keyBytes);
    Preconditions.check(checkAESKeyLength(keyBytes), "Key must be 16, 24 or 32 bytes");

    try
    {
        final SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
        final IvParameterSpec iv = new IvParameterSpec(Bytes.repeated(16, 0x00));
        final Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, key, iv);

        return cipher.doFinal(data);
    }
    catch (Exception e)
    {
        throw new IllegalStateException("Error decrypting data", e);
    }
}
 
開發者ID:mDL-ILP,項目名稱:mDL-ILP,代碼行數:33,代碼來源:AESUtils.java

示例7: decrypt

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
/**
 * 解密
 *
 * @param encKey          加密密碼
 * @param encryptedString 需要解密的內容
 * @return
 */
public static String decrypt(String encKey, String encryptedString) {
    String decryptedString = "";
    try {
        //初始化密鑰
        SecretKeySpec keySpec = new SecretKeySpec(encKey.getBytes("utf-8"), "DES");
        //選擇使用DES算法,ECB方式,填充方式為PKCS5Padding
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        //初始化
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        //獲取解密後的字符串
        decryptedString = new String(cipher.doFinal(hexToBytes(encryptedString)));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return decryptedString;
}
 
開發者ID:AH-UGC-Android,項目名稱:HttpProxyInjection,代碼行數:24,代碼來源:EncryptUtils.java

示例8: Encrypt

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
public static String Encrypt(String sSrc) throws Exception {
	if (key == null) {
		System.out.print("Key為空null");
		return null;
	}
	// 判斷Key是否為16位
	if (key.length() != 16) {
		System.out.print("Key長度不是16位");
		return null;
	}
	byte[] raw = key.getBytes("UTF-8");
	SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
	Cipher cipher = Cipher.getInstance("AES/CBC/Iso10126Padding");//"算法/模式/補碼方式"
	IvParameterSpec ivps = new IvParameterSpec(iv.getBytes("UTF-8"));//使用CBC模式,需要一個向量iv,可增加加密算法的強度
	cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivps);
	byte[] encrypted = cipher.doFinal(sSrc.getBytes("UTF-8"));

	return new String(Base64.encodeBase64(encrypted),"UTF-8");//此處使用BAES64做轉碼功能,同時能起到2次加密的作用。
}
 
開發者ID:wp521,項目名稱:MyFire,代碼行數:20,代碼來源:AESUtil.java

示例9: AESDecrypt

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
/**
 * 加密
 * 
 * @param text 要加密的字符串
 * @param iv 初始化向量參數
 * @param password 密鑰
 * @return
 */
public static String AESDecrypt(String text, String iv, String password, String mode) throws Exception
{
	Cipher cipher = Cipher.getInstance(mode);

	byte[] keyBytes = new byte[16];
	byte[] b = password.getBytes("UTF-8");
	int len = b.length;
	if (len > keyBytes.length)
		len = keyBytes.length;
	System.arraycopy(b, 0, keyBytes, 0, len);
	SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
	IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
	cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

	byte[] results = cipher.doFinal(Base64.decode(text));
	return new String(results, "UTF-8");
}
 
開發者ID:benniaobuguai,項目名稱:android-project-gallery,代碼行數:26,代碼來源:AESUtil.java

示例10: extractSecretKey

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
protected Key extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier contentEncryptionAlgorithm, byte[] derivedKey, byte[] encryptedContentEncryptionKey)
    throws CMSException
{
    Cipher keyEncryptionCipher = helper.createRFC3211Wrapper(keyEncryptionAlgorithm.getAlgorithm());

    try
    {
        IvParameterSpec ivSpec = new IvParameterSpec(ASN1OctetString.getInstance(keyEncryptionAlgorithm.getParameters()).getOctets());

        keyEncryptionCipher.init(Cipher.UNWRAP_MODE, new SecretKeySpec(derivedKey, keyEncryptionCipher.getAlgorithm()), ivSpec);

        return keyEncryptionCipher.unwrap(encryptedContentEncryptionKey, contentEncryptionAlgorithm.getAlgorithm().getId(), Cipher.SECRET_KEY);
    }
    catch (GeneralSecurityException e)
    {
        throw new CMSException("cannot process content encryption key: " + e.getMessage(), e);
    }
}
 
開發者ID:Appdome,項目名稱:ipack,代碼行數:19,代碼來源:JcePasswordRecipient.java

示例11: engineGenerateSecret

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
/**
 * Generates a <code>SecretKey</code> object from the provided key
 * specification (key material).
 *
 * @param keySpec the specification (key material) of the secret key
 *
 * @return the secret key
 *
 * @exception InvalidKeySpecException if the given key specification
 * is inappropriate for this key factory to produce a public key.
 */
protected SecretKey engineGenerateSecret(KeySpec keySpec)
    throws InvalidKeySpecException {

    try {
        if (keySpec instanceof DESedeKeySpec) {
            return new DESedeKey(((DESedeKeySpec)keySpec).getKey());
        }
        if (keySpec instanceof SecretKeySpec) {
            return new DESedeKey(((SecretKeySpec)keySpec).getEncoded());

        }
        throw new InvalidKeySpecException
            ("Inappropriate key specification");
    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException(e.getMessage());
    }
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:29,代碼來源:DESedeKeyFactory.java

示例12: encode

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
public String encode(String payload) {
    JWEAlgorithm alg = JWEAlgorithm.A128KW;
    EncryptionMethod encryptionMethod = EncryptionMethod.A128GCM;

    try {
        byte[] decodedKey = Base64.getDecoder().decode(encodedKeypair);
        SecretKey key = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
        JWEObject jwe = new JWEObject(
                new JWEHeader(alg, encryptionMethod),
                new Payload(payload));
        jwe.encrypt(new AESEncrypter(key));
        return jwe.serialize();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
開發者ID:PacktPublishing,項目名稱:OAuth-2.0-Cookbook,代碼行數:18,代碼來源:JweTokenSerializer.java

示例13: AESObfuscator

import javax.crypto.spec.SecretKeySpec; //導入依賴的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);
    }
}
 
開發者ID:tranleduy2000,項目名稱:text_converter,代碼行數:23,代碼來源:AESObfuscator.java

示例14: aesEncrypt

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
/**
 * @param sSrc
 * @return 加密程序
 * @throws Exception
 */
public static String aesEncrypt(String key, String sSrc) throws Exception {
    if (key == null) {
        throw new ExceptionInInitializerError("key not bo null");
    }

    if (key.length() != 16) {
        throw new ExceptionInInitializerError("key length must be 16!");
    }
    byte[] raw = key.getBytes("ASCII");
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(1, skeySpec);
    byte[] encrypted = cipher.doFinal(sSrc.getBytes());
    return byte2hex(encrypted).toLowerCase();
}
 
開發者ID:wolfboys,項目名稱:opencron,代碼行數:21,代碼來源:DigestUtils.java

示例15: EncryptActionPerformed

import javax.crypto.spec.SecretKeySpec; //導入依賴的package包/類
private void EncryptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EncryptActionPerformed
 try{
            FileInputStream file = new FileInputStream(file_path.getText());
            FileOutputStream outStream = new FileOutputStream("Encrypt.jpg");
            byte k[]="CooL2116NiTh5252".getBytes();
            SecretKeySpec key = new SecretKeySpec(k, "AES");
            Cipher enc = Cipher.getInstance("AES");
            enc.init(Cipher.ENCRYPT_MODE, key);
            CipherOutputStream cos = new CipherOutputStream(outStream, enc);
            byte[] buf = new byte[1024];
            int read;
            while((read=file.read(buf))!=-1){
                cos.write(buf,0,read);
            }
            file.close();
            outStream.flush();
            cos.close();
            JOptionPane.showMessageDialog(null, "The file encrypted Successfully");
        }catch(Exception e){
            JOptionPane.showMessageDialog(null, e);
        }


        // TODO add your handling code here:
}
 
開發者ID:rohanpillai20,項目名稱:Web-Based-Graphical-Password-Authentication-System,代碼行數:26,代碼來源:ImgCry.java


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