Java Code Examples for javax.crypto.Cipher

The following examples show how to use javax.crypto.Cipher. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Image-Steganography-Library-Android   Source File: Crypto.java    License: MIT License 6 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 Project: bop-bitcoin-client   Source File: ExtendedKey.java    License: 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 3
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 4
Source Project: spring-data-mongodb-encrypt   Source File: CryptVault.java    License: 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 5
Source Project: RipplePower   Source File: Passphrase.java    License: 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 6
Source Project: tomee   Source File: StaticDESPasswordCipher.java    License: 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 7
Source Project: TencentKona-8   Source File: SameBuffer.java    License: 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 8
Source Project: SprintNBA   Source File: DESEncrypt.java    License: 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 9
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 10
/**
 * 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 11
Source Project: java-aes-crypto   Source File: AesCbcWithIntegrity.java    License: 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 12
Source Project: javabase   Source File: DesUtil.java    License: 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 13
Source Project: jdk8u-jdk   Source File: CipherStreamClose.java    License: 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 14
Source Project: mollyim-android   Source File: LogFile.java    License: 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 15
Source Project: InjuredAndroid   Source File: VGV4dEVuY3J5cHRpb24.java    License: 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 16
Source Project: gemfirexd-oss   Source File: ENCRYPT1_4.java    License: 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 17
Source Project: openjsse   Source File: SSLCipher.java    License: 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 18
Source Project: opentest   Source File: Encryptor.java    License: MIT License 5 votes vote down vote up
public String decrypt(String encryptedData) {
    try {
        IvParameterSpec iv = new IvParameterSpec(this.initVector.getBytes("UTF-8"));

        SecretKey key = getKey();

        this.getCypher().init(Cipher.DECRYPT_MODE, key, iv);

        byte[] original = this.getCypher().doFinal(Base64.getDecoder().decode(encryptedData.toString()));

        return new String(original);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 19
public EncryptDES() throws NoSuchAlgorithmException, NoSuchPaddingException{
	//ʵ����֧��DES�㷨����Կ������(�㷨���������谴�涨�������׳��쳣)
	keygen = KeyGenerator.getInstance("DES", new org.bouncycastle.jce.provider.BouncyCastleProvider());
	//������Կ
	deskey = keygen.generateKey();
	//����Cipher����,ָ����֧�ֵ�DES�㷨
	c = Cipher.getInstance("DES");
}
 
Example 20
Source Project: live-chat-engine   Source File: AES128.java    License: Apache License 2.0 5 votes vote down vote up
public static byte[] encode(byte[] input, byte[] key) {
 	key = getNormalKey(key);
     try {
         Cipher cipher = Cipher.getInstance(CIPHER);
         cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, KEY_ALG));
         byte[] hexed = new Hex().encode(input);
byte[] encoded = cipher.doFinal(hexed);
return encoded;
     } catch (Exception e) {
         throw new IllegalStateException("can't encode", e);
     }
 }
 
Example 21
Source Project: PowerFileExplorer   Source File: CryptUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private static void rsaDecrypt(Context context, BufferedInputStream inputStream,
                               BufferedOutputStream outputStream) throws NoSuchPaddingException,
        NoSuchAlgorithmException, NoSuchProviderException, CertificateException,
        BadPaddingException, InvalidAlgorithmParameterException, KeyStoreException,
        UnrecoverableEntryException, IllegalBlockSizeException, InvalidKeyException, IOException {

    Cipher cipher = Cipher.getInstance(ALGO_AES, "BC");
    RSAKeygen keygen = new RSAKeygen(context);

    IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
    cipher.init(Cipher.DECRYPT_MODE, keygen.getSecretKey(), ivParameterSpec);
    CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);

    byte[] buffer = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
    int count;

    try {

        while ((count = cipherInputStream.read(buffer)) != -1) {

            outputStream.write(buffer, 0, count);
            ServiceWatcherUtil.POSITION+=count;
        }
    } finally {

        outputStream.flush();
        outputStream.close();
        cipherInputStream.close();
    }
}
 
Example 22
Source Project: jdk8u_jdk   Source File: PBECipherWrapper.java    License: GNU General Public License v2.0 5 votes vote down vote up
public AES(String algo, String passwd)
        throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeySpecException {
    super(algo, 0);

    ci = Cipher.getInstance(algo);

    SecretKeyFactory skf = SecretKeyFactory.getInstance(algo);
    key = skf.generateSecret(new PBEKeySpec(passwd.toCharArray()));
}
 
Example 23
Source Project: PreferenceRoom   Source File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String decrypt(String input) {
  if (input == null) return null;
  byte[] decrypted = null;
  try {
    SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, skey);
    decrypted = cipher.doFinal(Base64.decode(input, Base64.DEFAULT));
  } catch (Exception e) {
    e.printStackTrace();
  }
  return new String(decrypted);
}
 
Example 24
Source Project: armadillo   Source File: AesCbcEncryption.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public byte[] encrypt(byte[] rawEncryptionKey, byte[] rawData, @Nullable byte[] associatedData) throws AuthenticatedEncryptionException {
    checkAesKey(rawEncryptionKey);

    byte[] iv = null;
    byte[] encrypted = null;
    byte[] mac = null;
    try {
        iv = new byte[IV_LENGTH_BYTE];
        secureRandom.nextBytes(iv);

        final Cipher cipherEnc = getCipher();
        cipherEnc.init(Cipher.ENCRYPT_MODE, createEncryptionKey(rawEncryptionKey), new IvParameterSpec(iv));
        encrypted = cipherEnc.doFinal(rawData);

        mac = macCipherText(rawEncryptionKey, encrypted, iv, associatedData);

        ByteBuffer byteBuffer = ByteBuffer.allocate(1 + iv.length + 1 + mac.length + encrypted.length);
        byteBuffer.put((byte) iv.length);
        byteBuffer.put(iv);
        byteBuffer.put((byte) mac.length);
        byteBuffer.put(mac);
        byteBuffer.put(encrypted);

        return byteBuffer.array();
    } catch (Exception e) {
        throw new AuthenticatedEncryptionException("could not encrypt", e);
    } finally {
        Bytes.wrapNullSafe(iv).mutable().secureWipe();
        Bytes.wrapNullSafe(encrypted).mutable().secureWipe();
        Bytes.wrapNullSafe(mac).mutable().secureWipe();
    }
}
 
Example 25
Source Project: hedera-sdk-java   Source File: CryptoUtils.java    License: Apache License 2.0 5 votes vote down vote up
static Cipher initAesCbc128Encrypt(KeyParameter cipherKey, byte[] iv) {
    final Cipher aesCipher;

    try {
        aesCipher = Cipher.getInstance("AES/CBC/NoPadding");
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw new Error("platform does not support AES-CBC ciphers");
    }

    return initAesCipher(aesCipher, cipherKey, iv, false);
}
 
Example 26
Source Project: commons-vfs   Source File: DefaultCryptor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Decrypts the password.
 *
 * @param encryptedKey the encrypted password.
 * @return The plain text password.
 * @throws Exception If an error occurs.
 */
@Override
public String decrypt(final String encryptedKey) throws Exception {
    final SecretKeySpec key = new SecretKeySpec(KEY_BYTES, "AES");
    final Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, key);
    final byte[] decoded = decode(encryptedKey);
    final byte[] plainText = new byte[cipher.getOutputSize(decoded.length)];
    int ptLength = cipher.update(decoded, 0, decoded.length, plainText, 0);
    ptLength += cipher.doFinal(plainText, ptLength);
    return new String(plainText).substring(0, ptLength);
}
 
Example 27
Source Project: java-telegram-bot-api   Source File: RsaOaep.java    License: Apache License 2.0 5 votes vote down vote up
static byte[] decrypt(String privateKey, byte[] secret) throws Exception {
    String pkcs8Pem = privateKey;
    pkcs8Pem = pkcs8Pem.replace("-----BEGIN RSA PRIVATE KEY-----", "");
    pkcs8Pem = pkcs8Pem.replace("-----END RSA PRIVATE KEY-----", "");
    pkcs8Pem = pkcs8Pem.replaceAll("\\s+", "");
    byte[] pkcs8EncodedBytes = Base64.decode(pkcs8Pem, 0);

    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privKey = kf.generatePrivate(getRSAKeySpec(pkcs8EncodedBytes));

    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
    cipher.init(Cipher.DECRYPT_MODE, privKey);
    return cipher.doFinal(secret);
}
 
Example 28
/**
 * Encrypts the data with AES GSM Does not wipe the data nor the key
 *
 * @param x_passphraseKey
 * @param iv
 * @param data
 * @return the encrypted key ciphertext
 * @throws GeneralSecurityException
 */
public byte[] encryptSecretKey(SecretKey x_passphraseKey, byte[] iv, byte[] data)
        throws GeneralSecurityException {
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

    // TODO(abel) follow this rabbit hole down and wipe it!
    cipher.init(Cipher.ENCRYPT_MODE, x_passphraseKey, new IvParameterSpec(iv));

    return cipher.doFinal(data);
}
 
Example 29
Source Project: java_security   Source File: DESTest.java    License: MIT License 5 votes vote down vote up
public static void jdkDES()
{
	try 
	{
		// 生成KEY
		KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");			
		keyGenerator.init(56);
		// 产生密钥
		SecretKey secretKey = keyGenerator.generateKey();
		// 获取密钥
		byte[] bytesKey = secretKey.getEncoded();
		
		
		// KEY转换
		DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
		SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
		Key convertSecretKey = factory.generateSecret(desKeySpec);
		
		
		// 加密
		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
		byte[] result = cipher.doFinal(src.getBytes());
		System.out.println("jdk des encrypt:" + Hex.encodeHexString(result));
		
		// 解密
		cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
		result = cipher.doFinal(result);
		System.out.println("jdk des decrypt:" + new String(result));
		
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 30
Source Project: commcare-android   Source File: FormRecordToFileTask.java    License: Apache License 2.0 5 votes vote down vote up
private void decryptCopyFiles(File[] files, File targetDirectory, Cipher decryptCipher) throws IOException{
    for (File file : files) {
        // This is not the ideal long term solution for determining whether we need decryption, but works
        if (file.getName().endsWith(".xml")) {
            FileUtil.copyFile(file, new File(targetDirectory, file.getName()), decryptCipher, null);
        } else {
            FileUtil.copyFile(file, new File(targetDirectory, file.getName()));
        }
    }
}