編輯:關於Android編程
概述
RSA是目前最有影響力的公鑰加密算法,該算法基於一個十分簡單的數論事實:將兩個大素數相乘十分容易,但那時想要對其乘積進行因式分解卻極其困 難,因此可以將乘積公開作為加密密鑰,即公鑰,而兩個大素數組合成私鑰。公鑰是可發布的供任何人使用,私鑰則為自己所有,供解密之用。關於RSA其它需要了解的知識,參考維基百科:http://zh.wikipedia.org/zh-cn/RSA%E5%8A%A0%E5%AF%86%E6%BC%94%E7%AE%97%E6%B3%95
在項目開發中對於一些比較敏感的信息需要對其進行加密處理,我們就可以使用RSA這種非對稱加密算法來對數據進行加密處理。
使用
秘鑰對的生成
1、我們可以在代碼裡隨機生成密鑰對
/** * 隨機生成RSA密鑰對 * * @param keyLength * 密鑰長度,范圍:512~2048 * 一般1024 * @return */ public static KeyPair generateRSAKeyPair(int keyLength) { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA); kpg.initialize(keyLength); return kpg.genKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
2、通過OpenSSl工具生成密鑰對
OpenSSl工具下載:OpenSSl工具 (64位的也可使用)使用OpenSSl工具生成密鑰對的過程如下:
首先雙擊打開bin文件夾下的openssl.exe,打開之後是一個命令行窗口:
然後通過如下命令生成私鑰:
genrsa -out rsa_private_key.pem 1024
這條命令是讓openssl隨機生成了一份私鑰,加密長度是1024位, 密鑰長度,范圍:512~2048。執行完命令後就可在bin文件夾下看到rsa_private_key.pem文件了。
用文本類工具打開可看到裡面的內容:
-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQCfRTdcPIH10gT9f31rQuIInLwe7fl2dtEJ93gTmjE9c2H+kLVE NWgECiJVQ5sonQNfwToMKdO0b3Olf4pgBKeLThraz/L3nYJYlbqjHC3jTjUnZc0l uumpXGsox62+PuSGBlfb8zJO6hix4GV/vhyQVCpG9aYqgE7zyTRZYX9byQIDAQAB AoGAO9+sYRtKC9xJDfcocfMxv+UT/1ic6EDgcqu6Uzwq+Jvwod9KlXqyQJqCr6T7 pjfodc3RAZOTx4gCZJverBvz053RH5GawCdocEgaqbXAAWJOhA+9IEU0NUud7ckF yDko0QXLoGP9tanrMEt5zMqt8QxDyl6Xcij3mk8rivOgBJECQQDNTO6dZX8xCozc Ne0gzC53Gv/KQXANBBHMr7WkKUb2i5+tXkEJ5z3abx2ppEQXDr4AgJH8Gtbm6K7t EHV4ov4FAkEAxppD/iiT1/SVQq20be8CsiHpsjTPiestWQWdm1Qn/Y2nAkGkpCFp yEdUvVDPtQhRN9EqNggNAnwg5kMvsuwN9QJAfHBhQe4/hk5Kyz+0l+irUW6AFOxN KtaIo3TtuK98X/yJsOAstAACMeCgLi9vRjqdWFiWJCVwlU38mZ0cVx8UsQJBALzt M5Er+LiPKw5rQCD0JZRfPnkQU/3XgyQUe4Gv5PsHLcCvwXeBcafcc3hEz9JfPyPi Dk2oCvg6LPHfKBkFBaECQQCODcKX6DBWiyVxmPaJOOcF63KpCYDPkjeovIUHro1x ElR2GrQCC/9Q4C4vruOhBQ+vX8NMPnO6NBy5TLGDwMyc -----END RSA PRIVATE KEY-----
然後通過如下命令生成公鑰:
rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout
打開文件看下裡面的內容:
-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfRTdcPIH10gT9f31rQuIInLwe 7fl2dtEJ93gTmjE9c2H+kLVENWgECiJVQ5sonQNfwToMKdO0b3Olf4pgBKeLThra z/L3nYJYlbqjHC3jTjUnZc0luumpXGsox62+PuSGBlfb8zJO6hix4GV/vhyQVCpG 9aYqgE7zyTRZYX9byQIDAQAB -----END PUBLIC KEY-----
這樣密鑰就基本生成了,不過這樣密鑰對的私鑰是無法在代碼中直接使用的,要想使用它需要借助RSAPrivateKeyStructure這個類,java是不自帶的。所以為了方便使用,我們需要對私鑰進行PKCS#8編碼,命令如下:
pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt
這條命令的結果依然是在bin文件夾生成了pkcs8_rsa_private_key.pem文件,打開內容如下:
-----BEGIN PRIVATE KEY----- MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ9FN1w8gfXSBP1/ fWtC4gicvB7t+XZ20Qn3eBOaMT1zYf6QtUQ1aAQKIlVDmyidA1/BOgwp07Rvc6V/ imAEp4tOGtrP8vedgliVuqMcLeNONSdlzSW66alcayjHrb4+5IYGV9vzMk7qGLHg ZX++HJBUKkb1piqATvPJNFlhf1vJAgMBAAECgYA736xhG0oL3EkN9yhx8zG/5RP/ WJzoQOByq7pTPCr4m/Ch30qVerJAmoKvpPumN+h1zdEBk5PHiAJkm96sG/PTndEf kZrAJ2hwSBqptcABYk6ED70gRTQ1S53tyQXIOSjRBcugY/21qeswS3nMyq3xDEPK XpdyKPeaTyuK86AEkQJBAM1M7p1lfzEKjNw17SDMLnca/8pBcA0EEcyvtaQpRvaL n61eQQnnPdpvHamkRBcOvgCAkfwa1uboru0QdXii/gUCQQDGmkP+KJPX9JVCrbRt 7wKyIemyNM+J6y1ZBZ2bVCf9jacCQaSkIWnIR1S9UM+1CFE30So2CA0CfCDmQy+y 7A31AkB8cGFB7j+GTkrLP7SX6KtRboAU7E0q1oijdO24r3xf/Imw4Cy0AAIx4KAu L29GOp1YWJYkJXCVTfyZnRxXHxSxAkEAvO0zkSv4uI8rDmtAIPQllF8+eRBT/deD JBR7ga/k+wctwK/Bd4Fxp9xzeETP0l8/I+IOTagK+Dos8d8oGQUFoQJBAI4Nwpfo MFaLJXGY9ok45wXrcqkJgM+SN6i8hQeujXESVHYatAIL/1DgLi+u46EFD69fw0w+ c7o0HLlMsYPAzJw= -----END PRIVATE KEY-----
以上的密鑰文件使用時需要注意吧頭和尾的字符串去掉,我們只取中間的內容。
代碼中的使用
首先我們需要封裝寫個RSA的工具類,方便加密解密的操作。
package com.example.rsa; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; 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 Mr.Zheng * @date 2014年8月22日 下午1:44:23 */ public final class RSAUtils { private static String RSA = RSA; /** * 隨機生成RSA密鑰對(默認密鑰長度為1024) * * @return */ public static KeyPair generateRSAKeyPair() { return generateRSAKeyPair(1024); } /** * 隨機生成RSA密鑰對 * * @param keyLength * 密鑰長度,范圍:512~2048 * 一般1024 * @return */ public static KeyPair generateRSAKeyPair(int keyLength) { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA); kpg.initialize(keyLength); return kpg.genKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /** * 用公鑰加密 * 每次加密的字節數,不能超過密鑰的長度值減去11 * * @param data * 需加密數據的byte數據 * @param pubKey * 公鑰 * @return 加密後的byte型數據 */ public static byte[] encryptData(byte[] data, PublicKey publicKey) { try { Cipher cipher = Cipher.getInstance(RSA); // 編碼前設定編碼方式及密鑰 cipher.init(Cipher.ENCRYPT_MODE, publicKey); // 傳入編碼數據並返回編碼結果 return cipher.doFinal(data); } catch (Exception e) { e.printStackTrace(); return null; } } /** * 用私鑰解密 * * @param encryptedData * 經過encryptedData()加密返回的byte數據 * @param privateKey * 私鑰 * @return */ public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey) { try { Cipher cipher = Cipher.getInstance(RSA); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(encryptedData); } catch (Exception e) { return null; } } /** * 通過公鑰byte[](publicKey.getEncoded())將公鑰還原,適用於RSA算法 * * @param keyBytes * @return * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public 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 */ public 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 */ public 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 */ public 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 * 加載公鑰時產生的異常 */ public 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(公鑰數據為空); } } /** * 從字符串中加載私鑰 * 加載時使用的是PKCS8EncodedKeySpec(PKCS#8編碼的Key指令)。 * * @param privateKeyStr * @return * @throws Exception */ public 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 * 加載公鑰時產生的異常 */ public 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 */ public 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(' '); } } return sb.toString(); } /** * 打印公鑰信息 * * @param publicKey */ public 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()); } public 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()); } }
上面需要注意的就是加密是有長度限制的,過長的話會拋異常!!!
代碼中有些需要使用Base64再轉換的,而java中不自帶,Android中自帶,所以自己寫出一個來,方便Java後台使用
package com.example.rsa; import java.io.UnsupportedEncodingException; /** * @author Mr.Zheng * @date 2014年8月22日 下午9:50:28 */ public 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); } }
package com.example.rsa; import java.io.InputStream; import java.security.PrivateKey; import java.security.PublicKey; import android.app.Activity; import android.os.Bundle; import android.util.Base64; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity implements OnClickListener { private Button btn1, btn2;// 加密,解密 private EditText et1, et2, et3;// 需加密的內容,加密後的內容,解密後的內容 /* 密鑰內容 base64 code */ private static String PUCLIC_KEY = MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfRTdcPIH10gT9f31rQuIInLwe + + 7fl2dtEJ93gTmjE9c2H+kLVENWgECiJVQ5sonQNfwToMKdO0b3Olf4pgBKeLThra + + z/L3nYJYlbqjHC3jTjUnZc0luumpXGsox62+PuSGBlfb8zJO6hix4GV/vhyQVCpG + + 9aYqgE7zyTRZYX9byQIDAQAB + ; private static String PRIVATE_KEY = MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ9FN1w8gfXSBP1/ + + fWtC4gicvB7t+XZ20Qn3eBOaMT1zYf6QtUQ1aAQKIlVDmyidA1/BOgwp07Rvc6V/ + + imAEp4tOGtrP8vedgliVuqMcLeNONSdlzSW66alcayjHrb4+5IYGV9vzMk7qGLHg + + ZX++HJBUKkb1piqATvPJNFlhf1vJAgMBAAECgYA736xhG0oL3EkN9yhx8zG/5RP/ + + WJzoQOByq7pTPCr4m/Ch30qVerJAmoKvpPumN+h1zdEBk5PHiAJkm96sG/PTndEf + + kZrAJ2hwSBqptcABYk6ED70gRTQ1S53tyQXIOSjRBcugY/21qeswS3nMyq3xDEPK + + XpdyKPeaTyuK86AEkQJBAM1M7p1lfzEKjNw17SDMLnca/8pBcA0EEcyvtaQpRvaL + + n61eQQnnPdpvHamkRBcOvgCAkfwa1uboru0QdXii/gUCQQDGmkP+KJPX9JVCrbRt + + 7wKyIemyNM+J6y1ZBZ2bVCf9jacCQaSkIWnIR1S9UM+1CFE30So2CA0CfCDmQy+y + + 7A31AkB8cGFB7j+GTkrLP7SX6KtRboAU7E0q1oijdO24r3xf/Imw4Cy0AAIx4KAu + + L29GOp1YWJYkJXCVTfyZnRxXHxSxAkEAvO0zkSv4uI8rDmtAIPQllF8+eRBT/deD + + JBR7ga/k+wctwK/Bd4Fxp9xzeETP0l8/I+IOTagK+Dos8d8oGQUFoQJBAI4Nwpfo + + MFaLJXGY9ok45wXrcqkJgM+SN6i8hQeujXESVHYatAIL/1DgLi+u46EFD69fw0w+ + + c7o0HLlMsYPAzJw= + ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { btn1 = (Button) findViewById(R.id.btn1); btn2 = (Button) findViewById(R.id.btn2); btn1.setOnClickListener(this); btn2.setOnClickListener(this); et1 = (EditText) findViewById(R.id.et1); et2 = (EditText) findViewById(R.id.et2); et3 = (EditText) findViewById(R.id.et3); } @Override public void onClick(View v) { switch (v.getId()) { // 加密 case R.id.btn1: String source = et1.getText().toString().trim(); try { // 從字符串中得到公鑰 // PublicKey publicKey = RSAUtils.loadPublicKey(PUCLIC_KEY); // 從文件中得到公鑰 InputStream inPublic = getResources().getAssets().open(rsa_public_key.pem); PublicKey publicKey = RSAUtils.loadPublicKey(inPublic); // 加密 byte[] encryptByte = RSAUtils.encryptData(source.getBytes(), publicKey); // 為了方便觀察吧加密後的數據用base64加密轉一下,要不然看起來是亂碼,所以解密是也是要用Base64先轉換 String afterencrypt = Base64Utils.encode(encryptByte); et2.setText(afterencrypt); } catch (Exception e) { e.printStackTrace(); } break; // 解密 case R.id.btn2: String encryptContent = et2.getText().toString().trim(); try { // 從字符串中得到私鑰 // PrivateKey privateKey = RSAUtils.loadPrivateKey(PRIVATE_KEY); // 從文件中得到私鑰 InputStream inPrivate = getResources().getAssets().open(pkcs8_rsa_private_key.pem); PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate); // 因為RSA加密後的內容經Base64再加密轉換了一下,所以先Base64解密回來再給RSA解密 byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(encryptContent), privateKey); String decryptStr = new String(decryptByte); et3.setText(decryptStr); } catch (Exception e) { e.printStackTrace(); } break; default: break; } } }
最後我們來看下效果吧:
源碼下載地址:http://download.csdn.net/detail/bbld_/7806673
在項目中有一個小功能需要實現,就是對多行文本進行排版布局,每一行的內容又分為兩部分,左邊為標題,右邊為描述,左邊內容長度不確定,右邊的內容需要對齊,如有換行
前言:近年來,智能電視的發展如火如荼,Googel 也在大力推進TV及穿帶設備的發展,在互聯網的風口,是豬也會飛,這句話並不是沒有道理的。傳統電視機廠商,基本都轉型致力於
Android WebView 1.首先修改activity.xml中的代碼:2.然後MainActivity中的代碼:3.最後設置權限:<uses-permiss
簡介好久沒有寫博客了,最近公司產品剛發布了,終於有一點休閒的時間了,趁這個空閒的時間,今天給大家寫一個數字動畫的效果,可能在以後的時間,或許大家會用的到,值得大家收藏,直