Android使用RSA加密和解密的示例代碼
一、公鑰加密和私鑰解密
/**RSA算法*/ public static final String RSA = "RSA"; /**加密方式,android的*/ // public static final String TRANSFORMATION = "RSA/None/NoPadding"; /**加密方式,標(biāo)準(zhǔn)jdk的*/ public static final String TRANSFORMATION = "RSA/None/PKCS1Padding"; /** 使用公鑰加密 */ public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception { // 得到公鑰對(duì)象 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(keySpec); // 加密數(shù)據(jù) Cipher cp = Cipher.getInstance(TRANSFORMATION); cp.init(Cipher.ENCRYPT_MODE, pubKey); return cp.doFinal(data); } /** 使用私鑰解密 */ public static byte[] decryptByPrivateKey(byte[] encrypted, byte[] privateKey) throws Exception { // 得到私鑰對(duì)象 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey); KeyFactory kf = KeyFactory.getInstance(RSA); PrivateKey keyPrivate = kf.generatePrivate(keySpec); // 解密數(shù)據(jù) Cipher cp = Cipher.getInstance(TRANSFORMATION); cp.init(Cipher.DECRYPT_MODE, keyPrivate); byte[] arr = cp.doFinal(encrypted); return arr; }
1.data是要加密的數(shù)據(jù),如果是字符串則getBytes。publicKey是公鑰,privateKey是私鑰。自定義密鑰對(duì)測(cè)試
String data = "hello world"; try { int keyLength = 1024; //生成密鑰對(duì) KeyPair keyPair = RSAUtils.generateRSAKeyPair(keyLength); //獲取公鑰 byte[] publicKey = RSAUtils.getPublicKey(keyPair); //獲取私鑰 byte[] privateKey = RSAUtils.getPrivateKey(keyPair); //用公鑰加密 byte[] encrypt = RSAUtils.encryptByPublicKey(data.getBytes(), publicKey); Log.d("TAG", "加密后的數(shù)據(jù):" + StringUtils.byteArrayToString(encrypt)); //用私鑰解密 byte[] decrypt = RSAUtils.decryptByPrivateKey(encrypt, privateKey); Log.d("TAG", "解密后的數(shù)據(jù):" + new String(decrypt, "utf-8")); } catch (Exception e) { e.printStackTrace(); }
2.從文件中讀取公鑰
String data = "hello world"; //讀取公鑰文件 String publicKeyString = IOUtils.readAssetsFile(this, "rsa_public_key.pem"); //base64解碼 byte[] publicKey = Base64Utils.decodeToBytes(publicKeyString); try { //加密 byte[] encrypt = RSAUtils.encryptByPublicKey(data.getBytes(), publicKey); Log.d("TAG", "加密后的數(shù)據(jù):" + StringUtils.byteArrayToString(encrypt)); // //讀取私鑰文件 // String privateKeyString = IOUtils.readAssetsFile(this, "rsa_private_key.pem"); // //base64解碼 // byte[] privateKey = Base64Utils.decodeToBytes(privateKeyString); // //解密 // byte[] decrypt = RSAUtils.decryptByPrivateKey(encrypt, privateKey); // Log.d("TAG", "解密后的數(shù)據(jù):" + new String(decrypt, "utf-8")); } catch (Exception e) { e.printStackTrace(); }
二、公鑰分段加密和私鑰分段解密
當(dāng)加密的數(shù)據(jù)過(guò)長(zhǎng)時(shí),會(huì)出現(xiàn)javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes的異常。rsa算法規(guī)定一次加密的數(shù)據(jù)不能超過(guò)生成密鑰對(duì)時(shí)的keyLength/8-11,keyLength一般是1024個(gè)字節(jié),則加密的數(shù)據(jù)不能超過(guò)117個(gè)字節(jié)
/**秘鑰默認(rèn)長(zhǎng)度*/ public static final int DEFAULT_KEY_SIZE = 1024; /**加密的數(shù)據(jù)最大的字節(jié)數(shù),即117個(gè)字節(jié)*/ public static final int DEFAULT_BUFFERSIZE = (DEFAULT_KEY_SIZE / 8) - 11; /**當(dāng)加密的數(shù)據(jù)超過(guò)DEFAULT_BUFFERSIZE,則使用分段加密*/ public static final byte[] DEFAULT_SPLIT = "#PART#".getBytes(); /** 使用公鑰分段加密 */ public static byte[] encryptByPublicKeyForSpilt(byte[] data, byte[] publicKey) throws Exception{ int dataLen = data.length; if (dataLen <= DEFAULT_BUFFERSIZE) { return encryptByPublicKey(data, publicKey); } List<Byte> allBytes = new ArrayList<Byte>(2048); int bufIndex = 0; int subDataLoop = 0; byte[] buf = new byte[DEFAULT_BUFFERSIZE]; for (int i = 0; i < dataLen; i++) { buf[bufIndex] = data[i]; if (++bufIndex == DEFAULT_BUFFERSIZE || i == dataLen - 1) { subDataLoop++; if (subDataLoop != 1) { for (byte b : DEFAULT_SPLIT) { allBytes.add(b); } } byte[] encryptBytes = encryptByPublicKey(buf, publicKey); for (byte b : encryptBytes) { allBytes.add(b); } bufIndex = 0; if (i == dataLen - 1) { buf = null; } else { buf = new byte[Math .min(DEFAULT_BUFFERSIZE, dataLen - i - 1)]; } } } byte[] bytes = new byte[allBytes.size()]; int i = 0; for (Byte b : allBytes) { bytes[i++] = b.byteValue(); } return bytes; } /** 使用私鑰分段解密 */ public static byte[] decryptByPrivateKeyForSpilt(byte[] encrypted, byte[] privateKey) throws Exception { int splitLen = DEFAULT_SPLIT.length; if (splitLen <= 0) { return decryptByPrivateKey(encrypted, privateKey); } int dataLen = encrypted.length; List<Byte> allBytes = new ArrayList<Byte>(1024); int latestStartIndex = 0; for (int i = 0; i < dataLen; i++) { byte bt = encrypted[i]; boolean isMatchSplit = false; if (i == dataLen - 1) { // 到data的最后了 byte[] part = new byte[dataLen - latestStartIndex]; System.arraycopy(encrypted, latestStartIndex, part, 0, part.length); byte[] decryptPart = decryptByPrivateKey(part, privateKey); for (byte b : decryptPart) { allBytes.add(b); } latestStartIndex = i + splitLen; i = latestStartIndex - 1; } else if (bt == DEFAULT_SPLIT[0]) { // 這個(gè)是以split[0]開(kāi)頭 if (splitLen > 1) { if (i + splitLen < dataLen) { // 沒(méi)有超出data的范圍 for (int j = 1; j < splitLen; j++) { if (DEFAULT_SPLIT[j] != encrypted[i + j]) { break; } if (j == splitLen - 1) { // 驗(yàn)證到split的最后一位,都沒(méi)有break,則表明已經(jīng)確認(rèn)是split段 isMatchSplit = true; } } } } else { // split只有一位,則已經(jīng)匹配了 isMatchSplit = true; } } if (isMatchSplit) { byte[] part = new byte[i - latestStartIndex]; System.arraycopy(encrypted, latestStartIndex, part, 0, part.length); byte[] decryptPart = decryptByPrivateKey(part, privateKey); for (byte b : decryptPart) { allBytes.add(b); } latestStartIndex = i + splitLen; i = latestStartIndex - 1; } } byte[] bytes = new byte[allBytes.size()]; int i = 0; for (Byte b : allBytes) { bytes[i++] = b.byteValue(); } return bytes; }
測(cè)試分段加密和解密
String data = "hello world hello world hello world hello world hello world hello world hello world hello world " + "hello world hello world hello world hello world hello world hello world hello world hello world hello world " + "hello world hello world hello world hello world hello world hello world hello world hello world hello world "; Log.d("TAG", "要加密的數(shù)據(jù):" + data + ", 要加密的數(shù)據(jù)長(zhǎng)度:" + data.length()); try { //分段加密 byte[] encrypt = RSAUtils.encryptByPublicKeyForSpilt(data.getBytes(), publicKey); Log.d("TAG", "加密后的數(shù)據(jù):" + StringUtils.byteArrayToString(encrypt)); //分段解密 byte[] decrypt = RSAUtils.decryptByPrivateKeyForSpilt(encrypt, privateKey); Log.d("TAG", "解密后的數(shù)據(jù):" + new String(decrypt, "utf-8")); } catch (Exception e) { e.printStackTrace(); }
三、生成密鑰對(duì)
/** 生成密鑰對(duì),即公鑰和私鑰。key長(zhǎng)度是512-2048,一般為1024 */ public static KeyPair generateRSAKeyPair(int keyLength) throws NoSuchAlgorithmException { KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA); kpg.initialize(keyLength); return kpg.genKeyPair(); } /** 獲取公鑰,打印為48-12613448136942-12272-122-913111503-126115048-12...等等一長(zhǎng)串用-拼接的數(shù)字 */ public static byte[] getPublicKey(KeyPair keyPair) { RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); return rsaPublicKey.getEncoded(); } /** 獲取私鑰,同上 */ public static byte[] getPrivateKey(KeyPair keyPair) { RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); return rsaPrivateKey.getEncoded(); }
生成公鑰和私鑰后,用base64編碼
int keyLength = 1024; try { //生成密鑰對(duì) KeyPair keyPair = RSAUtils.generateRSAKeyPair(keyLength); //獲取公鑰 byte[] publicKey = RSAUtils.getPublicKey(keyPair); Log.d("TAG", "公鑰:" + StringUtils.byteArrayToString(publicKey)); //公鑰用base64編碼 String encodePublic = Base64Utils.encodeToString(publicKey); Log.d("TAG", "base64編碼的公鑰:" + encodePublic); //獲取私鑰 byte[] privateKey = RSAUtils.getPrivateKey(keyPair); Log.d("TAG", "私鑰:" + StringUtils.byteArrayToString(privateKey)); //私鑰用base64編碼 String encodePrivate = Base64Utils.encodeToString(privateKey); Log.d("TAG", "base64編碼的私鑰:" + encodePrivate); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
其它
一、android加密的數(shù)據(jù)服務(wù)器上無(wú)法解密?
android的rsa加密方式是RSA/ECB/NoPadding,而標(biāo)準(zhǔn)jdk是RSA/ECB/PKCS1Padding,所以加密時(shí)要設(shè)置標(biāo)準(zhǔn)jdk的加密方式
二、base64編碼。因?yàn)椴煌脑O(shè)備對(duì)字符的處理方式不同,字符有可能處理出錯(cuò),不利于傳輸。所以先把數(shù)據(jù)做base64編碼,變成可見(jiàn)字符,減少出錯(cuò)
官方提供的base64類(lèi),Base64.encode編碼,Base64.decode解碼。用這個(gè)會(huì)有換行符,需要自定義
三、rsa是非對(duì)稱加密算法。依賴于大數(shù)計(jì)算,加密速度比des慢,通常只用于加密少量數(shù)據(jù)或密鑰
四、公鑰加密比私鑰加密塊,公鑰解密比私鑰解密慢。加密后的數(shù)據(jù)大概是加密前的1.5倍
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android中AlertDialog各種對(duì)話框的用法實(shí)例詳解
這篇文章主要介紹了Android中AlertDialog各種對(duì)話框的用法在項(xiàng)目開(kāi)發(fā)中經(jīng)常用的到,本文給大家介紹的非常詳細(xì),具有參考借鑒價(jià)值2016-04-04簡(jiǎn)單實(shí)現(xiàn)Android倒計(jì)時(shí)效果
這篇文章主要教大家如何簡(jiǎn)單的實(shí)現(xiàn)Android倒計(jì)時(shí)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10Android開(kāi)發(fā)優(yōu)化之Apk瘦身優(yōu)化指南
隨著業(yè)務(wù)快速發(fā)展,各種業(yè)務(wù)功能上線,版本不斷迭代,apk體積也越來(lái)越大,下面這篇文章主要給大家介紹了關(guān)于Android開(kāi)發(fā)優(yōu)化之Apk瘦身優(yōu)化的相關(guān)資料,需要的朋友可以參考下2022-05-05淺談Android單元測(cè)試的作用以及簡(jiǎn)單示例
本篇文章主要介紹了淺談Android單元測(cè)試的作用以及簡(jiǎn)單示例,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08Android網(wǎng)絡(luò)請(qǐng)求框架Retrofit詳解
這篇文章主要為大家詳細(xì)介紹了Android網(wǎng)絡(luò)請(qǐng)求框架Retrofit,使用Retrofit2.0.0版本進(jìn)行實(shí)例演示,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08Android 對(duì)話框sweet-alert-dialog
這篇文章主要介紹了Android 對(duì)話框sweet-alert-dialog的相關(guān)資料,需要的朋友可以參考下2016-09-09快速解決android webview https圖片不顯示的問(wèn)題
今天小編就為大家分享一篇快速解決android webview https圖片不顯示的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07Android 創(chuàng)建/驗(yàn)證/刪除桌面快捷方式(已測(cè)試可用)
桌面快捷方式的出現(xiàn)方便了用戶操作,在某些程度上提高了用戶體驗(yàn),接下來(lái)將介紹下Android創(chuàng)建/驗(yàn)證/刪除桌面快捷方式的實(shí)現(xiàn)思路及代碼,感興趣的朋友可以了解下,或許本文可以幫助到你2013-02-02Ubuntu中為Android HAL編寫(xiě)JNI方法提供JAVA訪問(wèn)硬件服務(wù)接口
本文主要介紹Ubuntu中為Android硬件抽象層模塊編寫(xiě)JNI方法提供Java訪問(wèn)硬件服務(wù)接口,這里給大家詳細(xì)說(shuō)明如何編寫(xiě) JNI方法訪問(wèn)硬件接口并附示例代碼,有需要的小伙伴參考下2016-08-08