admin管理员组文章数量:1122852
Android MD5,3DES,AES,RSA,Base64加解密
导言:
由于数据的安全性,所以需要进行数据加密和解密处理,所以本文只是记录一点
名词:
对称加密算法:加密和解密使用相同密钥的算法
异或加密算法:简单加密算法的一种,通过异或算法处理
RSA:公钥和私钥,非对称密码算法
Des:密钥加载,对称加密算法
Des3:DES加密算法的扩展,它使用3条64位的密钥对数据进行三次加密,DES向AES过渡的加密算法
Aes:区块,对称加密算法,用来替代Des
Md5:单向不可逆加密算法,但是也是可以编译的,用跑字典,解决方式多次加密和加盐
SHA:单向不可逆加密算法,Md5后继者,有SHA-1,SHA-2(SHA-224、SHA-384,SHA-512),如Google将使用SHA-2
Base64:对数据内容进行编码转换适合网络传输,由于传输过程中那些不可见ascii码被处理错误
步骤:
1:MD5加密,很简单,直接将需要加密的字符串传入即可.
public static String MD5Tool(String str) {if (TextUtils.isEmpty(str)) {return "";}try {MessageDigest mDigest = MessageDigest.getInstance("MD5");byte[] bytes = mDigest.digest(str.getBytes());String result = "";for (byte bt : bytes) {String temp = Integer.toHexString(bt & 0xff);if (temp.length() == 1) {temp = "0" + temp;}result += temp;}return result;} catch (Exception e) {e.printStackTrace();}return "";}
2:3DES重要加密解密类
public class DES3Util {private static final String TYPE = "DESede";//加密public static byte[] encryptMode(byte[] keybyte, byte[] src) {try {SecretKey deskey = new SecretKeySpec(keybyte, TYPE);Cipher c1 = Cipher.getInstance(TYPE);c1.init(Cipher.ENCRYPT_MODE, deskey);return c1.doFinal(src);} catch (java.security.NoSuchAlgorithmException e1) {e1.printStackTrace();} catch (javax.crypto.NoSuchPaddingException e2) {e2.printStackTrace();} catch (java.lang.Exception e3) {e3.printStackTrace();}return null;}//解密public static byte[] decryptMode(byte[] keybyte, byte[] src) {try {SecretKey deskey = new SecretKeySpec(keybyte, TYPE);Cipher c1 = Cipher.getInstance(TYPE);c1.init(Cipher.DECRYPT_MODE, deskey);return c1.doFinal(src);} catch (java.security.NoSuchAlgorithmException e1) {e1.printStackTrace();} catch (javax.crypto.NoSuchPaddingException e2) {e2.printStackTrace();} catch (java.lang.Exception e3) {e3.printStackTrace();}return null;}//byte->hexStringpublic static String byte2hex(byte[] b) {String hs = "";String stmp = "";for (int n = 0; n < b.length; n++) {stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));if (stmp.length() == 1) hs = hs + "0" + stmp;else hs = hs + stmp;if (n < b.length - 1) hs = hs + "";}return hs.toUpperCase();}//hexString->bytepublic static byte[] hexStringToBytes(String hexString) {if (hexString == null || hexString.equals("")) {return null;}hexString = hexString.toUpperCase();int length = hexString.length() / 2;char[] hexChars = hexString.toCharArray();byte[] d = new byte[length];for (int i = 0; i < length; i++) {int pos = i * 2;d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));}return d;}private static byte charToByte(char c) {return (byte) "0123456789ABCDEF".indexOf(c);}
}
3:使用3DES加密解密样例
//三个不同秘钥
String key = "B1B2B3B4B5B6B7B8" + "A1A2A3A4A5A6A7A8" + "A1B2A3A4A5A6A7F8";
Sting src="1252142adfef@qq";
//加密
String encryResult = byte2hex(encryptMode(hexStringToBytes(key), src.getBytes("UTF-8")));
//解密
String decryptResult = new String(decryptMode(hexStringToBytes(key), hexStringToBytes(encryResult)), "UTF-8");
4:RSA,AES,Base64混合保证数据传递的安全性
释义:
RSA公钥和私钥通过Alipay_RSA签名工具生成,不要用代码生成,AES每次在客户端自动随机生成.
流程:android<—>服务器后台 是双向的
android:
1:RSA公钥a–加密–>AES秘钥b---->加密的AES秘钥c
2:AES秘钥b–加密–>原数据d---->加密数据e
服务器后台:
1:RSA私钥f–解密–>加密的AES秘钥c---->AES秘钥b
2:AES秘钥b–解密–>加密数据e---->原数据d
public class RSAESUtils {private static String sTransform = "RSA/NONE/PKCS1Padding";private static int sBase64Mode = Base64.DEFAULT;//RSA产生密钥对,经常通过第三方工具支付宝生成,而不是用代码生成,所以这个方法忽略public static KeyPair generateRSAKeyPair(int keyLength) {KeyPair keyPair = null;try {KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");//设置密钥长度keyPairGenerator.initialize(keyLength);//产生密钥对keyPair = keyPairGenerator.generateKeyPair();} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return keyPair;}//RSA加密或解密数据的通用方法private static byte[] processData(byte[] srcData, Key key, int mode) {//用来保存处理结果byte[] resultBytes = null;try {//获取Cipher实例Cipher cipher = Cipher.getInstance(sTransform);//初始化Cipher,mode指定是加密还是解密,key为公钥或私钥cipher.init(mode, key);//处理数据resultBytes = cipher.doFinal(srcData);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();}return resultBytes;}//RSA使用公钥加密数据,结果用Base64转码public static String encryptDataByPublicKey(byte[] srcData, PublicKey publicKey) {byte[] resultBytes = processData(srcData, publicKey, Cipher.ENCRYPT_MODE);return Base64.encodeToString(resultBytes, sBase64Mode);}//RSA使用私钥解密,返回解码数据public static byte[] decryptDataByPrivate(String encryptedData, PrivateKey privateKey) {byte[] bytes = Base64.decode(encryptedData, sBase64Mode);return processData(bytes, privateKey, Cipher.DECRYPT_MODE);}//RSA使用私钥进行解密,解密数据转换为字符串,使用utf-8编码格式public static String decryptedToStrByPrivate(String encryptedData, PrivateKey privateKey) {return new String(decryptDataByPrivate(encryptedData, privateKey));}//RSA使用私钥解密,解密数据转换为字符串,并指定字符集public static String decryptedToStrByPrivate(String encryptedData, PrivateKey privateKey, String charset) {try {return new String(decryptDataByPrivate(encryptedData, privateKey), charset);} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}//RSA使用私钥加密,结果用Base64转码public static String encryptDataByPrivateKey(byte[] srcData, PrivateKey privateKey) {byte[] resultBytes = processData(srcData, privateKey, Cipher.ENCRYPT_MODE);return Base64.encodeToString(resultBytes, sBase64Mode);}//RSA使用公钥解密,返回解密数据public static byte[] decryptDataByPublicKey(String encryptedData, PublicKey publicKey) {byte[] bytes = Base64.decode(encryptedData, sBase64Mode);return processData(bytes, publicKey, Cipher.DECRYPT_MODE);}//RSA使用公钥解密,结果转换为字符串,使用默认字符集utf-8public static String decryptedToStrByPublicKey(String encryptedData, PublicKey publicKey) {return new String(decryptDataByPublicKey(encryptedData, publicKey));}//RSA使用公钥解密,结果转换为字符串,使用指定字符集public static String decryptedToStrByPublicKey(String encryptedData, PublicKey publicKey, String charset) {try {return new String(decryptDataByPublicKey(encryptedData, publicKey), charset);} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}//RSA将字符串形式的公钥转换为公钥对象public static PublicKey keyStrToPublicKey(String publicKeyStr) {PublicKey publicKey = null;byte[] keyBytes = Base64.decode(publicKeyStr, sBase64Mode);X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);try {KeyFactory keyFactory = KeyFactory.getInstance("RSA");publicKey = keyFactory.generatePublic(keySpec);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (InvalidKeySpecException e) {e.printStackTrace();}return publicKey;}//RSA将字符串形式的私钥,转换为私钥对象public static PrivateKey keyStrToPrivate(String privateKeyStr) {PrivateKey privateKey = null;byte[] keyBytes = Base64.decode(privateKeyStr, sBase64Mode);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);try {KeyFactory keyFactory = KeyFactory.getInstance("RSA");privateKey = keyFactory.generatePrivate(keySpec);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (InvalidKeySpecException e) {e.printStackTrace();}return privateKey;}//生成AES秘钥public static byte[] generateAESKey(int keySize) {//保存AES密钥的字节数组byte[] keyBytes = null;try {//获取密钥生成器KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");//设置密钥长度,如果不调用该方法,默认生成256位的密钥keyGenerator.init(keySize);//获得密钥对象SecretKey secretKey = keyGenerator.generateKey();//转成字节数组keyBytes = secretKey.getEncoded();} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return keyBytes;}//AES初始化向量IVprivate static byte[] generatorIvBytes(int blockSize) {Random random = new Random();byte[] ivParam = new byte[blockSize];for (int index = 0; index < blockSize; index++) {ivParam[index] = (byte) random.nextInt(256);}return ivParam;}//AES ECB模式加密public static String encryptDataByECB(String srcData) {String finalResult = null;//产生密钥byte[] keyBytes = generateAESKey(256);//构建SecretKeySpec,初始化Cipher对象时需要该参数SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");try {//构建Cipher对象,需要传入一个字符串,格式必须为"algorithm/mode/padding"或者"algorithm/"Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//初始化Cipher对象cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);//加密数据byte[] resultBytes = cipher.doFinal(srcData.getBytes());//结果用Base64转码finalResult = Base64.encodeToString(resultBytes, Base64.DEFAULT);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();}return finalResult;}//AES ECB模式解密public static String decryptDataByECB(String srcData, byte[] keyBytes, String transform) {byte[] clearData = null;SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");try {//根据格式获取Cipher实例,需与加密时一致Cipher cipher = Cipher.getInstance(transform);//初始化Cipher,注意这里变为解密模式cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);//先Base64解码byte[] temp = Base64.decode(srcData, Base64.DEFAULT);//解密数据clearData = cipher.doFinal(temp);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();}return new String(clearData);}//AES CBC模式加密public static String encryptDataByCBC(String srcData) {String finalResult = null;//产生密钥byte[] keyBytes = generateAESKey(256);//构建SecretKeySpec,初始化Cipher对象时需要该参数SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");try {//构建Cipher对象,需要传入一个字符串,格式必须为"algorithm/mode/padding"或者"algorithm/"Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//初始化Cipher对象byte[] ivBytes = generatorIvBytes(keyBytes.length);IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);//加密数据byte[] resultBytes = cipher.doFinal(srcData.getBytes());//结果用Base64转码finalResult = Base64.encodeToString(resultBytes, Base64.DEFAULT);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (InvalidAlgorithmParameterException e) {e.printStackTrace();}return finalResult;}//AES CBC模式解密public static String decryptDataByCBC(String srcData, byte[] keyBytes, byte[] ivBytes, String transform) {byte[] clearData = null;SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");try {//根据格式获取Cipher实例,需与加密时一致Cipher cipher = Cipher.getInstance(transform);//初始化Cipher,注意这里变为解密模式IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);//先Base64解码byte[] temp = Base64.decode(srcData, Base64.DEFAULT);//解密数据clearData = cipher.doFinal(temp);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (InvalidAlgorithmParameterException e) {e.printStackTrace();}return new String(clearData);}
}
结束
本文标签: Android MD53DESAESRSABase64加解密
版权声明:本文标题:Android MD5,3DES,AES,RSA,Base64加解密 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/biancheng/1708922237a754164.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论