javax.crypto.Cipher Java Examples

The following examples show how to use javax.crypto.Cipher. 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 File: Crypto.java    From Image-Steganography-Library-Android with MIT License 8 votes vote down vote up
public static String decryptMessage(String encrypted_message, String secret_key) throws Exception {

        Log.d("Decrypt", "message: + " + encrypted_message);
        // Creating key and cipher
        SecretKeySpec aesKey = new SecretKeySpec(secret_key.getBytes(), "AES");
        Cipher cipher;

        //AES cipher
        cipher = Cipher.getInstance("AES");

        // decrypting the text
        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        String decrypted;
        byte[] decoded;
        decoded = android.util.Base64.decode(encrypted_message.getBytes(), 0);
        decrypted = new String(cipher.doFinal(decoded));

        //returning decrypted text
        return decrypted;
    }
 
Example #2
Source File: DesUtil.java    From javabase with Apache License 2.0 6 votes vote down vote up
/**
 * Description 根据键值进行加密
 * @param data
 * @param key  加密键byte数组
 * @return
 * @throws Exception
 */
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
	// 生成一个可信任的随机数源
	SecureRandom sr = new SecureRandom();
	
	// 从原始密钥数据创建DESKeySpec对象
	DESKeySpec dks = new DESKeySpec(key);
	
	// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
	SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
	SecretKey securekey = keyFactory.generateSecret(dks);
	
	// Cipher对象实际完成加密操作
	Cipher cipher = Cipher.getInstance(DES);
	
	// 用密钥初始化Cipher对象
	cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
	
	return cipher.doFinal(data);
}
 
Example #3
Source File: AesCbcWithIntegrity.java    From java-aes-crypto with MIT License 6 votes vote down vote up
/**
 * Generates a random IV and encrypts this plain text with the given key. Then attaches
 * a hashed MAC, which is contained in the CipherTextIvMac class.
 *
 * @param plaintext The text that will be encrypted
 * @param secretKeys The combined AES and HMAC keys with which to encrypt
 * @return a tuple of the IV, ciphertext, mac
 * @throws GeneralSecurityException if AES is not implemented on this system
 */
public static CipherTextIvMac encrypt(byte[] plaintext, SecretKeys secretKeys)
        throws GeneralSecurityException {
    byte[] iv = generateIv();
    Cipher aesCipherForEncryption = Cipher.getInstance(CIPHER_TRANSFORMATION);
    aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKeys.getConfidentialityKey(), new IvParameterSpec(iv));

    /*
     * Now we get back the IV that will actually be used. Some Android
     * versions do funny stuff w/ the IV, so this is to work around bugs:
     */
    iv = aesCipherForEncryption.getIV();
    byte[] byteCipherText = aesCipherForEncryption.doFinal(plaintext);
    byte[] ivCipherConcat = CipherTextIvMac.ivCipherConcat(iv, byteCipherText);

    byte[] integrityMac = generateMac(ivCipherConcat, secretKeys.getIntegrityKey());
    return new CipherTextIvMac(byteCipherText, iv, integrityMac);
}
 
Example #4
Source File: CipherStreamClose.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static byte[] streamEncrypt(String message, SecretKey key,
    MessageDigest digest)
    throws Exception {

    byte[] data;
    Cipher encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    encCipher.init(Cipher.ENCRYPT_MODE, key);
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DigestOutputStream dos = new DigestOutputStream(bos, digest);
        CipherOutputStream cos = new CipherOutputStream(dos, encCipher)) {
        try (ObjectOutputStream oos = new ObjectOutputStream(cos)) {
            oos.writeObject(message);
        }
        data = bos.toByteArray();
    }

    if (debug) {
        System.out.println(DatatypeConverter.printHexBinary(data));
    }
    return data;
}
 
Example #5
Source File: LogFile.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
void writeEntry(@NonNull String entry) throws IOException {
  new SecureRandom().nextBytes(ivBuffer);

  byte[] plaintext = entry.getBytes();
  try {
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secret, "AES"), new IvParameterSpec(ivBuffer));

    int    cipherLength = cipher.getOutputSize(plaintext.length);
    byte[] ciphertext   = ciphertextBuffer.get(cipherLength);
    cipherLength = cipher.doFinal(plaintext, 0, plaintext.length, ciphertext);

    outputStream.write(ivBuffer);
    outputStream.write(Conversions.intToByteArray(cipherLength));
    outputStream.write(ciphertext, 0, cipherLength);

    outputStream.flush();
  } catch (ShortBufferException | InvalidAlgorithmParameterException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
    throw new AssertionError(e);
  }
}
 
Example #6
Source File: SimpleCredentialsConfig.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypts the given string in a fairly secure way so that it can be
 * {@link #decrypt(String) decrypted} again.
 *
 * @param s string to encrypt
 * @return the encrypted string with a "{AES}" prefix.
 */
private static String encrypt(String s) {
    try {
        SecretKey key = KeyGenerator.getInstance("DES").generateKey();
        Cipher cipher = Cipher.getInstance("DES");
        byte[] keyBytes = key.getEncoded();
        byte[] data = s.getBytes("utf-8");
        ByteArrayOutputStream out = new ByteArrayOutputStream(keyBytes.length + data.length);
        out.write(keyBytes);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        out.write(cipher.update(data));
        out.write(cipher.doFinal());
        StringBuilder ret = new StringBuilder(PREFIX);
        for (byte b: out.toByteArray()) {
            ret.append(Text.hexTable[b>>4 & 0x0f]).append(Text.hexTable[b&0x0f]);
        }
        return ret.toString();
    } catch (Exception e) {
        log.warn("Unable to encrypt string: " + e);
        return null;
    }
}
 
Example #7
Source File: ExtendedKey.java    From bop-bitcoin-client with Apache License 2.0 6 votes vote down vote up
public byte[] encrypt (String passphrase, boolean production) throws ValidationException
{
	try
	{
		byte[] key = SCrypt.generate (passphrase.getBytes ("UTF-8"), BITCOIN_SEED, 16384, 8, 8, 32);
		SecretKeySpec keyspec = new SecretKeySpec (key, "AES");
		Cipher cipher = Cipher.getInstance ("AES/CBC/PKCS5Padding", "BC");
		cipher.init (Cipher.ENCRYPT_MODE, keyspec);
		byte[] iv = cipher.getIV ();
		byte[] c = cipher.doFinal (serialize (production).getBytes ());
		byte[] result = new byte[iv.length + c.length];
		System.arraycopy (iv, 0, result, 0, iv.length);
		System.arraycopy (c, 0, result, iv.length, c.length);
		return result;
	}
	catch ( UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException
			| IllegalBlockSizeException | BadPaddingException e )
	{
		throw new ValidationException (e);
	}
}
 
Example #8
Source File: WrongAAD.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void decryptWithWrongAAD() throws Exception {
    System.out.println("decrypt with wrong AAD");

    // initialize it with wrong AAD to get an exception during decryption
    Cipher decryptCipher = createCipher(Cipher.DECRYPT_MODE,
            encryptCipher.getParameters());
    byte[] someAAD = Helper.generateBytes(AAD_SIZE + 1);
    decryptCipher.updateAAD(someAAD);

    // init output stream
    try (ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput,
                    decryptCipher);) {
        if (decrypt(ciOutput, baOutput)) {
            throw new RuntimeException(
                    "A decryption has been perfomed successfully in"
                            + " spite of the decrypt Cipher has been"
                            + " initialized with fake AAD");
        }
    }

    System.out.println("Passed");
}
 
Example #9
Source File: CryptVault.java    From spring-data-mongodb-encrypt with Apache License 2.0 6 votes vote down vote up
public byte[] decrypt(byte[] data) {
    int version = fromSignedByte(data[0]);
    CryptVersion cryptVersion = cryptVersion(version);

    try {
        byte[] random = new byte[cryptVersion.saltLength];
        System.arraycopy(data, 1, random, 0, cryptVersion.saltLength);
        IvParameterSpec iv_spec = new IvParameterSpec(random);

        Cipher cipher = cipher(cryptVersions[version].cipher);
        cipher.init(Cipher.DECRYPT_MODE, cryptVersions[version].key, iv_spec);
        return cipher.doFinal(data, cryptVersion.saltLength + 1, data.length - cryptVersion.saltLength - 1);
    } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
        // wrap checked exception for easy use
        throw new CryptOperationException("JCE exception caught while decrypting with key version " + version, e);
    }
}
 
Example #10
Source File: Passphrase.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
public static byte[] decrypt(Passphrase passphrase, byte[] encryptedData) throws Exception {
	if (encryptedData.length == 0) {
		return new byte[0];
	}
	byte[] byteHolder1;
	byte[] byteHolder2 = null;
	try {
		List<Cipher> ciphers = cipherList(passphrase.getPassphraseHash(), Cipher.DECRYPT_MODE);
		byteHolder1 = ciphers.get(2).doFinal(encryptedData);
		byteHolder2 = ciphers.get(1).doFinal(byteHolder1);
		byteHolder1 = ciphers.get(0).doFinal(byteHolder2);
		byteHolder2 = unPad4AES(byteHolder1);
	} catch (Exception ex) {
		ex.printStackTrace();
	}
	return byteHolder2;
}
 
Example #11
Source File: CipherInputStreamExceptions.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static void gcm_suppressUnreadCorrupt() throws Exception {
    Cipher c;
    byte[] read = new byte[200];

    System.out.println("Running supressUnreadCorrupt test");

    // Encrypt 100 bytes with AES/GCM/PKCS5Padding
    byte[] ct = encryptedText("GCM", 100);
    // Corrupt the encrypted message
    ct = corruptGCM(ct);
    // Create stream for decryption
    CipherInputStream in = getStream("GCM", ct);

    try {
        in.close();
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail: " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example #12
Source File: StaticDESPasswordCipher.java    From tomee with Apache License 2.0 6 votes vote down vote up
/**
 * @throws RuntimeException in any case of error.
 * @see org.apache.openejb.cipher.PasswordCipher#decrypt(char[])
 */
public String decrypt(final char[] encodedPassword) {
    if (null == encodedPassword || encodedPassword.length == 0) {
        throw new IllegalArgumentException("encodedPassword cannot be null nor empty.");
    }

    try {
        final byte[] cipherText = Base64.decodeBase64(
            String.valueOf(encodedPassword).getBytes());

        // Get a 3DES Cipher object
        final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        // Set it into decryption mode
        cipher.init(Cipher.DECRYPT_MODE, KEY);

        // Decrypt data
        return new String(cipher.doFinal(cipherText));

    } catch (final Exception e) {
        throw new OpenEJBRuntimeException(e);
    }
}
 
Example #13
Source File: ENCRYPT1_4.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
@Override // GemStoneAddition
public void init() throws Exception {
    // generate keys according to the specified algorithms
    // generate publicKey and Private Key using RSA
    KeyPairGenerator KpairGen=KeyPairGenerator.getInstance(getAlgorithm(asymAlgorithm));
    KpairGen.initialize(asymInit, new SecureRandom());
    Kpair=KpairGen.generateKeyPair();

    // generate secret key
    KeyGenerator keyGen=KeyGenerator.getInstance(getAlgorithm(symAlgorithm));
    keyGen.init(symInit);
    desKey=keyGen.generateKey();

    // initialize for rsa, cipher encryption/decryption
    rsa=Cipher.getInstance(asymAlgorithm);
    cipher=Cipher.getInstance(symAlgorithm);


 if(log.isInfoEnabled()) log.info(ExternalStrings.ENCRYPT1_4_BOTH_ASYM_AND_SYM_ALGO_INITIALIZED_WITH_THE_SINGLE_SHARED_KEY);
}
 
Example #14
Source File: DESEncrypt.java    From SprintNBA with Apache License 2.0 6 votes vote down vote up
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 byte2hex(bytes);
    } catch (Exception e) {
        e.printStackTrace();
        return data;
    }
}
 
Example #15
Source File: SameBuffer.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void runGCMWithSameArray(int mode, byte[] array, int txtOffset,
        int length, AlgorithmParameters params) throws Exception {
    // first, generate cipher text at an allocated buffer
    Cipher cipher = createCipher(mode, params);
    cipher.updateAAD(array, 0, AADLength);
    byte[] outputText = cipher.doFinal(array, txtOffset, length);

    // new cipher for encrypt operation
    Cipher anotherCipher = createCipher(mode, params);
    anotherCipher.updateAAD(array, 0, AADLength);

    // next, generate cipher text again at the same buffer of plain text
    int off = anotherCipher.update(array, txtOffset, length,
            array, txtOffset);
    anotherCipher.doFinal(array, txtOffset + off);

    // check if two results are equal or not
    if (!isEqual(array, txtOffset, outputText, 0,
            outputText.length)) {
        throw new RuntimeException(
                "Two results are not equal, mode:" + mode);
    }
}
 
Example #16
Source File: VGV4dEVuY3J5cHRpb24.java    From InjuredAndroid with Apache License 2.0 6 votes vote down vote up
public static String encrypt(String value) {
    try {
        System.out.println(KEY);
        DESKeySpec keySpec = new DESKeySpec(KEY);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        byte[] clearText = value.getBytes("UTF8");
        // Implement this in a thread safe way, or switch to AES.
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        String encrypedText = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT);
        Log.d("Oh snap!", "Encrypted: " + value + " -> " + encrypedText);
        return encrypedText;

    } catch (InvalidKeyException | UnsupportedEncodingException | InvalidKeySpecException | NoSuchAlgorithmException | BadPaddingException | NoSuchPaddingException | IllegalBlockSizeException e) {
        e.printStackTrace();
    }
    return value;
}
 
Example #17
Source File: Encrypt.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void combination_4(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher ci = createCipher(mode, params);
    ci.updateAAD(AAD);
    byte[] part41 = new byte[ci.getOutputSize(plainText.length)];
    int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0;
    int len = ci.update(plainText, 0, plainText.length - offset, part41, 0);
    int rest4 = ci.doFinal(plainText, plainText.length - offset, offset,
            part41, len);
    byte[] outputText4 = new byte[len + rest4];
    System.arraycopy(part41, 0, outputText4, 0, outputText4.length);
    results.add(outputText4);
}
 
Example #18
Source File: SSOSymmetrical.java    From kisso with Apache License 2.0 5 votes vote down vote up
/**
 * 加密
 *
 * @param algorithm
 * @param data
 * @param key
 * @return
 */
public byte[] encrypt(Algorithm algorithm, byte[] data, String key) {
    try {
        Cipher cipher = Cipher.getInstance(algorithm.toString());
        cipher.init(Cipher.ENCRYPT_MODE, this.toKey(algorithm, key));
        return cipher.doFinal(data);
    } catch (Exception e) {
        log.error("Encrypt setKey is exception.");
        throw new KissoException(e);
    }
}
 
Example #19
Source File: IronEncryption.java    From Iron with Apache License 2.0 5 votes vote down vote up
@Override
public Cipher getCipher(int mode){
    try {
        byte[] iv = generateIv();
        Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);
        cipher.init(mode, mKey.getConfidentialityKey(), new IvParameterSpec(iv));
        return cipher;
    }catch(GeneralSecurityException e){
        e.printStackTrace();
    }
    return null;
}
 
Example #20
Source File: EncryptionHelpers.java    From sejda with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Cipher getCipher(String salt, String key, int mode) {
    try {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(mode, keyToSpec(salt, key));

        return cipher;
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: TempOutputStream.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns the data as an InputStream
 */
public InputStream getInputStream() throws IOException
{
    if (tempFile != null)
    {
        if (encrypt)
        {
            final Cipher cipher;
            try
            {
                cipher = Cipher.getInstance(TRANSFORMATION);
                cipher.init(Cipher.DECRYPT_MODE, symKey, new IvParameterSpec(iv));
            }
            catch (Exception e)
            {
                destroy();

                if (logger.isErrorEnabled())
                {
                    logger.error("Cannot initialize decryption cipher", e);
                }

                throw new IOException("Cannot initialize decryption cipher", e);
            }

            return new BufferedInputStream(new CipherInputStream(new FileInputStream(tempFile), cipher));
        }
        return new BufferedInputStream(new FileInputStream(tempFile));
    }
    else
    {
        return new ByteArrayInputStream(tempStream.getBuffer(), 0, tempStream.getCount());
    }
}
 
Example #22
Source File: Crypto.java    From PewCrypt with MIT License 5 votes vote down vote up
public boolean encrypt_AES_key() {
	// get KeySpec
	X509EncodedKeySpec ks = new X509EncodedKeySpec(this.RSA_key);

	try {

		KeyFactory kf = KeyFactory.getInstance("RSA");

		// Get public key from KeySpec
		PublicKey pub = kf.generatePublic(ks);

		// create new AES.key file
		File kfile = new File("AES.key");
		kfile.createNewFile();

		// encrypt AES key with public
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, pub);

		// encrypted data buffer
		byte[] out = cipher.doFinal(this.PASS);

		// write encrypted data to AES.key file
		Files.write(kfile.toPath(), out);

	} catch (InvalidKeySpecException | IOException | NoSuchPaddingException | InvalidKeyException
			| IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException e) {
		e.printStackTrace();
		return false;
	}

	return true;
}
 
Example #23
Source File: AESUtils.java    From crypto-utils with GNU General Public License v3.0 5 votes vote down vote up
/**
 * The method that will encrypt data.
 * 
 * @param secretKey
 * 		The key used to encrypt the data.
 * 
 * @param data
 * 		The data to encrypt.
 * 
 * @return The encrypted data.
 */
public static byte[] encrypt(SecretKey secretKey, byte[] data) {
	try {
		Cipher cipher = Cipher.getInstance(algorithm);
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		return cipher.doFinal(data);
	} catch (Exception ex) {

	}

	return null;

}
 
Example #24
Source File: PasswordCrypt.java    From ermaster-b with Apache License 2.0 5 votes vote down vote up
public static String encrypt(String password) throws Exception {
    Key key = getKey();

    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, key);

    byte[] input = password.getBytes();
    byte[] encrypted = cipher.doFinal(input);

    return new String(Base64.encodeBase64(encrypted));
}
 
Example #25
Source File: SSLCipher.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
StreamReadCipher(Authenticator authenticator,
        ProtocolVersion protocolVersion, String algorithm,
        Key key, AlgorithmParameterSpec params,
        SecureRandom random) throws GeneralSecurityException {
    super(authenticator, protocolVersion);
    this.cipher = JsseJce.getCipher(algorithm);
    cipher.init(Cipher.DECRYPT_MODE, key, params, random);
}
 
Example #26
Source File: Cryptos.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
public static byte[] desDecrypt(byte[] pwd, byte[] key) throws Exception {
	// 从原始密钥数据创建DESKeySpec对象
	DESKeySpec dks = new DESKeySpec(key);
	// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
	SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
	SecretKey securekey = keyFactory.generateSecret(dks);
	// Cipher对象实际完成加密操作
	Cipher cipher = Cipher.getInstance(DES);
	// 用密钥初始化Cipher对象
	cipher.init(Cipher.DECRYPT_MODE, securekey, random);
	return cipher.doFinal(pwd);
}
 
Example #27
Source File: MasterSecretUtil.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
private static Cipher getCipherFromPassphrase(String passphrase, byte[] salt, int iterations, int opMode)
    throws GeneralSecurityException
{
  SecretKey key    = getKeyFromPassphrase(passphrase, salt, iterations);
  Cipher    cipher = Cipher.getInstance(key.getAlgorithm());
  cipher.init(opMode, key, new PBEParameterSpec(salt, iterations));

  return cipher;
}
 
Example #28
Source File: MasterCipher.java    From Silence with GNU General Public License v3.0 5 votes vote down vote up
public MasterCipher(MasterSecret masterSecret) {
  try {
    this.masterSecret = masterSecret;
    this.encryptingCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    this.decryptingCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    this.hmac             = Mac.getInstance("HmacSHA1");
  } catch (NoSuchPaddingException | NoSuchAlgorithmException nspe) {
    throw new AssertionError(nspe);
  }
}
 
Example #29
Source File: ReadWriteSkip.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
final void doTest(BufferType type) throws Exception {
    // init ciphers
    encryptCipher = createCipher(Cipher.ENCRYPT_MODE);
    decryptCipher = createCipher(Cipher.DECRYPT_MODE);

    // init cipher input stream
    ciInput = new CipherInputStream(new ByteArrayInputStream(plaintext),
            encryptCipher);

    runTest(type);
}
 
Example #30
Source File: AESCrypto.java    From openzaly with Apache License 2.0 5 votes vote down vote up
/**
 * 加密内容
 * 
 * @param tsk
 * @param content
 * @return
 */
public static byte[] encrypt(byte[] tsk, byte[] content) {
	try {
		SecretKeySpec key = new SecretKeySpec(tsk, "AES");
		Cipher cipher = Cipher.getInstance(ALGORITHM);// 创建密码器
		cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
		return cipher.doFinal(content);
	} catch (Exception e) {
		logger.error("aes encrypt error tsk-size={} content-size={}", tsk.length, content.length);
	}
	return null;
}