您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關如何在java中實現RSA非對稱加密算法,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
初始化密鑰:
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中實現RSA非對稱加密算法了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。