在Android中进行加密和解密操作时,建议使用安全的算法和方法,不要使用过于简单的算法或自行编写的加解密算法,以免被攻击者利用漏洞进行攻击。以下是一些常用的加密和解密方法:
1.对称加密算法:使用同一密钥进行加解密操作的算法,例如AES算法。
示例代码:
//加密操作 public static String encrypt(String content, String key) throws Exception { byte[] byteContent = content.getBytes("UTF-8"); byte[] enCodeFormat = key.getBytes(); SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] result = cipher.doFinal(byteContent); return Base64.encodeToString(result, Base64.DEFAULT); }
//解密操作 public static String decrypt(String content, String key) throws Exception { byte[] byteContent = Base64.decode(content, Base64.DEFAULT); byte[] enCodeFormat = key.getBytes(); SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] result = cipher.doFinal(byteContent); return new String(result, "UTF-8"); }
2.非对称加密算法:使用公钥加密数据,使用私钥解密数据的算法,例如RSA算法。
示例代码:
//生成RSA密钥对 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate();
//加密操作 public static String encryptRSA(String content, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] result = cipher.doFinal(content.getBytes()); return Base64.encodeToString(result, Base64.DEFAULT); }
//解密操作 public static String decryptRSA(String content, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] result = cipher.doFinal(Base64.decode(content, Base64.DEFAULT)); return new String(result); }
3.Hash算法:将任意长度的输入映射为固定长度的输出,常用的算法有MD5和SHA-1。
示例代码:
//MD5哈希 public static String md5(String content) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] result = md.digest(content.getBytes()); return byteArrayToHexString(result); }
//SHA-1哈希 public static String sha1(String content) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] result = md.digest(content.getBytes()); return byteArrayToHexString(result); }
//将字节数组转为十六进制字符串 private static String byteArrayToHexString(byte[] b) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < b.length; i++) { String hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { sb.append("0"); } sb