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

项目:pay    文件:AlipayEncrypt.java   
private static String aesEncrypt(String content, String aesKey, String charset)
                                                                               throws AlipayApiException {

    try {
        Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);

        IvParameterSpec iv = new IvParameterSpec(AES_IV);
        cipher.init(Cipher.ENCRYPT_MODE,
            new SecretKeySpec(Base64.decodeBase64(aesKey.getBytes()), AES_ALG), iv);

        byte[] encryptBytes = cipher.doFinal(content.getBytes(charset));
        return new String(Base64.encodeBase64(encryptBytes));
    } catch (Exception e) {
        throw new AlipayApiException("AES加密失败:Aescontent = " + content + "; charset = "
                                     + charset, e);
    }

}
项目: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;
    }
}
项目:Wurst-MC-1.12    文件:Encryption.java   
public Encryption()
{
    KeyPair rsaKeyPair =
        getRsaKeyPair(WurstFolders.RSA.resolve("wurst_rsa.pub"),
            WurstFolders.RSA.resolve("wurst_rsa"));

    SecretKey aesKey =
        getAesKey(WurstFolders.MAIN.resolve("key"), rsaKeyPair);

    try
    {
        encryptCipher = Cipher.getInstance("AES/CFB8/NoPadding");
        encryptCipher.init(Cipher.ENCRYPT_MODE, aesKey,
            new IvParameterSpec(aesKey.getEncoded()));

        decryptCipher = Cipher.getInstance("AES/CFB8/NoPadding");
        decryptCipher.init(Cipher.DECRYPT_MODE, aesKey,
            new IvParameterSpec(aesKey.getEncoded()));

    }catch(GeneralSecurityException e)
    {
        throw new ReportedException(
            CrashReport.makeCrashReport(e, "Creating AES ciphers"));
    }
}
项目: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);
    }
}
项目: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;
}
项目:osc-core    文件:DESDecryption.java   
private String fromEncryptedBytes(byte[] message) throws Exception {

        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("UTF-8"));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        decipher.init(Cipher.DECRYPT_MODE, key, iv);

        final byte[] plainText = decipher.doFinal(message);

        return new String(plainText, "UTF-8");
    }
项目:Server-Quickstart-Vert.x    文件:AES256.java   
public static String decrypt(String str) {
    if (str == null) return null;
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec,
                new IvParameterSpec(ips.getBytes("UTF-8")));

        byte[] byteStr = Base64.decodeBase64(str.getBytes());
        String Str = new String(cipher.doFinal(byteStr), "UTF-8");

        return Str;
    } catch (NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | InvalidAlgorithmParameterException
            | IllegalBlockSizeException | BadPaddingException
            | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}
项目:wolfcrypt-jni    文件:WolfCryptCipher.java   
@Override
protected void engineInit(int opmode, Key key,
        AlgorithmParameters params, SecureRandom random)
    throws InvalidKeyException, InvalidAlgorithmParameterException {

    AlgorithmParameterSpec spec;

    try {

        spec = params.getParameterSpec(IvParameterSpec.class);

        if (debug.DEBUG)
            log("initialized with key and AlgorithmParameters");

    } catch (InvalidParameterSpecException ipe) {
        throw new InvalidAlgorithmParameterException(ipe);
    }

    wolfCryptCipherInit(opmode, key, spec, random);
}
项目:privacyidea-authenticator    文件:ApplicationTest.java   
@Test
public void testEncryptionHelper() throws NoSuchPaddingException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException,
        IllegalBlockSizeException, UnsupportedEncodingException, InvalidAlgorithmParameterException, DecoderException {

    // https://golang.org/src/crypto/cipher/gcm_test.go
    String[][] testCases = new String[][]{
            new String[]{"11754cd72aec309bf52f7687212e8957", "3c819d9a9bed087615030b65", "", "250327c674aaf477aef2675748cf6971"},
            new String[]{"ca47248ac0b6f8372a97ac43508308ed", "ffd2b598feabc9019262d2be", "", "60d20404af527d248d893ae495707d1a"},
            new String[]{"7fddb57453c241d03efbed3ac44e371c", "ee283a3fc75575e33efd4887", "d5de42b461646c255c87bd2962d3b9a2", "2ccda4a5415cb91e135c2a0f78c9b2fdb36d1df9b9d5e596f83e8b7f52971cb3"},
            new String[]{"ab72c77b97cb5fe9a382d9fe81ffdbed", "54cc7dc2c37ec006bcc6d1da", "007c5e5b3e59df24a7c355584fc1518d", "0e1bde206a07a9c2c1b65300f8c649972b4401346697138c7a4891ee59867d0c"},
            new String[]{"feffe9928665731c6d6a8f9467308308", "cafebabefacedbaddecaf888", "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255",
                    "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f59854d5c2af327cd64a62cf35abd2ba6fab4"},
    };
    for (String[] testCase : testCases) {

        SecretKeySpec k = new SecretKeySpec(new Hex().decode(testCase[0].getBytes()), "AES");
        IvParameterSpec iv = new IvParameterSpec(new Hex().decode(testCase[1].getBytes()));

        byte[] cipherTExt = EncryptionHelper.encrypt(k, iv, new Hex().decode(testCase[2].getBytes()));
        String cipher = new String(new Hex().encode(cipherTExt));

        assertEquals(cipher, testCase[3]);
        assertEquals(testCase[2], new String(new Hex().encode(EncryptionHelper.decrypt(k, iv, cipherTExt))));
    }
}
项目: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);
    }
项目:LogiGSK    文件:Encryption.java   
public static String encrypt(String decryptedString, String password) {
    try {
        // build the initialization vector (randomly).
        SecureRandom random = new SecureRandom();
        byte initialVector[] = new byte[16];
        //generate random 16 byte IV AES is always 16bytes
        random.nextBytes(initialVector);
        IvParameterSpec ivspec = new IvParameterSpec(initialVector);
        SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
        byte[] encrypted = cipher.doFinal(decryptedString.getBytes());
        byte[] encryptedWithIV = new byte[encrypted.length + initialVector.length];
        System.arraycopy(encrypted, 0, encryptedWithIV, 0, encrypted.length);
        System.arraycopy(initialVector, 0, encryptedWithIV, encrypted.length, initialVector.length);
        return Base64.encodeBase64String(encryptedWithIV);
    } catch (Exception ex) {
        Logger.getLogger(Encryption.class.getName()).log(Level.SEVERE, null, ex);
        return "Error";
    }
}
项目: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");
}
项目:Encryption    文件:Blowfish.java   
/**
     * Implementation of Blowfish decryption
     */
    public static String decrypt(String method, byte[] key, int keySize, byte[] vector, byte[] message) throws Exception {

//        generate Key
        byte[] keyBytes = generateKey(key, keySize);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, AES.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);
    }
项目:Daejeon-People    文件:AES.java   
public static String encrypt(String str) {
    if (str == null) return null;
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec,
                new IvParameterSpec(ips.getBytes("UTF-8")));

        byte[] encrypted = cipher.doFinal(str.getBytes("UTF-8"));
        String Str = new String(Base64.encodeBase64(encrypted));
        return Str;
    } catch (NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | InvalidAlgorithmParameterException
            | IllegalBlockSizeException | BadPaddingException
            | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}
项目:AirPlayAuth    文件:AirPlayAuth.java   
private void doPairVerify2(Socket socket, byte[] pairVerify1Response, byte[] randomPrivateKey, byte[] randomPublicKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException, InvalidAlgorithmParameterException, SignatureException {
    byte[] atvPublicKey = Arrays.copyOfRange(pairVerify1Response, 0, 32);
    byte[] sharedSecret = new byte[32];
    Curve25519.curve(sharedSecret, randomPrivateKey, atvPublicKey);

    MessageDigest sha512Digest = MessageDigest.getInstance("SHA-512");
    sha512Digest.update("Pair-Verify-AES-Key".getBytes(StandardCharsets.UTF_8));
    sha512Digest.update(sharedSecret);
    byte[] sharedSecretSha512AesKey = Arrays.copyOfRange(sha512Digest.digest(), 0, 16);

    sha512Digest.update("Pair-Verify-AES-IV".getBytes(StandardCharsets.UTF_8));
    sha512Digest.update(sharedSecret);
    byte[] sharedSecretSha512AesIV = Arrays.copyOfRange(sha512Digest.digest(), 0, 16);

    Cipher aesCtr128Encrypt = Cipher.getInstance("AES/CTR/NoPadding");
    aesCtr128Encrypt.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(sharedSecretSha512AesKey, "AES"), new IvParameterSpec(sharedSecretSha512AesIV));

    aesCtr128Encrypt.update(Arrays.copyOfRange(pairVerify1Response, 32, pairVerify1Response.length));

    EdDSAEngine edDSAEngine = new EdDSAEngine();
    edDSAEngine.initSign(authKey);

    byte[] signature = aesCtr128Encrypt.update(edDSAEngine.signOneShot(AuthUtils.concatByteArrays(randomPublicKey, atvPublicKey)));

    AuthUtils.postData(socket, "/pair-verify", "application/octet-stream", AuthUtils.concatByteArrays(new byte[]{0, 0, 0, 0}, signature));
}
项目:spring-data-mongodb-encrypt    文件:CryptVault.java   
public byte[] encrypt(int version, byte[] data) {
    CryptVersion cryptVersion = cryptVersion(version);
    try {
        int cryptedLength = cryptVersion.encryptedLength.apply(data.length);
        byte[] result = new byte[cryptedLength + cryptVersion.saltLength + 1];
        result[0] = toSignedByte(version);

        byte[] random = urandomBytes(cryptVersion.saltLength);
        IvParameterSpec iv_spec = new IvParameterSpec(random);
        System.arraycopy(random, 0, result, 1, cryptVersion.saltLength);

        Cipher cipher = cipher(cryptVersion.cipher);
        cipher.init(Cipher.ENCRYPT_MODE, cryptVersion.key, iv_spec);
        int len = cipher.doFinal(data, 0, data.length, result, cryptVersion.saltLength + 1);

        if (len < cryptedLength) LOG.info("len was " + len + " instead of " + cryptedLength);

        return result;
    } catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) {
        throw new RuntimeException("JCE exception caught while encrypting with version " + version, e);
    }
}
项目:asura    文件:EncryptionUtil.java   
public static String DESDecrypt(String ivString, String keyString, String content) {
    try {
        if (Check.NuNStr(content)) {
            return null;
        }
        IvParameterSpec iv = new IvParameterSpec(ivString.getBytes());
        DESKeySpec dks = new DESKeySpec(keyString.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] result = cipher.doFinal(hexStr2ByteArr(content));
        return new String(result, "utf-8");
    } catch (Exception e) {
        LOGGER.error("ENCRYPT ERROR:"+e);
    }
    return null;
}
项目:springboot-shiro-cas-mybatis    文件:EncryptedMapDecorator.java   
/**
 * Encrypt.
 *
 * @param value the value
 * @param hashedKey the hashed key
 * @return the string
 */
protected String encrypt(final String value, final String hashedKey) {
    if (value == null) {
        return null;
    }

    try {
        final Cipher cipher = getCipherObject();
        final byte[] ivValue = generateIV(this.ivSize);
        final IvParameterSpec ivSpec = new IvParameterSpec(ivValue);

        cipher.init(Cipher.ENCRYPT_MODE, this.key, ivSpec);

        final byte[] ciphertext = cipher.doFinal(value.getBytes(Charset.defaultCharset()));
        final byte[] ivCiphertext = new byte[INTEGER_LEN + this.ivSize + ciphertext.length];

        System.arraycopy(int2byte(this.ivSize), 0, ivCiphertext, 0, INTEGER_LEN);
        System.arraycopy(ivValue, 0, ivCiphertext, INTEGER_LEN, this.ivSize);
        System.arraycopy(ciphertext, 0, ivCiphertext, INTEGER_LEN + this.ivSize, ciphertext.length);

        return CompressionUtils.encodeBase64(ivCiphertext);
    } catch(final Exception e) {
        throw new RuntimeException(e);
    }
}
项目:SmartChart    文件:AES.java   
/**
 * 通过String类型的密钥 解密String类型的密文
 *
 * @param content
 * @param key
 * @return
 */
public static String decrypt(String content, String key, IvParameterSpec iv) {
    String decryptedText = null;
    try {
        Cipher cipher = Cipher.getInstance(CipherMode);
        SecretKeySpec keySpec = new SecretKeySpec(Base64.decode(key, Base64.DEFAULT), "AES");
        if (null == iv) {
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);
        }
        byte[] result = cipher.doFinal(Base64.decode(content, Base64.DEFAULT));
        decryptedText = new String(result, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return decryptedText;
}
项目:asura    文件:EncryptionUtil.java   
/**
 * DES加密
 *
 * @param content
 * @return
 */
public static String DESEncrypt(String ivString, String keyString, String content) {
    try {
        if (Check.NuNStr(content)) {
            return null;
        }
        IvParameterSpec iv = new IvParameterSpec(ivString.getBytes());
        DESKeySpec dks = new DESKeySpec(keyString.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        byte[] result = cipher.doFinal(content.getBytes("utf-8"));
        return byteArr2HexStr(result);
    } catch (Exception e) {
        LOGGER.error("ENCRYPT ERROR:"+e);
    }
    return null;
}
项目:unity-obb-downloader    文件: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);
    }
}
项目:ibm-cos-sdk-java    文件:ContentCryptoScheme.java   
/**
 * Creates and initializes a {@link CipherLite} for content
 * encrypt/decryption.
 * 
 * @param cek
 *            content encrypting key
 * @param iv
 *            initialization vector
 * @param cipherMode
 *            such as {@link Cipher#ENCRYPT_MODE}
 * @param securityProvider
 *            optional security provider to be used but only if there is no
 *            specific provider defined for the specified scheme.
 * @return the cipher lite created and initialized.
 */
CipherLite createCipherLite(SecretKey cek, byte[] iv, int cipherMode,
        Provider securityProvider) {
    String specificProvider = getSpecificCipherProvider();
    Cipher cipher;
    try {
        if (specificProvider != null) { // use the specific provider if defined
                cipher = Cipher.getInstance(getCipherAlgorithm(), specificProvider);
        } else if (securityProvider != null) { // use the one optionally specified in the input
            cipher = Cipher.getInstance(getCipherAlgorithm(), securityProvider);
        } else { // use the default provider
            cipher = Cipher.getInstance(getCipherAlgorithm());
        }
        cipher.init(cipherMode, cek, new IvParameterSpec(iv));
        return newCipherLite(cipher, cek, cipherMode);
    } catch (Exception e) {
        throw e instanceof RuntimeException
            ? (RuntimeException) e
            : new SdkClientException(
                "Unable to build cipher: "
                    + e.getMessage()
                    + "\nMake sure you have the JCE unlimited strength policy files installed and "
                    + "configured for your JVM",
                e);
    }
}
项目:automatic-mower    文件:PasswordDecrypt.java   
/**
 * Descrypt a password using a random key
 * @param key
 * @param secureRandom
 * @param encrypted
 * @return descrypted password
 */
public String decrypt(String key, String secureRandom, String encrypted) {
    try {
        SettingInterface defaultSettingLoader = SettingLoaderFactory.getSettingLoader("default");
        IvParameterSpec ivParam = new IvParameterSpec(secureRandom.getBytes(defaultSettingLoader.getEncoding()));
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(defaultSettingLoader.getEncoding()), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParam);

        byte[] passsword = cipher.doFinal(Base64.decodeBase64(encrypted));

        return new String(passsword);
    } catch (Exception ex) {
        throw new MowerException(WRONG_PASSWORD);
    }
}
项目:stynico    文件:AESUtil.java   
/**
 * 加密
 *
 * @param sSrc 加密源
 * @param sKey 加密的key
 * @return 加密后内容
 * @throws Exception
 */
public static String encrypt(String sSrc, String sKey) throws Exception {

    if (sKey == null) {
        //Log.e("Key为空null", "Key为空null");
        return null;
    }
    // 判断Key是否为16位
    if (sKey.length() != 16) {
        //Log.e("\"Key长度不是16位\"", "Key长度不是16位");
        return null;
    }
    byte[] raw = sKey.getBytes();
    SecretKeySpec sKeySpec = new SecretKeySpec(raw, "AESUtil");
    Cipher cipher = Cipher.getInstance("AESUtil/CBC/PKCS5Padding");//"算法/模式/补码方式"
    IvParameterSpec iv = new IvParameterSpec("1234567890123456".getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
    cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, iv);
    byte[] encrypted = cipher.doFinal(sSrc.getBytes());

    return Base64_2Util.encode(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
项目:Encryption    文件:PBE.java   
/**
     * Implementation of PBE decryption
     */
    public static String decrypt(Method method, byte[] key, KeySize keySize, byte[] vector, byte[] message) throws Exception {

//        generate Key
        byte[] keyBytes = generateKey(key, keySize.getSize());
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, method.getMethod());

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

        Cipher cipher = Cipher.getInstance(method.getMethod());

        if (hasInitVector(method.getMethod())) {
            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);
    }
项目:raven    文件:AESUtils.java   
public static String encryptCbcTemp(String content, String encryptKey)
        throws EncryptException
{
    if (StringUtils.isEmpty(content) || StringUtils.isEmpty(encryptKey))
    {
        return null;
    }

    // 因为加密key必须为16位
    if(encryptKey.length() > 16)
    {
        encryptKey = encryptKey.substring(0, 16);
    }
    else
    {
        int padLength = 16-encryptKey.length();

        for(int i = 0; i < padLength ;i++)
        {
            encryptKey += '0';
        }
    }

    try
    {
        IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
        SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] encryptedData = cipher.doFinal(content.getBytes("utf-8"));

        return Base64.encodeBase64String(encryptedData);
    }
    catch (Exception e)
    {
        throw new EncryptException("Failed to encrypt for content: "
                + content + ", encrypt key: " + encryptKey, e);
    }

}
项目:azeroth    文件:DES.java   
/**
 * DES算法,加密
 *
 * @param data 待加密字符串
 * @param key  加密私钥,长度不能够小于8位
 * @return 加密后的字节数组,一般结合Base64编码使用
 * @throws InvalidAlgorithmParameterException
 * @throws Exception
 */
public static String encrypt(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);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(IV_PARAMS_BYTES);
        ;
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        byte[] bytes = cipher.doFinal(data.getBytes());
        return byte2hex(bytes);
    } catch (Exception e) {
        e.printStackTrace();
        return data;
    }
}
项目:batch-scheduler    文件:CryptoAES.java   
/**
     * AES加密字符串
     *
     * @param content 需要被加密的字符串
     * @return 密文
     */
    public String aesDecrypt(String content) {
        try {

            byte[] encrypted1 = Base64.decodeBase64(content);

//            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(content);

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keyspec = new SecretKeySpec(PASSWORD_KEY.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(PASSWORD_KEY.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            String originalString = new String(cipher.doFinal(encrypted1));
            int length = originalString.length();
            int ch = originalString.charAt(length - 1);
            return originalString.substring(0, length - ch);
        } catch (Exception e) {
            logger.error("aesDecrypt failure ,error message is:{}", e.getMessage());
        }
        return null;
    }
项目:DMS    文件:AES256.java   
public String decrypt(String str) {
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec,
                new IvParameterSpec(ips.getBytes("UTF-8")));

        byte[] byteStr = Base64.decodeBase64(str.getBytes());
        String Str = new String(cipher.doFinal(byteStr), "UTF-8");

        return Str;
    } catch (NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | InvalidAlgorithmParameterException
            | IllegalBlockSizeException | BadPaddingException
            | UnsupportedEncodingException e) {
    }
    return null;
}
项目:asura    文件:DESEncrypt.java   
public static String DESDecrypt(final String ivString, final String keyString, final String content) {
    try {
        if (Check.isNullOrEmpty(content)) {
            return null;
        }
        IvParameterSpec iv = new IvParameterSpec(ivString.getBytes());
        DESKeySpec dks = new DESKeySpec(keyString.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] result = cipher.doFinal(hexStr2ByteArr(content));
        return new String(result, "utf-8");
    } catch (Exception e) {
        LOGGER.error("ENCRYPT ERROR:" + e);
    }
    return null;
}
项目:Encryption    文件:PBE.java   
/**
     * Implementation of PBE encryption
     */
    public static String encrypt(Method method, byte[] key, KeySize keySize, byte[] vector, byte[] message) throws Exception{

//        generate Key
        byte[] keyBytes = generateKey(key, keySize.getSize());
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes , method.getMethod());

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

        Cipher cipher = Cipher.getInstance(method.getMethod());

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

        byte[] cipherText = cipher.doFinal(message);

        return Base64.encodeToString(cipherText, Base64.DEFAULT);
    }
项目:Sense-Hub-Android-Things    文件:BroadlinkConnector.java   
public PacketData encrypt(PacketData input){
    PacketData output = null;
    try {
        IvParameterSpec iv = new IvParameterSpec(mIV);
        SecretKeySpec skeySpec = new SecretKeySpec(mKey, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        Log.d(TAG, "encrypt - before - length=" + input.getLength());

        byte[] encrypted = cipher.doFinal(input.getBuffer());
        System.out.println("encrypted string: "
                + Base64.encodeBase64String(encrypted));
        Log.d(TAG, "encrypt - after - length=" + input.getLength());
        output = new PacketData(encrypted, encrypted.length);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return output;
}
项目:MVVMFrames    文件:AES.java   
/**
 * 加密
 *
 * @throws Exception
 */
public static String Encrypt(String sSrc, String sKey) throws Exception {

    if (sKey == null) {
        Log.e("Key为空null", "Key为空null");
        return null;
    }
    // 判断Key是否为16位
    if (sKey.length() != 16) {
        Log.e("\"Key长度不是16位\"", "Key长度不是16位");
        return null;
    }
    byte[] raw = sKey.getBytes();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
    IvParameterSpec iv = new IvParameterSpec("1234567890123456".getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
    byte[] encrypted = cipher.doFinal(sSrc.getBytes());

    return encode(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
项目:osc-core    文件:AESCTREncryption.java   
public String decrypt(String cipherText) throws EncryptionException {
    if(StringUtils.isBlank(cipherText)) {
        return cipherText;
    }

    try {
        String[] params = cipherText.split(":");
        byte[] iv = DatatypeConverter.parseHexBinary(params[IV_INDEX]);
        byte[] hash = DatatypeConverter.parseHexBinary(params[AES_INDEX]);

        SecretKey key = new SecretKeySpec(DatatypeConverter.parseHexBinary(keyProvider.getKeyHex()), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance(AESCTR_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        byte[] result = cipher.doFinal(DatatypeConverter.parseHexBinary(DatatypeConverter.printHexBinary(hash)));

        return new String(result, "UTF-8");
    } catch (Exception ex) {
        LOG.error("Error decrypting message", ex);
        throw new EncryptionException("Failed to decrypt cipher with AES-CTR", ex);
    }
}
项目:cas4.0.x-server-wechat    文件:EncryptedMapDecorator.java   
protected String encrypt(final String value, final String hashedKey) {
    if (value == null) {
        return null;
    }

    try {
        final Cipher cipher = getCipherObject();
        final byte[] ivValue = generateIV(this.ivSize);
        final IvParameterSpec ivSpec = new IvParameterSpec(ivValue);

        cipher.init(Cipher.ENCRYPT_MODE, this.key, ivSpec);

        final byte[] ciphertext = cipher.doFinal(value.getBytes());
        final byte[] ivCiphertext = new byte[INTEGER_LEN + this.ivSize + ciphertext.length];

        System.arraycopy(int2byte(this.ivSize), 0, ivCiphertext, 0, INTEGER_LEN);
        System.arraycopy(ivValue, 0, ivCiphertext, INTEGER_LEN, this.ivSize);
        System.arraycopy(ciphertext, 0, ivCiphertext, INTEGER_LEN + this.ivSize, ciphertext.length);

        return new String(encode(ivCiphertext));
    } catch(final Exception e) {
        throw new RuntimeException(e);
    }
}
项目:pivaa    文件:Encryption.java   
/**
 * Decrypt DATA
 * @param encryptedBase64
 * @return
 */
public static String decryptAES_ECB_PKCS5Padding(String encryptedBase64) {
    try {
        byte[] IV = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        IvParameterSpec iv = new IvParameterSpec(IV);

        byte[] key = {
                1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1
        };
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);

        Base64 b64 = new Base64();
        byte[] encryptedBase64Bytes = encryptedBase64.getBytes();
        byte[] original = cipher.doFinal(b64.decodeBase64(encryptedBase64Bytes));

        return new String(original);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return null;
}
项目:boohee_v5.6    文件:a.java   
public static byte[] b(SecretKeySpec secretKeySpec, byte[] bArr, byte[] bArr2) {
    Cipher instance = Cipher.getInstance("AES/CBC/PKCS7Padding");
    instance.init(2, secretKeySpec, new IvParameterSpec(bArr));
    byte[] doFinal = instance.doFinal(bArr2);
    a("decryptedBytes", doFinal);
    return doFinal;
}
项目:OpenJSharp    文件:CipherBox.java   
static CipherBox newCipherBox(ProtocolVersion version, BulkCipher cipher,
        SecretKey key, IvParameterSpec iv, SecureRandom random,
        boolean encrypt) throws NoSuchAlgorithmException {
    if (cipher.allowed == false) {
        throw new NoSuchAlgorithmException("Unsupported cipher " + cipher);
    }

    if (cipher == B_NULL) {
        return NULL;
    } else {
        return new CipherBox(version, cipher, key, iv, random, encrypt);
    }
}
项目:raven    文件:DESUtils.java   
/**
 * 
 * (根据CBC 加密模式、指定加密key输出对应的BASE64编码解密串)<br>
 *
 * @param content
 * @param decryptKey
 * @return
 * @throws Exception
 * String
 * @Author fanyaowu
 * @data 2015年2月2日
 * @exception 
 * @version
 *
 */
public static String decryptByCBC(String content, String decryptKey) throws Exception
{
    try
    {
        DESKeySpec dks = new DESKeySpec(decryptKey.getBytes());

        // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ENCRYPT_TYPE);

        SecretKey secretKey = keyFactory.generateSecret(dks);

        // using DES in CBC mode
        Cipher cipher = Cipher.getInstance(CBC_ALGORITHM);

        // 用密匙初始化Cipher对象
        IvParameterSpec param = new IvParameterSpec(iv);

        cipher.init(Cipher.DECRYPT_MODE, secretKey, param);

        // 正式执行解密操作
        byte decryptedData[] = cipher.doFinal(Base64.decodeBase64(content));

        return new String(decryptedData);

    }
    catch (Exception e)
    {
        throw new EncryptException("Failed to encrypt for content: "
                + content + ", encrypt key: " + decryptKey, e);
    }
}
项目:belling-spring-rabbitmq    文件:ThreeDesUtils.java   
/**
 * 3DES加密
 * 
 * @param plainText 普通文本 pk 密钥
 * @return 加密的结果
 * @throws Exception 
 */
public static String desEncode(String plainText,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.ENCRYPT_MODE, deskey, ips);
    byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
    return Bytes2HexString(encryptData);
}