Android RSA加密,通過模數和指數生成秘鑰在加密遇到的坑


這是我第一篇博客,是因為后台傳過來16位的模數和指數讓前段自己生成秘鑰並進行加密 ,網上有很多類似的的功能, 我看過很多大神寫的資料,在做成功,廢話不說看代碼

 KeyPairGenerator keyPairGen = null; 
                try {
		 
keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
//從后台獲取的模數和指數轉成大整數  
//16也就是16位的意思,后台傳過來是16位的也這樣寫 RSAPublicKeySpec keySpec = new RSAPublicKeySpec( new BigInteger(easyWorkerApp. modulus, 16), new BigInteger(pe, 16)); KeyFactory factory = KeyFactory. getInstance( "RSA"); publicKey = (RSAPublicKey)factory.generatePublic(keySpec); // RSA/ECB/PKCS1PADDING" 必須這樣寫 只寫rsa 必然失敗,
// 對數據加密
//http://blog.csdn.net/zhengbin_mei/article/details/50803907 這篇博客找到的問題,感謝作者  Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
                    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
                    byte[] encryptedData = cipher.doFinal(password.getBytes());
                    KLog.e("TAs", new String(Base64Coder.encode(encryptedData)));
//這個包我是從網上下的 轉碼用 
                    s1 = new String(Base64Coder.encode(encryptedData));
 
//下面是解密 想看就看看 不想看直接傳 s1給后台就ok // //PrivateKey轉換處理 // String PrivateExponent = "c9917e337b0fd30a8dc1b9addfeb5f205feecf583f1f9da1c1075852c52e540c0c97ccfd415fe6465aa55130f9684ebb1092dc654705c0ff54b2e6711556072f32f9896020fc53846296b62fb1d750216d6e4be5408794f7f2982f9300bd93fa5be25a2b74f111c2422542dee7f50c07dcfd7b5fcc9f3cceab7657945bb7e1e1"; // RSAPrivateKeySpec pkspec = new RSAPrivateKeySpec(new BigInteger(modulus, 16), new BigInteger(PrivateExponent, 16)); // privateKey = (RSAPrivateKey) factory.generatePrivate(pkspec); ////解密 // byte[] encryptedDatass = Base64Coder.decodeLines(encryptedString); // byte[] privatemima = RSAUtils.decryptData(encryptedDatass, privateKey); // KLog.e("tas", new String(privatemima)); // KLog.e("tas", privatemima);  } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    KLog.e("TAs", e);
                    e.printStackTrace();
                }


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com