Java 类javax.crypto.spec.SecretKeySpec 实例源码

项目:osc-core    文件:AESCTREncryption.java   
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);
    }
}
项目:hbs_decipher    文件:QNAPFileDecrypterEngine.java   
/**
 * 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;
    }
}
项目:Encryption    文件:AES.java   
/**
     * 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);
    }
项目:KafkaToSQS    文件:AESEncrypt.java   
static String checkKey(String cipherKey){
    String ret = null;
    try {
        SecretKeySpec Testkey = new SecretKeySpec(getUTF8Bytes(cipherKey),"AES");
        IvParameterSpec TestIv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
        Properties properties = new Properties();
    properties.setProperty(CryptoCipherFactory.CLASSES_KEY,
            CipherProvider.OPENSSL.getClassName());
        CryptoCipher test = Utils.getCipherInstance("AES/CBC/PKCS5Padding", properties);
        test.init(Cipher.ENCRYPT_MODE, Testkey, TestIv);
        test.close();
    }catch (Throwable e) {
         ret = e.getMessage();
    }
    return ret;
}
项目:mDL-ILP    文件:AESUtils.java   
/**
 * 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);
    }
}
项目:mDL-ILP    文件:AESUtils.java   
/**
 * 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);
    }
}
项目:AlipayWechatPlatform    文件:AESUtils.java   
/**
 * 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;
}
项目:HttpProxyInjection    文件:EncryptUtils.java   
/**
 * 解密
 *
 * @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;
}
项目:MyFire    文件:AESUtil.java   
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次加密的作用。
}
项目:android-project-gallery    文件:AESUtil.java   
/**
 * 加密
 * 
 * @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");
}
项目:ipack    文件:JcePasswordRecipient.java   
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);
    }
}
项目:OpenJSharp    文件:DESedeKeyFactory.java   
/**
 * 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());
    }
}
项目:OAuth-2.0-Cookbook    文件:JweTokenSerializer.java   
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);
    }
}
项目:text_converter    文件:AESObfuscator.java   
/**
 * @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);
    }
}
项目:opencron    文件:DigestUtils.java   
/**
 * @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();
}
项目:Web-Based-Graphical-Password-Authentication-System    文件:ImgCry.java   
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:
}
项目:AirQuickUtils    文件:AirSecurity.java   
/**
 * CBC mode, PKCS5 Padding.
 *
 * @param encoded
 *            Decode target, Encrypted state.
 * @param key
 * @param initializationVector
 *            CBC requires an initialization vector.
 * @return decrypt array
 */
public byte[] decrypt(byte[] encoded , byte[] key, byte[] initializationVector) {
    try {
        Cipher dcipher = null;
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(initializationVector);
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

        dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        dcipher.init(Cipher.DECRYPT_MODE, keySpec, paramSpec);

        return dcipher.doFinal(encoded);
    } catch (Exception e) {
        AirQuickUtils.log.e("AesCipher" , e);
    }
    return null;
}
项目:CryptoPayAPI    文件:HttpRest.java   
public static String decrypt(byte[] input, byte[] key){
    System.out.println(input);
    byte[] output = null;
    try{
        SecretKeySpec skey = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skey);
        String temp = new String(input);
        temp = temp.replace("\\", "");
        output = cipher.doFinal(Base64.getDecoder().decode(temp));
        temp = "";
    } catch(Exception e){
        System.out.println(e.toString());
    }
    return new String(output);
}
项目:PeSanKita-android    文件:MasterSecretUtil.java   
public static MasterSecret generateMasterSecret(Context context, String passphrase) {
  try {
    byte[] encryptionSecret             = generateEncryptionSecret();
    byte[] macSecret                    = generateMacSecret();
    byte[] masterSecret                 = Util.combine(encryptionSecret, macSecret);
    byte[] encryptionSalt               = generateSalt();
    int    iterations                   = generateIterationCount(passphrase, encryptionSalt);
    byte[] encryptedMasterSecret        = encryptWithPassphrase(encryptionSalt, iterations, masterSecret, passphrase);
    byte[] macSalt                      = generateSalt();
    byte[] encryptedAndMacdMasterSecret = macWithPassphrase(macSalt, iterations, encryptedMasterSecret, passphrase);

    save(context, "encryption_salt", encryptionSalt);
    save(context, "mac_salt", macSalt);
    save(context, "passphrase_iterations", iterations);
    save(context, "master_secret", encryptedAndMacdMasterSecret);
    save(context, "passphrase_initialized", true);

    return new MasterSecret(new SecretKeySpec(encryptionSecret, "AES"),
                            new SecretKeySpec(macSecret, "HmacSHA1"));
  } catch (GeneralSecurityException e) {
    Log.w("keyutil", e);
    return null;
  }
}
项目:syndesis    文件:StaticEditionTest.java   
@Test
public void shouldCreateEditionFromProperties() {
    ClientSideStateProperties properties = new ClientSideStateProperties();
    properties.setAuthenticationAlgorithm("HmacSHA1");
    properties.setAuthenticationKey("oID3dF6UovTkzMyr3a9dr0kgTnE=");
    properties.setEncryptionAlgorithm("AES/CBC/PKCS5Padding");
    properties.setEncryptionKey("T2NasjRXURA3dSL8dUQubQ==");
    properties.setTid(1L);

    StaticEdition edition = new StaticEdition(properties);

    assertThat(edition.authenticationAlgorithm).isEqualTo("HmacSHA1");
    assertThat(edition.encryptionAlgorithm).isEqualTo("AES/CBC/PKCS5Padding");
    assertThat(edition.tid).isEqualTo(new byte[] {1});
    assertThat(edition.keySource().authenticationKey())
        .isEqualTo(new SecretKeySpec(new byte[] {(byte) 0xa0, (byte) 0x80, (byte) 0xf7, 0x74, 0x5e, (byte) 0x94,
            (byte) 0xa2, (byte) 0xf4, (byte) 0xe4, (byte) 0xcc, (byte) 0xcc, (byte) 0xab, (byte) 0xdd, (byte) 0xaf,
            0x5d, (byte) 0xaf, 0x49, 0x20, 0x4e, 0x71}, "HmacSHA1"));
    assertThat(edition.keySource().encryptionKey()).isEqualTo(new SecretKeySpec(new byte[] {0x4f, 0x63, 0x5a,
        (byte) 0xb2, 0x34, 0x57, 0x51, 0x10, 0x37, 0x75, 0x22, (byte) 0xfc, 0x75, 0x44, 0x2e, 0x6d}, "AES"));
}
项目:openjdk-jdk10    文件:DESKeyFactory.java   
/**
 * 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 DESKeySpec) {
            return new DESKey(((DESKeySpec)keySpec).getKey());
        }

        if (keySpec instanceof SecretKeySpec) {
            return new DESKey(((SecretKeySpec)keySpec).getEncoded());
        }

        throw new InvalidKeySpecException(
                "Inappropriate key specification");

    } catch (InvalidKeyException e) {
        throw new InvalidKeySpecException(e.getMessage());
    }
}
项目:FaceDistinguish    文件:SignUtil.java   
/**
 * 计算签名
 *
 * @param secret APP密钥
 * @param method HttpMethod
 * @param path
 * @param headers
 * @param querys
 * @param bodys
 * @param signHeaderPrefixList 自定义参与签名Header前缀
 * @return 签名后的字符串
 */
public static String sign(String secret, String method, String path, 
                            Map<String, String> headers, 
                            Map<String, String> querys, 
                            Map<String, String> bodys, 
                            List<String> signHeaderPrefixList) {
    try {
        Mac hmacSha256 = Mac.getInstance(Constants.HMAC_SHA256);
        byte[] keyBytes = secret.getBytes(Constants.ENCODING);
        hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, Constants.HMAC_SHA256));

        return new String(Base64.encodeBase64(
                hmacSha256.doFinal(buildStringToSign(method, path, headers, querys, bodys, signHeaderPrefixList)
                        .getBytes(Constants.ENCODING))),
                Constants.ENCODING);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:automat    文件:WXBizMsgCrypt.java   
/**
 * 对明文进行加密.
 * 
 * @param text 需要加密的明文
 * @return 加密后base64编码的字符串
 * @throws AesException aes加密失败
 */
String encrypt(String randomStr, String text) throws AesException {
    ByteGroup byteCollector = new ByteGroup();
    byte[] randomStrBytes = randomStr.getBytes(CHARSET);
    byte[] textBytes = text.getBytes(CHARSET);
    byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
    byte[] corpidBytes = corpId.getBytes(CHARSET);

    // randomStr + networkBytesOrder + text + corpid
    byteCollector.addBytes(randomStrBytes);
    byteCollector.addBytes(networkBytesOrder);
    byteCollector.addBytes(textBytes);
    byteCollector.addBytes(corpidBytes);

    // ... + pad: 使用自定义的填充方式对明文进行补位填充
    byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
    byteCollector.addBytes(padBytes);

    // 获得最终的字节流, 未加密
    byte[] unencrypted = byteCollector.toBytes();

    try {
        // 设置加密模式为AES的CBC模式
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
        IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

        // 加密
        byte[] encrypted = cipher.doFinal(unencrypted);

        // 使用BASE64对加密后的字符串进行编码
        String base64Encrypted = base64.encodeToString(encrypted);

        return base64Encrypted;
    } catch (Exception e) {
        e.printStackTrace();
        throw new AesException(AesException.EncryptAESError);
    }
}
项目:bootstrap    文件:ApiTokenResource.java   
/**
 * Encrypt the message with the given key.
 * 
 * @param message
 *            Ciphered message.
 * @param secretKey
 *            The secret key.
 * @return the original message.
 */
private String encrypt(final String message, final byte[] secretKey) throws GeneralSecurityException {
    final MessageDigest digest = MessageDigest.getInstance(tokenDigest);
    digest.reset();
    final byte[] digestOfPassword = digest.digest(secretKey);
    final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
    final SecretKey key = new SecretKeySpec(keyBytes, tokenCrypt);
    final Cipher cipher = Cipher.getInstance(tokenCrypt);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    final byte[] plainTextBytes = message.getBytes(StandardCharsets.UTF_8);
    final byte[] buf = cipher.doFinal(plainTextBytes);
    final byte[] base64Bytes = Base64.encodeBase64(buf);
    return new String(base64Bytes, StandardCharsets.UTF_8);
}
项目:export-distro    文件:EncryptionTransformer.java   
private String getEncryptedString(String data, String encryptionKey, String vector) throws Exception {
    MessageDigest msgDigest = MessageDigest.getInstance(MSG_DIGEST_HASH);
    SecretKeySpec keySpec = new SecretKeySpec(first128Bits(msgDigest.digest(getBytes(encryptionKey))),
            ENCRYPTION_ALGORITHM);
    IvParameterSpec initVectorSpec = new IvParameterSpec(first128Bits(getBytes(vector)));
    Cipher cipher = Cipher.getInstance(CIPHER_TRX);
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, initVectorSpec);
    return new String(Base64.getEncoder().encode(cipher.doFinal(getBytes(data))), LOCAL_ENCODING);
}
项目:java-dukpt    文件:Dukpt.java   
/**
 * Performs Single AES Decryption.
 * 
 * This is supplied for use generic encryption and decryption purposes, but is not a part of the Dukpt algorithm.
 * 
 * @param key The key for decryption.
 * @param data The data to decrypt.
 * @param padding When true, PKCS5 Padding will be assumed.  This is most likely not desirable.
 * @return The decrypted data.
 * @throws Exception
 */
public static byte[] decryptAes(byte[] key, byte[] data, boolean padding) throws Exception {
    IvParameterSpec iv = new IvParameterSpec(new byte[16]);
    SecretKeySpec decryptKey = new SecretKeySpec(key, "AES");

    Cipher decryptor;
    if (padding)
        decryptor = Cipher.getInstance("AES/CBC/PKCS5Padding");
    else
        decryptor = Cipher.getInstance("AES/CBC/NoPadding");
    decryptor.init(Cipher.DECRYPT_MODE, decryptKey, iv);
    return decryptor.doFinal(data);
}
项目:Android-UtilCode    文件:EncryptUtils.java   
/**
 * Hmac加密模板
 *
 * @param data      数据
 * @param key       秘钥
 * @param algorithm 加密算法
 * @return 密文字节数组
 */
private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) {
    if (data == null || data.length == 0 || key == null || key.length == 0) return null;
    try {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(secretKey);
        return mac.doFinal(data);
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}
项目:godlibrary    文件:AESCipher.java   
private static byte[] decrypt(byte[] key, byte[] encrypted) throws Exception {
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    byte[] decrypted = cipher.doFinal(encrypted);
    return decrypted;
}
项目:HeadlineNews    文件:EncryptUtils.java   
/**
 * Hmac加密模板
 *
 * @param data      数据
 * @param key       秘钥
 * @param algorithm 加密算法
 * @return 密文字节数组
 */
private static byte[] hmacTemplate(final byte[] data, final byte[] key, final String algorithm) {
    if (data == null || data.length == 0 || key == null || key.length == 0) return null;
    try {
        SecretKeySpec secretKey = new SecretKeySpec(key, algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(secretKey);
        return mac.doFinal(data);
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}
项目:mumu    文件:HmacCoder.java   
/**
 * HmacMD4消息摘要
 * 
 * @param data 待做消息摘要处理的数据
 * @param byte[] 密钥
 * @return byte[] 消息摘要
 * @throws Exception
 */
public static byte[] encodeHmacMD4(byte[] data, byte[] key) throws Exception {
    // 还原密钥
    SecretKey secretKey = new SecretKeySpec(key, "HmacMD4");
    // 实例化Mac
    Mac mac = Mac.getInstance(secretKey.getAlgorithm());
    // 初始化Mac
    mac.init(secretKey);
    // 执行消息摘要
    return mac.doFinal(data);
}
项目:PreferenceRoom    文件:SecurityUtils.java   
public static String encrypt(String input) {
    if(input == null) return null;
    byte[] encrypted = null;
    try{
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skey);
        encrypted = cipher.doFinal(input.getBytes());
    } catch(Exception e){
        e.printStackTrace();
    }
    return Base64.encodeToString(encrypted, Base64.DEFAULT);
}
项目:PreferenceRoom    文件:SecurityUtils.java   
public static String decrypt(String input) {
    if(input == null) return null;
    byte[] decrypted = null;
    try{
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skey);
        decrypted = cipher.doFinal(Base64.decode(input, Base64.DEFAULT));
    } catch(Exception e){
        e.printStackTrace();
    }
    return new String(decrypted);
}
项目:secure-tomcat-datasourcefactory    文件:Main.java   
public static byte[] encryptPassword(String password, String algorithm, String mode, String padding, byte[] key) throws GeneralSecurityException {
    SecretKeySpec keySpec = new SecretKeySpec(key, algorithm);
    Cipher cipher = Cipher.getInstance(format("%s/%s/%s", algorithm, mode, padding));
       cipher.init(ENCRYPT_MODE, keySpec);
       byte[] cipherText = cipher.doFinal(password.getBytes());

       return cipherText;
}
项目:OpenJSharp    文件:HmacMD5KeyGenerator.java   
/**
 * Generates an HMAC-MD5 key.
 *
 * @return the new HMAC-MD5 key
 */
protected SecretKey engineGenerateKey() {
    if (this.random == null) {
        this.random = SunJCE.getRandom();
    }

    byte[] keyBytes = new byte[this.keysize];
    this.random.nextBytes(keyBytes);

    return new SecretKeySpec(keyBytes, "HmacMD5");
}
项目:keepass2android    文件:CipherFactory.java   
public static Cipher getInstance(UUID uuid, int opmode, byte[] key, byte[] IV, boolean androidOverride) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
    if ( uuid.equals(AES_CIPHER) ) {
        Cipher cipher = CipherFactory.getInstance("AES/CBC/PKCS5Padding", androidOverride); 

        cipher.init(opmode, new SecretKeySpec(key, "AES"), new IvParameterSpec(IV));

        return cipher;
    }

    throw new NoSuchAlgorithmException("UUID unrecognized.");
}
项目:NoteBuddy    文件:AesCbcWithIntegrity.java   
/**
 * A function that generates random AES & HMAC keys and prints out exceptions but
 * doesn't throw them since none should be encountered. If they are
 * encountered, the return value is null.
 *
 * @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 generateKey() throws GeneralSecurityException {
    fixPrng();
    KeyGenerator keyGen = KeyGenerator.getInstance(CIPHER);
    // No need to provide a SecureRandom or set a seed since that will
    // happen automatically.
    keyGen.init(AES_KEY_LENGTH_BITS);
    SecretKey confidentialityKey = keyGen.generateKey();

    //Now make the HMAC key
    byte[] integrityKeyBytes = randomBytes(HMAC_KEY_LENGTH_BITS / 8);//to get bytes
    SecretKey integrityKey = new SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM);

    return new SecretKeys(confidentialityKey, integrityKey);
}
项目:CryptoPayAPI    文件:HttpRest.java   
public static String encrypt(byte[] input, byte[] key){
    byte[] crypted = null;
    try{
        SecretKeySpec skey = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skey);
        crypted = cipher.doFinal(input);
    }catch(Exception e){
        System.out.println(e.toString());
    }
    return new String(Base64.getEncoder().encode(crypted));
}
项目:mesh-core-on-android    文件:AES128.java   
public static byte[] encrypt(byte[] key, byte[] text) throws Exception {      
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");      
    Cipher cipher = Cipher.getInstance("AES");      
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);      
    byte[] encrypted = cipher.doFinal(text);      
    return encrypted;      
}
项目:crypto-utils    文件:AESUtils.java   
/**
 * Creates a new {@link SecretKey} based on a password.
 * 
 * @param password
 *      The password that will be the {@link SecretKey}.
 * 
 * @return The key.
 */
public static SecretKey createKey(String password) {
    try {
        byte[] key = password.getBytes("UTF-8");
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        key = sha.digest(key);
        key = Arrays.copyOf(key, 16); // use only first 128 bit

        return new SecretKeySpec(key, algorithm);
    } catch (Exception ex) {

    }

    return null;
}
项目:spring-backend-boilerplate    文件:HmacUtils.java   
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;
}