当前位置: 首页>>代码示例>>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;未经允许,请勿转载。