类javax.crypto.Cipher源码实例Demo

下面列出了怎么用javax.crypto.Cipher的API类实例代码及写法,或者点击链接到github查看源代码。

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;
    }
 
源代码2 项目: bop-bitcoin-client   文件: ExtendedKey.java
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);
	}
}
 
源代码3 项目: openjdk-jdk8u-backup   文件: WrongAAD.java
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");
}
 
源代码4 项目: spring-data-mongodb-encrypt   文件: CryptVault.java
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);
    }
}
 
源代码5 项目: RipplePower   文件: Passphrase.java
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;
}
 
源代码6 项目: tomee   文件: StaticDESPasswordCipher.java
/**
 * @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);
    }
}
 
源代码7 项目: TencentKona-8   文件: SameBuffer.java
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);
    }
}
 
源代码8 项目: SprintNBA   文件: DESEncrypt.java
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;
    }
}
 
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());
    }
}
 
/**
 * 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;
    }
}
 
源代码11 项目: java-aes-crypto   文件: AesCbcWithIntegrity.java
/**
 * 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);
}
 
源代码12 项目: javabase   文件: DesUtil.java
/**
 * 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);
}
 
源代码13 项目: jdk8u-jdk   文件: CipherStreamClose.java
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;
}
 
源代码14 项目: mollyim-android   文件: LogFile.java
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);
  }
}
 
源代码15 项目: InjuredAndroid   文件: VGV4dEVuY3J5cHRpb24.java
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;
}
 
源代码16 项目: gemfirexd-oss   文件: ENCRYPT1_4.java
@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);
}
 
源代码17 项目: openjsse   文件: SSLCipher.java
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);
}
 
源代码18 项目: opentest   文件: Encryptor.java
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);
    }
}
 
源代码19 项目: translationstudio8   文件: EncryptDES.java
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");
}
 
源代码20 项目: live-chat-engine   文件: AES128.java
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);
     }
 }
 
源代码21 项目: PowerFileExplorer   文件: CryptUtil.java
@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();
    }
}
 
源代码22 项目: jdk8u_jdk   文件: PBECipherWrapper.java
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()));
}
 
源代码23 项目: PreferenceRoom   文件: SecurityUtils.java
public static String decrypt(String input) {
  if (input == null) return null;
  byte[] decrypted = null;
  try {
    SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, skey);
    decrypted = cipher.doFinal(Base64.decode(input, Base64.DEFAULT));
  } catch (Exception e) {
    e.printStackTrace();
  }
  return new String(decrypted);
}
 
源代码24 项目: armadillo   文件: AesCbcEncryption.java
@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();
    }
}
 
源代码25 项目: hedera-sdk-java   文件: CryptoUtils.java
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);
}
 
源代码26 项目: commons-vfs   文件: DefaultCryptor.java
/**
 * 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);
}
 
源代码27 项目: java-telegram-bot-api   文件: RsaOaep.java
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);
}
 
源代码28 项目: Zom-Android-XMPP   文件: PassphraseSecretsImpl.java
/**
 * 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);
}
 
源代码29 项目: java_security   文件: DESTest.java
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();
	}
}
 
源代码30 项目: commcare-android   文件: FormRecordToFileTask.java
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()));
        }
    }
}