android加密字符串,在Android中加密/解密字符串的简便方法

您可以使用Cipher.

此类提供用于加密和解密的加密密码的功能.它构成了Java Cryptographic Extension(JCE)框架的核心.

加密和解密样本:

public static SecretKey generateKey()

throws NoSuchAlgorithmException, InvalidKeySpecException

{

return secret = new SecretKeySpec(password.getBytes(), "AES");

}

public static byte[] encryptMsg(String message, SecretKey secret)

throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException

{

/* Encrypt the message. */

Cipher cipher = null;

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

cipher.init(Cipher.ENCRYPT_MODE, secret);

byte[] cipherText = cipher.doFinal(message.getBytes("UTF-8"));

return cipherText;

}

public static String decryptMsg(byte[] cipherText, SecretKey secret)

throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException

{

/* Decrypt the message, given derived encContentValues and initialization vector. */

Cipher cipher = null;

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

cipher.init(Cipher.DECRYPT_MODE, secret);

String decryptString = new String(cipher.doFinal(cipherText), "UTF-8");

return decryptString;

}

要加密:

SecretKey secret = generateKey();

EncUtil.encryptMsg(String toEncrypt, secret))

要解密:

EncUtil.decryptMsg(byte[] toDecrypt, secret))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值