android 与java服务器进行RSA+AES加密通信
来源:互联网 发布:苹果电脑直播音效软件 编辑:程序博客网 时间:2024/05/22 06:10
流程 :
1 首先需要有一对RSA的公钥和私钥 , 然后私钥留在服务器,公钥随apk发布;
2 通信的时候,首先由android端,随机生成一个字符串作为AES加密算法的key,用AES加密算法来加密与服务器传输的主要内容(因为AES速度比较快);
3 然后客户端再使用RSA的公钥将AES的key进行加密,与AES加密后的内容一同传输给服务器;
4 服务器端先用RSA的私钥将AES的key进行解密,然后使用这个key来解密传输的内容;
5 需要注意的是,android端的AES加密算法和服务器的AES加密算法的默认序列(默认序列就是决定根据传入key生成真正加解密key的一个东西,类似c++生成随机数的玩意)是不同的,所以网上的那些AES加密算法都只适合android和android,服务器和服务器之间的使用,不适合android和服务器之间使用;(这玩意屡了半天才研究明白)
生成RSA密钥对的方法
/** * 生成公钥和私钥 */public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException { HashMap<String, Object> map = new HashMap<String, Object>(); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); map.put("public", publicKey); map.put("private", privateKey); return map;}
上边的方法生成一堆公钥和私钥,然后使用ObjectOutputStream和ObjectInputStream的writeObject和readObject方法就可以将两个key保存成文件和读取保存后的文件;
RSAUtil.java
public class RSAUtils {/** * 生成公钥和私钥 */public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException {HashMap<String, Object> map = new HashMap<String, Object>();KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");keyPairGen.initialize(1024);KeyPair keyPair = keyPairGen.generateKeyPair();RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();map.put("public", publicKey);map.put("private", privateKey);return map;}/** * 公钥加密 */public static String encryptByPublicKey(String data, RSAPublicKey publicKey) throws Exception {/* 这块将padding变成和服务器默认的一致 */Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");cipher.init(Cipher.ENCRYPT_MODE, publicKey);// 模长int key_len = publicKey.getModulus().bitLength() / 8;// 加密数据长度 <= 模长-11String[] datas = splitString(data, key_len - 11);String mi = "";// 如果明文长度大于模长-11则要分组加密for (String s : datas) {mi += bcd2Str(cipher.doFinal(s.getBytes()));}return mi;}/** * 私钥解密 */public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey) throws Exception {Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);// 模长int key_len = privateKey.getModulus().bitLength() / 8;byte[] bytes = data.getBytes();byte[] bcd = ASCII_To_BCD(bytes, bytes.length);// 如果密文长度大于模长则要分组解密String ming = "";byte[][] arrays = splitArray(bcd, key_len);for (byte[] arr : arrays) {ming += new String(cipher.doFinal(arr));}return ming;}/** * ASCII码转BCD码 * */public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {byte[] bcd = new byte[asc_len / 2];int j = 0;for (int i = 0; i < (asc_len + 1) / 2; i++) {bcd[i] = asc_to_bcd(ascii[j++]);bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));}return bcd;}public static byte asc_to_bcd(byte asc) {byte bcd;if ((asc >= '0') && (asc <= '9'))bcd = (byte) (asc - '0');else if ((asc >= 'A') && (asc <= 'F'))bcd = (byte) (asc - 'A' + 10);else if ((asc >= 'a') && (asc <= 'f'))bcd = (byte) (asc - 'a' + 10);elsebcd = (byte) (asc - 48);return bcd;}/** * BCD转字符串 */public static String bcd2Str(byte[] bytes) {char temp[] = new char[bytes.length * 2], val;for (int i = 0; i < bytes.length; i++) {val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');val = (char) (bytes[i] & 0x0f);temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');}return new String(temp);}/** * 拆分字符串 */public static String[] splitString(String string, int len) {int x = string.length() / len;int y = string.length() % len;int z = 0;if (y != 0) {z = 1;}String[] strings = new String[x + z];String str = "";for (int i = 0; i < x + z; i++) {if (i == x + z - 1 && y != 0) {str = string.substring(i * len, i * len + y);} else {str = string.substring(i * len, i * len + len);}strings[i] = str;}return strings;}/** * 拆分数组 */public static byte[][] splitArray(byte[] data, int len) {int x = data.length / len;int y = data.length % len;int z = 0;if (y != 0) {z = 1;}byte[][] arrays = new byte[x + z][];byte[] arr;for (int i = 0; i < x + z; i++) {arr = new byte[len];if (i == x + z - 1 && y != 0) {System.arraycopy(data, i * len, arr, 0, y);} else {System.arraycopy(data, i * len, arr, 0, len);}arrays[i] = arr;}return arrays;}/** * 使用模和指数生成RSA公钥 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA * /None/NoPadding】 * * @param modulus * 模 * @param exponent * 指数 * @return */public static RSAPublicKey getPublicKey(String modulus, String exponent) {try {BigInteger b1 = new BigInteger(modulus);BigInteger b2 = new BigInteger(exponent);KeyFactory keyFactory = KeyFactory.getInstance("RSA");RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);return (RSAPublicKey) keyFactory.generatePublic(keySpec);} catch (Exception e) {e.printStackTrace();return null;}}/** * 使用模和指数生成RSA私钥 * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA * /None/NoPadding】 * * @param modulus * 模 * @param exponent * 指数 * @return */public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {try {BigInteger b1 = new BigInteger(modulus);BigInteger b2 = new BigInteger(exponent);KeyFactory keyFactory = KeyFactory.getInstance("RSA");RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);} catch (Exception e) {e.printStackTrace();return null;}}
AESUtil.java(key需要16位)
public class AESUtil { public static String encrypt(String data , String key) { try { SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF-8"),"AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE , spec,new IvParameterSpec(new byte[cipher.getBlockSize()])); byte[] bs = cipher.doFinal(data.getBytes("UTF-8")); return Base64.encode(bs); } catch (Exception e) { return null; } } public static String decrypt(String data, String key) { try { SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE , spec , new IvParameterSpec(new byte[cipher.getBlockSize()])); byte[] originBytes = Base64.decode(data); byte[] result = cipher.doFinal(originBytes); return new String(result,"UTF-8"); } catch (Exception e) { return null; } }}
下边是android的使用示例:
public class RSA_AES_Activity extends AppCompatActivity{ @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); try{ /* AES的key(应该是随机生成 , 需要16位) */ String aes_key = "123456789abcdddd"; /* 获取RSA的公钥 */ RSAPublicKey pk = getPublicKeyFromAsset(); /* 明文 */ String data = "hello , fuck you"; /* 实际与服务器通信数据的密文 */ String dataMI = AESUtil.encrypt(data , aes_key); /* AES key的密文 */ String keyMI = RSAUtils.encryptByPublicKey(aes_key,pk); /* 发送密文 */ FormBody body = new FormBody.Builder().add("data", dataMI).add("key",keyMI).build(); /* 下边就是发送数据了 */ Request request = new Request.Builder().url("http://192.168.10.159:8080/cache").post(body).build(); new OkHttpClient().newCall(request).enqueue(new Callback() { public void onResponse(Call call, final Response response) throws IOException { final String str = response.body().string(); runOnUiThread(new Runnable() { public void run() { Toast.makeText(RSAActivity.this, str, Toast.LENGTH_SHORT).show(); } }); } public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { public void run() { Toast.makeText(RSAActivity.this, "over but err", Toast.LENGTH_SHORT).show(); } }); } }); }catch (Exception e){ e.printStackTrace(); } } /* 公钥文件放在了assets文件夹里边 , 这个方法将assets的key文件放到本地,再用ObjectInputStream读取 */ private RSAPublicKey getPublicKeyFromAsset(){ try{ InputStream in = getAssets().open("publicKey.key"); File targetFile = new File(getFilesDir(), "pk"); FileOutputStream out = new FileOutputStream(targetFile); byte[] bytes = new byte[in.available()]; in.read(bytes); in.close(); out.write(bytes); out.flush(); out.close(); ObjectInputStream oin = new ObjectInputStream(new FileInputStream(targetFile)); Object key = oin.readObject(); oin.close(); return (RSAPublicKey) key; }catch (Exception e){ e.printStackTrace(); return null; } }}
然后是服务器端 (Servlet的post方法):
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String keyMI = req.getParameter("key"); String dataMI = req.getParameter("data"); try { RSAPrivateKey pk = (RSAPrivateKey) loadKey(); String aes_key = RSAUtils.decryptByPrivateKey(keyMI,pk); String realData = AESUtil.decrypt(dataMI,aes_key); resp.getWriter().write(realData); } catch (Exception e) { e.printStackTrace(); resp.getWriter().write(e.toString()); } }
android和服务器都需要一个Base64.java (不要用android自带的那个)
public final class Base64 { private static final int BASELENGTH = 128; private static final int LOOKUPLENGTH = 64; private static final int TWENTYFOURBITGROUP = 24; private static final int EIGHTBIT = 8; private static final int SIXTEENBIT = 16; private static final int FOURBYTE = 4; private static final int SIGN = -128; private static char PAD = '='; private static byte[] base64Alphabet = new byte[BASELENGTH]; private static char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; static { for (int i = 0; i < BASELENGTH; ++i) { base64Alphabet[i] = -1; } for (int i = 'Z'; i >= 'A'; i--) { base64Alphabet[i] = (byte) (i - 'A'); } for (int i = 'z'; i >= 'a'; i--) { base64Alphabet[i] = (byte) (i - 'a' + 26); } for (int i = '9'; i >= '0'; i--) { base64Alphabet[i] = (byte) (i - '0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; for (int i = 0; i <= 25; i++) { lookUpBase64Alphabet[i] = (char) ('A' + i); } for (int i = 26, j = 0; i <= 51; i++, j++) { lookUpBase64Alphabet[i] = (char) ('a' + j); } for (int i = 52, j = 0; i <= 61; i++, j++) { lookUpBase64Alphabet[i] = (char) ('0' + j); } lookUpBase64Alphabet[62] = '+'; lookUpBase64Alphabet[63] = '/'; } private static boolean isWhiteSpace(char octect) { return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); } private static boolean isPad(char octect) { return (octect == PAD); } private static boolean isData(char octect) { return (octect < BASELENGTH && base64Alphabet[octect] != -1); } /** * Encodes hex octects into Base64 * * @param binaryData Array containing binaryData * @return Encoded Base64 array */ public static String encode(byte[] binaryData) { if (binaryData == null) { return null; } int lengthDataBits = binaryData.length * EIGHTBIT; if (lengthDataBits == 0) { return ""; } int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets; char encodedData[] = null; encodedData = new char[numberQuartet * 4]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; for (int i = 0; i < numberTriplets; i++) { b1 = binaryData[dataIndex++]; b2 = binaryData[dataIndex++]; b3 = binaryData[dataIndex++]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; } // form integral number of 6-bit groups if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex++] = PAD; encodedData[encodedIndex++] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex++] = PAD; } return new String(encodedData); } /** * Decodes Base64 data into octects * * @param encoded string containing Base64 data * @return Array containind decoded data. */ public static byte[] decode(String encoded) { if (encoded == null) { return null; } char[] base64Data = encoded.toCharArray(); // remove white spaces int len = removeWhiteSpace(base64Data); if (len % FOURBYTE != 0) { return null;// should be divisible by four } int numberQuadruple = (len / FOURBYTE); if (numberQuadruple == 0) { return new byte[0]; } byte decodedData[] = null; byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; char d1 = 0, d2 = 0, d3 = 0, d4 = 0; int i = 0; int encodedIndex = 0; int dataIndex = 0; decodedData = new byte[(numberQuadruple) * 3]; for (; i < numberQuadruple - 1; i++) { if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++])) || !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++]))) { return null; }// if found "no data" just return null b1 = base64Alphabet[d1]; b2 = base64Alphabet[d2]; b3 = base64Alphabet[d3]; b4 = base64Alphabet[d4]; decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); } if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) { return null;// if found "no data" just return null } b1 = base64Alphabet[d1]; b2 = base64Alphabet[d2]; d3 = base64Data[dataIndex++]; d4 = base64Data[dataIndex++]; if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters if (isPad(d3) && isPad(d4)) { if ((b2 & 0xf) != 0)// last 4 bits should be zero { return null; } byte[] tmp = new byte[i * 3 + 1]; System.arraycopy(decodedData, 0, tmp, 0, i * 3); tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); return tmp; } else if (!isPad(d3) && isPad(d4)) { b3 = base64Alphabet[d3]; if ((b3 & 0x3) != 0)// last 2 bits should be zero { return null; } byte[] tmp = new byte[i * 3 + 2]; System.arraycopy(decodedData, 0, tmp, 0, i * 3); tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); return tmp; } else { return null; } } else { // No PAD e.g 3cQl b3 = base64Alphabet[d3]; b4 = base64Alphabet[d4]; decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); } return decodedData; } /** * remove WhiteSpace from MIME containing encoded Base64 data. * * @param data the byte array of base64 data (with WS) * @return the new length */ private static int removeWhiteSpace(char[] data) { if (data == null) { return 0; } // count characters that's not whitespace int newSize = 0; int len = data.length; for (int i = 0; i < len; i++) { if (!isWhiteSpace(data[i])) { data[newSize++] = data[i]; } } return newSize; }}
3 0
- android 与java服务器进行RSA+AES加密通信
- AES与RSA加密
- Android进阶----使用AES+RSA对http请求进行加密
- Java对称与非对称加密解密,AES与RSA
- Java对称与非对称加密解密,AES与RSA
- Java对称与非对称加密解密,AES与RSA
- java 进行aes加密
- Android采用AES+RSA的加密机制对http请求进行加密
- 客户端服务器加密通信(1):AES加密
- RSA加密在移动端与服务器通信中的应用
- AES与RSA相结合数据加密方案
- polarssl rsa & aes 加密与解密
- Android DES,AES,RSA加密实现
- Android AES DES RSA 加密解密 解析
- Android 数据加密之RSA + AES
- iOS客户端、java服务器的通信用RSA加密
- iOS客户端、java服务器的通信用RSA加密
- Java实现简单AES RSA加密
- [转载]STL学习之Vector
- 版本迭代,上传ipa时的小毛病
- git 切换分支,pull分支,提交分支
- leetcode 31. Next Permutation
- Eclipse中调节字体大小、颜色与背景色
- android 与java服务器进行RSA+AES加密通信
- 人生苦短,我用 Python
- 建立自己的MIT App Inventer 2的网络微数据库网络后台
- macOS下信号量semaphore部分函数失效的问题
- 把已经存在的项目上传到github
- 关于使用Android Studio 2.1+ 出现AGPBI错误的处理
- 177.Convert Sorted Array to Binary Search Tree With Minimal Height-把排序数组转换为高度最小的二叉搜索树(容易题)
- 命名空间的顺序
- 浅谈Android中MVC、MVP、MVVM模式(一)