標籤:解密 加密 安卓 rsa java
安卓中預設與java工程中不一樣,要當心
安卓端使用 公開金鑰 一鍵加密 解密 代碼
注意,初始化時需要使用這個類,jar需要單獨下載 org.bouncycastle.jce.provider.BouncyCastleProvider
代碼中 Constants.getPBK() 得到的是公開金鑰
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.math.BigInteger;import java.security.Key;import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.NoSuchAlgorithmException;import java.security.PrivateKey;import java.security.PublicKey;import java.security.interfaces.RSAPrivateKey;import java.security.interfaces.RSAPublicKey;import java.security.spec.InvalidKeySpecException;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.RSAPublicKeySpec;import java.security.spec.X509EncodedKeySpec;import javax.crypto.Cipher; /** * @author Young * @date * 一鍵加密解密 安卓版 */public final class RSAUtils{private static String RSA = "RSA";private static PublicKey publicKey;/** * 隨機產生RSA金鑰組(預設密鑰長度為1024) * * @return */private static KeyPair generateRSAKeyPair(){return generateRSAKeyPair(1024);}/** * 隨機產生RSA金鑰組 * * @param keyLength * 密鑰長度,範圍:512~2048<br> * 一般1024 * @return */private static KeyPair generateRSAKeyPair(int keyLength){try{KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA,new org.bouncycastle.jce.provider.BouncyCastleProvider());kpg.initialize(keyLength);return kpg.genKeyPair();} catch (Throwable e){e.printStackTrace();return null;}} /** * 用公開金鑰加密 <br> * 每次加密的位元組數,不能超過密鑰的長度值減去11 * * @return 加密後的 資料 */public static String encryptData(String data ){try{if (publicKey==null) {publicKey=loadPublicKey(Constants.getPBK());}//Cipher cipher = Cipher.getInstance(RSA);Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");// 編碼前設定編碼方式及密鑰cipher.init(Cipher.ENCRYPT_MODE, publicKey);// 傳入編碼資料並返回編碼結果return Base64Utils.encode(cipher.doFinal(data.getBytes())); } catch (Exception e){e.printStackTrace();return null;}}/** * 用公開金鑰解密 * * @return */public static String decryptData(String data){try{if (publicKey==null) {publicKey=loadPublicKey(Constants.getPBK());}byte[] encryptedData=Base64Utils.decode(data);//Cipher cipher = Cipher.getInstance(RSA);Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");cipher.init(Cipher.DECRYPT_MODE, publicKey);return new String(cipher.doFinal(encryptedData));} catch (Exception e){return null;}} /** * 通過公開金鑰byte[](publicKey.getEncoded())將公開金鑰還原,適用於RSA演算法 * * @param keyBytes * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */private static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,InvalidKeySpecException{X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(RSA);PublicKey publicKey = keyFactory.generatePublic(keySpec);return publicKey;}/** * 通過私密金鑰byte[]將公開金鑰還原,適用於RSA演算法 * * @param keyBytes * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */private static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,InvalidKeySpecException{PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(RSA);PrivateKey privateKey = keyFactory.generatePrivate(keySpec);return privateKey;}/** * 使用N、e值還原公開金鑰 * * @param modulus * @param publicExponent * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */private static PublicKey getPublicKey(String modulus, String publicExponent)throws NoSuchAlgorithmException, InvalidKeySpecException{BigInteger bigIntModulus = new BigInteger(modulus);BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);KeyFactory keyFactory = KeyFactory.getInstance(RSA);PublicKey publicKey = keyFactory.generatePublic(keySpec);return publicKey;}/** * 使用N、d值還原私密金鑰 * * @param modulus * @param privateExponent * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */private static PrivateKey getPrivateKey(String modulus, String privateExponent)throws NoSuchAlgorithmException, InvalidKeySpecException{BigInteger bigIntModulus = new BigInteger(modulus);BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);KeyFactory keyFactory = KeyFactory.getInstance(RSA);PrivateKey privateKey = keyFactory.generatePrivate(keySpec);return privateKey;}/** * 從字串中載入公開金鑰 * * @param publicKeyStr * 公開金鑰資料字串 * @throws Exception * 載入公開金鑰時產生的異常 */private static PublicKey loadPublicKey(String publicKeyStr) throws Exception{try{byte[] buffer = Base64Utils.decode(publicKeyStr);KeyFactory keyFactory = KeyFactory.getInstance(RSA);X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);return (RSAPublicKey) keyFactory.generatePublic(keySpec);} catch (NoSuchAlgorithmException e){throw new Exception("無此演算法");} catch (InvalidKeySpecException e){throw new Exception("公開金鑰非法");} catch (NullPointerException e){throw new Exception("公開金鑰資料為空白");}}/** * 從字串中載入私密金鑰<br> * 載入時使用的是PKCS8EncodedKeySpec(PKCS#8編碼的Key指令)。 * * @param privateKeyStr * @return * @throws Exception */private static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception{try{byte[] buffer = Base64Utils.decode(privateKeyStr);// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);KeyFactory keyFactory = KeyFactory.getInstance(RSA);return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);} catch (NoSuchAlgorithmException e){throw new Exception("無此演算法");} catch (InvalidKeySpecException e){throw new Exception("私密金鑰非法");} catch (NullPointerException e){throw new Exception("私密金鑰資料為空白");}}/** * 從檔案中輸入資料流中載入公開金鑰 * * @param in * 公開金鑰輸入資料流 * @throws Exception * 載入公開金鑰時產生的異常 */private static PublicKey loadPublicKey(InputStream in) throws Exception{try{return loadPublicKey(readKey(in));} catch (IOException e){throw new Exception("公開金鑰資料流讀取錯誤");} catch (NullPointerException e){throw new Exception("公開金鑰輸入資料流為空白");}}/** * 從檔案中載入私密金鑰 * * @param keyFileName * 私密金鑰檔案名稱 * @return 是否成功 * @throws Exception */private static PrivateKey loadPrivateKey(InputStream in) throws Exception{try{return loadPrivateKey(readKey(in));} catch (IOException e){throw new Exception("私密金鑰資料讀取錯誤");} catch (NullPointerException e){throw new Exception("私密金鑰輸入資料流為空白");}}/** * 讀取密鑰資訊 * * @param in * @return * @throws IOException */private static String readKey(InputStream in) throws IOException{BufferedReader br = new BufferedReader(new InputStreamReader(in));String readLine = null;StringBuilder sb = new StringBuilder();while ((readLine = br.readLine()) != null){if (readLine.charAt(0) == '-'){continue;} else{sb.append(readLine);sb.append('\r');}}br.close();return sb.toString();}/** * 列印公開金鑰資訊 * * @param publicKey */private static void printPublicKeyInfo(PublicKey publicKey){RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;System.out.println("----------RSAPublicKey----------");System.out.println("Modulus.length=" + rsaPublicKey.getModulus().bitLength());System.out.println("Modulus=" + rsaPublicKey.getModulus().toString());System.out.println("PublicExponent.length=" + rsaPublicKey.getPublicExponent().bitLength());System.out.println("PublicExponent=" + rsaPublicKey.getPublicExponent().toString());}private static void printPrivateKeyInfo(PrivateKey privateKey){RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;System.out.println("----------RSAPrivateKey ----------");System.out.println("Modulus.length=" + rsaPrivateKey.getModulus().bitLength());System.out.println("Modulus=" + rsaPrivateKey.getModulus().toString());System.out.println("PrivateExponent.length=" + rsaPrivateKey.getPrivateExponent().bitLength());System.out.println("PrivatecExponent=" + rsaPrivateKey.getPrivateExponent().toString());}}
package com.yagou.yggx.android.utils.rsa;import java.io.UnsupportedEncodingException;/** * @author Mr.Zheng * @date 2014年8月22日 下午9:50:28 */class Base64Utils{private static char[] base64EncodeChars = new char[]{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T','U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5','6', '7', '8', '9', '+', '/' };private static byte[] base64DecodeChars = new byte[]{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,-1, -1, -1 };/** * 加密 * * @param data * @return */public static String encode(byte[] data){StringBuffer sb = new StringBuffer();int len = data.length;int i = 0;int b1, b2, b3;while (i < len){b1 = data[i++] & 0xff;if (i == len){sb.append(base64EncodeChars[b1 >>> 2]);sb.append(base64EncodeChars[(b1 & 0x3) << 4]);sb.append("==");break;}b2 = data[i++] & 0xff;if (i == len){sb.append(base64EncodeChars[b1 >>> 2]);sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);sb.append("=");break;}b3 = data[i++] & 0xff;sb.append(base64EncodeChars[b1 >>> 2]);sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);sb.append(base64EncodeChars[b3 & 0x3f]);}return sb.toString();}/** * 解密 * * @param str * @return */public static byte[] decode(String str){try{return decodePrivate(str);} catch (UnsupportedEncodingException e){e.printStackTrace();}return new byte[]{};}private static byte[] decodePrivate(String str) throws UnsupportedEncodingException{StringBuffer sb = new StringBuffer();byte[] data = null;data = str.getBytes("US-ASCII");int len = data.length;int i = 0;int b1, b2, b3, b4;while (i < len){do{b1 = base64DecodeChars[data[i++]];} while (i < len && b1 == -1);if (b1 == -1)break;do{b2 = base64DecodeChars[data[i++]];} while (i < len && b2 == -1);if (b2 == -1)break;sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));do{b3 = data[i++];if (b3 == 61)return sb.toString().getBytes("iso8859-1");b3 = base64DecodeChars[b3];} while (i < len && b3 == -1);if (b3 == -1)break;sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));do{b4 = data[i++];if (b4 == 61)return sb.toString().getBytes("iso8859-1");b4 = base64DecodeChars[b4];} while (i < len && b4 == -1);if (b4 == -1)break;sb.append((char) (((b3 & 0x03) << 6) | b4));}return sb.toString().getBytes("iso8859-1");}}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
安卓RSA加密,適配javaweb