Android RSA&SHA加密
阿新 • • 發佈:2021-01-29
前言
RSA允許你選擇公鑰的大小。512位的金鑰被視為不安全的;768位的金鑰不用擔心受到除了國家安全管理(NSA)外的其他事物的危害;1024位的金鑰幾乎是安全的。RSA在一些主要產品內部都有嵌入,像 Windows、網景 Navigator、 Quicken和 Lotus Notes。
RSA公開金鑰密碼體制的原理是:根據數論,尋求兩個大素數比較簡單,而將它們的乘積進行因式分解卻極其困難,因此可以將乘積公開作為加密金鑰。
(1)任意選取兩個不同的大素數p和q計算乘積;
(2)任意選取一個大整數e,滿足
整數e用做加金鑰(注意:e的選取是很容易的,例如,所有大於p和q的素數都可用);
(3)確定的解金鑰d,滿足
即
是一個任意的整數;所以,若知道e和
,則很容易計算出d;
(4)公開整數n和e,祕密儲存d;
(5)將明文m(m<n是一個整數)加密成密文c,加密演算法為
(6)將密文c解密為明文m,解密演算法為
然而只根據n和e(注意:不是p和q)要計算出d是不可能的。因此,任何人都可對明文進行加密,但只有授權使用者(知道d)才可對密文解密。
1.線上加密解密
https://www.bejson.com/enc/rsa/
https://www.bejson.com/enc/sha/
2.RSA加密
RSA加密需要金鑰,具體金鑰字串需要自己定義
public static String getRSAPublidKeyBybase64(String KEY, String text) { Cipher cipher; try { cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//Android上使用 byte[] publicBytes = Base64.decode(KEY.getBytes(StandardCharsets.UTF_8), Base64.DEFAULT); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(keySpec); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] encryptedBytes = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8)); return Base64.encodeToString(encryptedBytes, Base64.DEFAULT); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException | InvalidKeySpecException e) { e.printStackTrace(); } return ""; }
3.SHA加密
SHA加密型別
輸入加密型別時:SHA-512
/** * SHA加密 * @param strText 待加密的字串 * @param strType 加密型別 * @return 加密後的字串 */ public static String SHA(final String strText, final String strType) { // 返回值 String strResult = null; // 是否是有效字串 if (strText != null && strText.length() > 0) { try { // SHA 加密開始 // 建立加密物件 並傳入加密型別 MessageDigest messageDigest = MessageDigest.getInstance(strType); // 傳入要加密的字串 messageDigest.update(strText.getBytes()); // 得到 byte 型別結果 byte[] byteBuffer = messageDigest.digest(); // 將 byte 轉換為 string StringBuilder strHexString = new StringBuilder(); // 遍歷 byte buffer for (byte b : byteBuffer) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) { strHexString.append('0'); } strHexString.append(hex); } // 得到返回結果 strResult = strHexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return strResult; }