Android加密算法

时间:2014-04-21 07:50:50

标签: android encryption

我正在加密字节数组,我想知道Android 4.0.3及更高版本默认哪些密码算法(AES,DES,MD5等)可用。我找不到任何官方参考指南。

由于我并不特别熟悉Android中的加密,因此我发布了我感兴趣的相关代码。

public static byte[] encrypt(byte[] value, String cryptoPass) {
    try {
        DESKeySpec keySpec = new DESKeySpec(cryptoPass.getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        // Cipher is not thread safe
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        Log.d("bitmap", "Decrypted: " + value + " -> " + value);
        String encryptedValue = Base64.encodeToString(cipher.doFinal(value), Base64.DEFAULT);
        Log.d("bitmap", "Encrypted: " + value + " -> " + encryptedValue);

        return encryptedValue.getBytes("UTF-8");

    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }
    return value;
};

public static byte[] decrypt(byte[] value, String cryptoPass) {

    try {
        DESKeySpec keySpec = new DESKeySpec(cryptoPass.getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        byte[] encrypedPwdBytes = Base64.decode(value, Base64.DEFAULT);
        // cipher is not thread safe
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key);

        return (cipher.doFinal(encrypedPwdBytes));

    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }
    return value;
}

0 个答案:

没有答案