Java Code Examples for javax.crypto.spec.IvParameterSpec

The following examples show how to use javax.crypto.spec.IvParameterSpec. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: Library-Assistant   Author: afsalashyana   File: EncryptionUtil.java    License: Apache License 2.0 7 votes vote down vote up
private static String decrypt(byte[] key, byte[] initVector, String encrypted) {
    try {
        IvParameterSpec iv = new IvParameterSpec(initVector);
        SecretKeySpec skeySpec = new SecretKeySpec(key, SECRET_KEY_SPEC);

        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

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

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

    return null;
}
 
Example #2
Source Project: hottub   Author: dsrg-uoft   File: PBKDF2Wrapper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initiate the Cipher object for PBKDF2 algorithm using given "mode".
 *
 * @param mode Cipher mode: encrypt or decrypt
 * @return Cipher object for PBKDF2 algorithm
 * @throws GeneralSecurityException all security exceptions are thrown.
 */
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    // Generate secret key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(),
            salt, DEFAULT_ITERATION, PKDF2_DEFAULT_KEY_LEN);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(baseAlgo);
    SecretKey key = keyFactory.generateSecret(pbeKeySpec);

    // get Cipher instance
    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION, provider);
    cipher.init(mode,
            new SecretKeySpec(key.getEncoded(),KEY_ALGORITHM),
            new IvParameterSpec(iv));
    return cipher;
}
 
Example #3
Source Project: ImitateTaobaoApp   Author: zxuu   File: DESUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * DES算法,加密
 *
 * @param data
 *         待加密字符串
 * @param key
 *            加密私钥,长度不能够小于8位
 * @return 加密后的字节数组,一般结合Base64编码使用

 * @throws Exception
 */
public static String encode(String key, String data) {
    if (data == null)
        return null;
    try {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // key的长度不能够小于8位字节
        Key secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
        IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
        AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        byte[] bytes = cipher.doFinal(data.getBytes());
        return byte2String(bytes);
    } catch (Exception e) {
        e.printStackTrace();
        return data;
    }
}
 
Example #4
Source Project: jdk8u_jdk   Author: JetBrains   File: PBKDF2Wrapper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initiate the Cipher object for PBKDF2 algorithm using given "mode".
 *
 * @param mode Cipher mode: encrypt or decrypt
 * @return Cipher object for PBKDF2 algorithm
 * @throws GeneralSecurityException all security exceptions are thrown.
 */
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    // Generate secret key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(),
            salt, DEFAULT_ITERATION, PKDF2_DEFAULT_KEY_LEN);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(baseAlgo);
    SecretKey key = keyFactory.generateSecret(pbeKeySpec);

    // get Cipher instance
    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION, provider);
    cipher.init(mode,
            new SecretKeySpec(key.getEncoded(),KEY_ALGORITHM),
            new IvParameterSpec(iv));
    return cipher;
}
 
Example #5
Source Project: dragonwell8_jdk   Author: alibaba   File: PBKDF2Wrapper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initiate the Cipher object for PBKDF2 algorithm using given "mode".
 *
 * @param mode Cipher mode: encrypt or decrypt
 * @return Cipher object for PBKDF2 algorithm
 * @throws GeneralSecurityException all security exceptions are thrown.
 */
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    // Generate secret key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(),
            salt, DEFAULT_ITERATION, PKDF2_DEFAULT_KEY_LEN);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(baseAlgo);
    SecretKey key = keyFactory.generateSecret(pbeKeySpec);

    // get Cipher instance
    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION, provider);
    cipher.init(mode,
            new SecretKeySpec(key.getEncoded(),KEY_ALGORITHM),
            new IvParameterSpec(iv));
    return cipher;
}
 
Example #6
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: NativeCipher.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
protected synchronized AlgorithmParameters engineGetParameters() {
    AlgorithmParameters params = null;
    try {
        if (iv != null) {
            IvParameterSpec ivSpec = new IvParameterSpec(iv.clone());
            params = AlgorithmParameters.getInstance(keyAlgo);
            params.init(ivSpec);
        }
    } catch (GeneralSecurityException e) {
        // NoSuchAlgorithmException, NoSuchProviderException
        // InvalidParameterSpecException
        throw new UcryptoException("Could not encode parameters", e);
    }
    return params;
}
 
Example #7
Source Project: j2objc   Author: google   File: PBEParameterSpecTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * getAlgorithmParameterSpec() method testing. Tests that returned value is equal
 * to the value specified in the constructor.
 */
public void testGetAlgorithmParameterSpec() {
    byte[] salt = new byte[] {1, 2, 3, 4, 5};
    int iterationCount = 10;

    // Check that the constructor works with a null AlgorithmParameterSpec and it's correctly
    // returned in the getter.
    PBEParameterSpec pbeps = new PBEParameterSpec(salt, iterationCount, null);
    assertNull("The returned AlgorithmParameterSpec is not null, as the specified "
                    + "in the constructor.",
            pbeps.getParameterSpec());

    // Check that a non-null AlgorithmParameterSpec is returned correctly.
    AlgorithmParameterSpec aps = new IvParameterSpec(new byte[16]);
    pbeps = new PBEParameterSpec(salt, iterationCount, aps);
    assertSame("The returned AlgorithmParameterSpec is not the same as the specified "
                    + "in the constructor.",
            aps, pbeps.getParameterSpec());
}
 
Example #8
Source Project: MicroCommunity   Author: java110   File: AuthenticationFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * DES解密字符串
 *
 * @param password 解密密码,长度不能够小于8位
 * @param data     待解密字符串
 * @return 解密后内容
 */
public static String decrypt(String password, String data) {
    if (password == null || password.length() < 8) {
        throw new RuntimeException("加密失败,key不能小于8位");
    }
    if (data == null)
        return null;
    try {
        Key secretKey = generateKey(password);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET))), CHARSET);
    } catch (Exception e) {
        e.printStackTrace();
        return data;
    }
}
 
Example #9
Source Project: text_converter   Author: tranleduy2000   File: AESObfuscator.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @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);
    }
}
 
Example #10
Source Project: AsuraFramework   Author: AsuraTeam   File: EncryptionUtil.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #11
Source Project: java-unified-sdk   Author: leancloud   File: AES.java    License: Apache License 2.0 6 votes vote down vote up
public AES() {

    try {
      keyfactory = SecretKeyFactory.getInstance(KEY_GENERATION_ALG);
      sk = keyfactory.generateSecret(myKeyspec);

    } catch (NoSuchAlgorithmException nsae) {
      Log.e("no key factory support for PBEWITHSHAANDTWOFISH-CBC");
    } catch (InvalidKeySpecException ikse) {
      Log.e("invalid key spec for PBEWITHSHAANDTWOFISH-CBC");
    }

    // This is our secret key. We could just save this to a file instead of
    // regenerating it
    // each time it is needed. But that file cannot be on the device (too
    // insecure). It could
    // be secure if we kept it on a server accessible through https.
    byte[] skAsByteArray = sk.getEncoded();
    skforAES = new SecretKeySpec(skAsByteArray, "AES");
    IV = new IvParameterSpec(iv);
  }
 
Example #12
Source Project: openjdk-8-source   Author: keerath   File: CipherHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Obtains an initialized DES cipher.
 *
 * @param encryptMode true if encryption is desired, false is decryption
 * is desired.
 * @param key the bytes for the DES key
 * @param ivBytes the initial vector bytes
 */
private final Cipher getInitializedDes(boolean encryptMode, byte[] key,
                                      byte[] ivBytes)
    throws  GSSException  {


    try {
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        SecretKey jceKey = (SecretKey) (new SecretKeySpec(key, "DES"));

        Cipher desCipher = Cipher.getInstance("DES/CBC/NoPadding");
        desCipher.init(
            (encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE),
            jceKey, iv);
        return desCipher;
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example #13
Source Project: jdk8u-dev-jdk   Author: frohoff   File: CipherHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Obtains an initialized DES cipher.
 *
 * @param encryptMode true if encryption is desired, false is decryption
 * is desired.
 * @param key the bytes for the DES key
 * @param ivBytes the initial vector bytes
 */
private final Cipher getInitializedDes(boolean encryptMode, byte[] key,
                                      byte[] ivBytes)
    throws  GSSException  {


    try {
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        SecretKey jceKey = (SecretKey) (new SecretKeySpec(key, "DES"));

        Cipher desCipher = Cipher.getInstance("DES/CBC/NoPadding");
        desCipher.init(
            (encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE),
            jceKey, iv);
        return desCipher;
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example #14
Source Project: cas4.0.x-server-wechat   Author: luotuo   File: EncryptedMapDecorator.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #15
Source Project: web3sdk   Author: FISCO-BCOS   File: Wallet.java    License: Apache License 2.0 6 votes vote down vote up
private static byte[] performCipherOperation(
        int mode, byte[] iv, byte[] encryptKey, byte[] text) throws CipherException {

    try {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

        SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES");
        cipher.init(mode, secretKeySpec, ivParameterSpec);
        return cipher.doFinal(text);
    } catch (NoSuchPaddingException
            | NoSuchAlgorithmException
            | InvalidAlgorithmParameterException
            | InvalidKeyException
            | BadPaddingException
            | IllegalBlockSizeException e) {
        throw new CipherException("Error performing cipher operation", e);
    }
}
 
Example #16
Source Project: Klyph   Author: jonathangerbaud   File: AESObfuscator.java    License: MIT License 6 votes vote down vote up
/**
 * @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);
    }
}
 
Example #17
Source Project: development   Author: servicecatalog   File: AESEncrypter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Encrypts a given string based on a shared secret.
 *
 * @param text
 *            the text to encrypt
 * @return the iv and encrypted text as Base64 separated with ':'.
 * @throws GeneralSecurityException
 *             on any problem during encryption
 */
public static String encrypt(String text) throws GeneralSecurityException {

    if (text == null) {
        return null;
    }

    byte[] decrypted;
    try {
        decrypted = text.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    byte[] iv = new byte[IV_BYTES];
    new SecureRandom().nextBytes(iv);
    IvParameterSpec ivSpec = new IvParameterSpec(iv);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

    byte[] encrypted = cipher.doFinal(decrypted);
    return new String(Base64.encodeBase64(iv)) + ":"
            + new String(Base64.encodeBase64(encrypted));
}
 
Example #18
Source Project: lion   Author: micyo202   File: AESUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * AES 自定义秘钥解密
 *
 * @param ciphertext 密文
 * @param key        秘钥(必须16位)
 * @return 明文
 */
public static String decrypt(String ciphertext, String key) {
    if (StringUtils.isEmpty(ciphertext) || StringUtils.isEmpty(key) || 16 != key.length()) {
        return null;
    }
    try {
        byte[] encryptedBytes = Base64.getDecoder().decode(ciphertext);
        byte[] enCodeFormat = key.getBytes();
        SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, AES);
        byte[] initParam = IV_STRING.getBytes();
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
        Cipher cipher = Cipher.getInstance(CIPHER);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] result = cipher.doFinal(encryptedBytes);
        return new String(result, ENCODEING);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return null;
}
 
Example #19
Source Project: cosmic   Author: MissionCriticalCloud   File: ConsoleProxyPasswordBasedEncryptor.java    License: Apache License 2.0 6 votes vote down vote up
public String encryptText(final String text) {
    if (text == null || text.isEmpty()) {
        return text;
    }

    try {
        final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        final SecretKeySpec keySpec = new SecretKeySpec(this.keyIvPair.getKeyBytes(), "AES");

        cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(this.keyIvPair.getIvBytes()));

        final byte[] encryptedBytes = cipher.doFinal(text.getBytes());

        final byte[] ivcipher = concat(this.keyIvPair.getIvBytes(), encryptedBytes);
        final byte[] hmac = generateHMAC(this.authenticationKey, ivcipher);

        return Base64.encodeBase64URLSafeString(concat(ivcipher, hmac));
    } catch (Exception e) {
        s_logger.error("Unexpected exception ", e);
        return null;
    }
}
 
Example #20
Source Project: dragonwell8_jdk   Author: alibaba   File: CipherHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Obtains an initialized DES cipher.
 *
 * @param encryptMode true if encryption is desired, false is decryption
 * is desired.
 * @param key the bytes for the DES key
 * @param ivBytes the initial vector bytes
 */
private final Cipher getInitializedDes(boolean encryptMode, byte[] key,
                                      byte[] ivBytes)
    throws  GSSException  {


    try {
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        SecretKey jceKey = (SecretKey) (new SecretKeySpec(key, "DES"));

        Cipher desCipher = Cipher.getInstance("DES/CBC/NoPadding");
        desCipher.init(
            (encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE),
            jceKey, iv);
        return desCipher;
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example #21
Source Project: faster-framework-project   Author: faster-framework   File: DesCbcUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *  3DES解密
 * @param encryptText 加密文本
 * @param secretKey 密钥
 * @param iv 向量
 * @return 解密后明文,失败返回null
 */
public static String decode(String encryptText, String secretKey, String iv) {
    String result = null;
    try {
        DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("desede");
        Key desKey = secretKeyFactory.generateSecret(spec);
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, desKey, ips);
        byte[] decryptData = cipher.doFinal(Base64Utils.decodeFromString(encryptText));
        result = new String(decryptData, encoding);
    } catch (Exception e) {
        log.error("DesCbcUtil decode error : {}", e.getMessage());
    }
    return result;
}
 
Example #22
Source Project: ZTuoExchange_framework   Author: sengeiou   File: DESUtil.java    License: MIT License 6 votes vote down vote up
/**
 * DES加密
 * @param HexString 字符串(16位16进制字符串)
 * @param keyStr 密钥16个1
 * @param keyENCODED  Keybyte转换编码
 * @param HexStringENCODED 要加密值的转换byte编码
 * @param CipherInstanceType 需要加密类型
 * @return
 * @throws Exception
 */
public static String ENCRYPTMethod(String HexString, String keyStr,String keyENCODED,String HexStringENCODED,String CipherInstanceType)
		throws Exception {
	String jmstr = "";
	try {
		byte[] theKey = null;
		String jqstr = getstrByte(keyStr).substring(0,8).toUpperCase();
		theKey = jqstr.getBytes(keyENCODED);
		Cipher cipher = Cipher.getInstance(CipherInstanceType);
		DESKeySpec desKeySpec = new DESKeySpec(theKey);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(theKey);
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
		byte[] theCph = cipher.doFinal(HexString.getBytes(HexStringENCODED));
		jmstr = toHexString(theCph).toUpperCase();
		jmstr = toHexString(theCph);
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
	return jmstr;
}
 
Example #23
Source Project: springboot-shiro-cas-mybatis   Author: hsj-xiaokang   File: EncryptedMapDecorator.java    License: MIT License 6 votes vote down vote up
/**
 * Decrypt the value.
 *
 * @param value the value
 * @param hashedKey the hashed key
 * @return the string
 */
protected String decrypt(final String value, final String hashedKey) {
    if (value == null) {
        return null;
    }

    try {
        final Cipher cipher = getCipherObject();
        final byte[] ivCiphertext = CompressionUtils.decodeBase64ToByteArray(value);
        final int ivSize = byte2int(Arrays.copyOfRange(ivCiphertext, 0, INTEGER_LEN));
        final byte[] ivValue = Arrays.copyOfRange(ivCiphertext, INTEGER_LEN, (INTEGER_LEN + ivSize));
        final byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, INTEGER_LEN + ivSize, ivCiphertext.length);
        final IvParameterSpec ivSpec = new IvParameterSpec(ivValue);
        
        cipher.init(Cipher.DECRYPT_MODE, this.key, ivSpec);

        final byte[] plaintext = cipher.doFinal(ciphertext);

        return new String(plaintext, Charset.defaultCharset());
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source Project: TelePlus-Android   Author: TelePlusDev   File: AesFlushingCipher.java    License: GNU General Public License v2.0 6 votes vote down vote up
public AesFlushingCipher(int mode, byte[] secretKey, long nonce, long offset) {
  try {
    cipher = Cipher.getInstance("AES/CTR/NoPadding");
    blockSize = cipher.getBlockSize();
    zerosBlock = new byte[blockSize];
    flushedBlock = new byte[blockSize];
    long counter = offset / blockSize;
    int startPadding = (int) (offset % blockSize);
    cipher.init(
        mode,
        new SecretKeySpec(secretKey, Util.splitAtFirst(cipher.getAlgorithm(), "/")[0]),
        new IvParameterSpec(getInitializationVector(nonce, counter)));
    if (startPadding != 0) {
      updateInPlace(new byte[startPadding], 0, startPadding);
    }
  } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
      | InvalidAlgorithmParameterException e) {
    // Should never happen.
    throw new RuntimeException(e);
  }
}
 
Example #25
Source Project: Alite   Author: CmdrStardust   File: AESObfuscator.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @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);
    }
}
 
Example #26
Source Project: enjoyshop   Author: gaolhjy   File: DESUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * DES算法,加密
 *
 * @param data
 *         待加密字符串
 * @param key
 *            加密私钥,长度不能够小于8位
 * @return 加密后的字节数组,一般结合Base64编码使用

 * @throws Exception
 */
public static String encode(String key, String data) {
    if (data == null)
        return null;
    try {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // key的长度不能够小于8位字节
        Key secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
        IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
        AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        byte[] bytes = cipher.doFinal(data.getBytes());
        return byte2String(bytes);
    } catch (Exception e) {
        e.printStackTrace();
        return data;
    }
}
 
Example #27
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: CipherHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Obtains an initialized DES cipher.
 *
 * @param encryptMode true if encryption is desired, false is decryption
 * is desired.
 * @param key the bytes for the DES key
 * @param ivBytes the initial vector bytes
 */
private final Cipher getInitializedDes(boolean encryptMode, byte[] key,
                                      byte[] ivBytes)
    throws  GSSException  {


    try {
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        SecretKey jceKey = (SecretKey) (new SecretKeySpec(key, "DES"));

        Cipher desCipher = Cipher.getInstance("DES/CBC/NoPadding");
        desCipher.init(
            (encryptMode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE),
            jceKey, iv);
        return desCipher;
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            e.getMessage());
        ge.initCause(e);
        throw ge;
    }
}
 
Example #28
Source Project: Android-InsecureBankv2   Author: dineshshetty   File: CryptoClass.java    License: MIT License 6 votes vote down vote up
public static byte[] aes256decrypt(byte[] ivBytes, byte[] keyBytes, byte[] textBytes)
throws UnsupportedEncodingException,
NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
IllegalBlockSizeException,
BadPaddingException {

	AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
	SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
	Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
	return cipher.doFinal(textBytes);
	
}
 
Example #29
Source Project: Conversations   Author: iNPUTmice   File: XmppAxolotlMessage.java    License: GNU General Public License v3.0 5 votes vote down vote up
public XmppAxolotlPlaintextMessage decrypt(XmppAxolotlSession session, Integer sourceDeviceId) throws CryptoFailedException {
    XmppAxolotlPlaintextMessage plaintextMessage = null;
    byte[] key = unpackKey(session, sourceDeviceId);
    if (key != null) {
        try {
            if (key.length < 32) {
                throw new OutdatedSenderException("Key did not contain auth tag. Sender needs to update their OMEMO client");
            }
            final int authTagLength = key.length - 16;
            byte[] newCipherText = new byte[key.length - 16 + ciphertext.length];
            byte[] newKey = new byte[16];
            System.arraycopy(ciphertext, 0, newCipherText, 0, ciphertext.length);
            System.arraycopy(key, 16, newCipherText, ciphertext.length, authTagLength);
            System.arraycopy(key, 0, newKey, 0, newKey.length);
            ciphertext = newCipherText;
            key = newKey;

            final Cipher cipher = Compatibility.twentyEight() ? Cipher.getInstance(CIPHERMODE) : Cipher.getInstance(CIPHERMODE, PROVIDER);
            SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            String plaintext = new String(cipher.doFinal(ciphertext));
            plaintextMessage = new XmppAxolotlPlaintextMessage(Config.OMEMO_PADDING ? plaintext.trim() : plaintext, session.getFingerprint());

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
                | InvalidAlgorithmParameterException | IllegalBlockSizeException
                | BadPaddingException | NoSuchProviderException e) {
            throw new CryptoFailedException(e);
        }
    }
    return plaintextMessage;
}
 
Example #30
Source Project: DisCal-Discord-Bot   Author: DreamExposure   File: AESEncryption.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Constructor for AESEncryption.
 * This class it to be used for encrypting/decrypting data.
 *
 * @throws Exception if something fails
 */
public AESEncryption(GuildSettings gs) throws Exception {
	String SECRET_KEY_2 = gs.getPrivateKey();
	ivParameterSpec = new IvParameterSpec(SECRET_KEY_1.getBytes(StandardCharsets.UTF_8));
	secretKeySpec = new SecretKeySpec(SECRET_KEY_2.getBytes(StandardCharsets.UTF_8), "AES");
	cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
}