這期內容當中小編將會給大家?guī)碛嘘P如何在java中實現(xiàn)RSA非對稱加密算法,文章內容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
創(chuàng)新互聯(lián)-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設、高性價比宜黃網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式宜黃網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設找我們,業(yè)務覆蓋宜黃地區(qū)。費用合理售后完善,十多年實體公司更值得信賴。
初始化密鑰:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(512); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPrivateKey rsaprivateKey = (RSAPrivateKey)keyPair.getPrivate();//私有密鑰 RSAPublicKey rsapublicKey = (RSAPublicKey)keyPair.getPublic();//公有密鑰 System.out.println("privateKey : "+Base64.encodeBase64String(rsaprivateKey.getEncoded())); System.out.println("publicKey : "+Base64.encodeBase64String(rsapublicKey.getEncoded()));
1、私鑰加密,公鑰解密:
//私鑰加密,公鑰解密--加密 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaprivateKey.getEncoded()); KeyFactory privateKeyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = privateKeyFactory.generatePrivate(pkcs8EncodedKeySpec); Cipher privateCipher = Cipher.getInstance("RSA"); privateCipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] result = privateCipher.doFinal(src.getBytes()); System.out.println("私鑰加密,公鑰解密--加密:"+Base64.encodeBase64String(result)); //私鑰加密,公鑰解密--解密 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsapublicKey.getEncoded()); KeyFactory publicKeyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = publicKeyFactory.generatePublic(x509EncodedKeySpec); Cipher publicCipher = Cipher.getInstance("RSA"); publicCipher.init(Cipher.DECRYPT_MODE, publicKey); result = publicCipher.doFinal(result); System.out.println("私鑰加密,公鑰解密--解密:"+new String(result));
2、公鑰加密,私鑰解密:
//公鑰加密,私鑰解密---加密 x509EncodedKeySpec = new X509EncodedKeySpec(rsapublicKey.getEncoded()); publicKeyFactory = KeyFactory.getInstance("RSA"); publicKey = publicKeyFactory.generatePublic(x509EncodedKeySpec); publicCipher = Cipher.getInstance("RSA"); publicCipher.init(Cipher.ENCRYPT_MODE, publicKey); result = publicCipher.doFinal(src.getBytes()); System.out.println("公鑰加密,私鑰解密---加密:"+Base64.encodeBase64String(result)); //公鑰加密,私鑰解密---解密 pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaprivateKey.getEncoded()); privateKeyFactory = KeyFactory.getInstance("RSA"); privateKey = privateKeyFactory.generatePrivate(pkcs8EncodedKeySpec); privateCipher = Cipher.getInstance("RSA"); privateCipher.init(Cipher.DECRYPT_MODE, privateKey); result = privateCipher.doFinal(result); System.out.println("公鑰加密,私鑰解密---解密:"+new String(result));
上述就是小編為大家分享的如何在java中實現(xiàn)RSA非對稱加密算法了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道。