RSA的Java實現不能一次加密很大的字元,自己處理了一下,見下面的代碼。Base64編碼類用的是一個Public domain Base64 for java http://iharder.sourceforge.net/current/java/base64/其他的保存公鑰到文件等簡單的實現,就不詳細說了,看代碼吧。==============================================import java.security.*;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.HashMap;import java.util.Map;import javax.crypto.*;import java.io.*;public class Encryptor {private static final String KEY_FILENAME = "c:\\mykey.dat";private static final String OTHERS_KEY_FILENAME = "c:\\Otherskey.dat";// private static final int KEY_SIZE = 1024;// private static final int BLOCK_SIZE = 117;// private static final int OUTPUT_BLOCK_SIZE = 128;private static final int KEY_SIZE = 2048; //RSA key 是多少位的private static final int BLOCK_SIZE = 245; //一次RSA加密操作所允許的最大長度//這個值與 KEY_SIZE 已經padding方法有關。因為 1024的key的輸出是128,2048key輸出是256位元組//可能11個位元組用於保存padding信息了,所以最多可用的就只有245位元組了。private static final int OUTPUT_BLOCK_SIZE = 256;private SecureRandom secrand;private Cipher rsaCipher;private KeyPair keys;private Map<String, Key> allUserKeys;public Encryptor() throws Exception {try {allUserKeys = new HashMap<String, Key>();secrand = new SecureRandom();//SunJCE Provider 中只支持ECB mode,試了一下只有PKCS1PADDING可以直接還原原始數據,//NOPadding導致解壓出來的都是blocksize長度的數據,還要自己處理//參見 http://java.sun.com/javase/6/docs/technotes/guides/security/SunProviders.html#SunJCEProvider////另外根據 Open-JDK-6.b17-src( http://www.docjar.com/html/api/com/sun/crypto/provider/RSACipher.java.html)// 中代碼的注釋,使用RSA來加密大量數據不是一種標準的用法。所以現有實現一次doFinal調用之進行一個RSA操作,//如果用doFinal來加密超過的一個操作所允許的長度數據將拋出異常。//根據keysize的長度,典型的1024個長度的key和PKCS1PADDING一起使用時//一次doFinal調用只能加密117個byte的數據。(NOPadding 和1024 keysize時128個位元組長度)//(2048長度的key和PKCS1PADDING 最多允許245位元組一次)//想用來加密大量數據的只能自己用其他辦法實現了。可能RSA加密速度比較慢吧,要用AES才行rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();throw e;}ObjectInputStream in;try {in = new ObjectInputStream(new FileInputStream(KEY_FILENAME));} catch (FileNotFoundException e) {if (false == GenerateKeys()){throw e;}LoadKeys();return;}keys = (KeyPair) in.readObject();in.close();LoadKeys();}/** 生成自己的公鑰和私鑰*/private Boolean GenerateKeys() {try {KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");// secrand = new SecureRandom();// sedSeed之後會造成 生成的密鑰都是一樣的// secrand.setSeed("chatencrptor".getBytes()); // 初始化隨機產生器//key長度至少512長度,不過好像說現在用2048才算比較安全的了keygen.initialize(KEY_SIZE, secrand); // 初始化密鑰生成器keys = keygen.generateKeyPair(); // 生成密鑰組AddKey("me", EncodeKey(keys.getPublic()));} catch (NoSuchAlgorithmException e) {e.printStackTrace();return false;}ObjectOutputStream out;try {out = new ObjectOutputStream(new FileOutputStream(KEY_FILENAME));} catch (IOException e) {e.printStackTrace();return false;}try {out.writeObject(keys);} catch (IOException e) {e.printStackTrace();return false;} finally {try {out.close();} catch (IOException e) {e.printStackTrace();return false;}}return true;}public String EncryptMessage(String toUser, String Message) throws IOException {Key pubkey = allUserKeys.get(toUser);if ( pubkey == null ){throw new IOException("NoKeyForThisUser") ;}try {//PublicKey pubkey = keys.getPublic();rsaCipher.init(Cipher.ENCRYPT_MODE, pubkey, secrand);//System.out.println(rsaCipher.getBlockSize()); 返回0,非block 加密演算法來的?//System.out.println(Message.getBytes("utf-8").length);//byte[] encryptedData = rsaCipher.doFinal(Message.getBytes("utf-8"));byte[] data = Message.getBytes("utf-8");int blocks = data.length / BLOCK_SIZE ;int lastBlockSize = data.length % BLOCK_SIZE ;byte [] encryptedData = new byte[ (lastBlockSize == 0 ? blocks : blocks + 1)* OUTPUT_BLOCK_SIZE];for (int i=0; i < blocks; i++){//int thisBlockSize = ( i + 1 ) * BLOCK_SIZE > data.length ? data.length - i * BLOCK_SIZE : BLOCK_SIZE ;rsaCipher.doFinal(data,i * BLOCK_SIZE, BLOCK_SIZE, encryptedData ,i * OUTPUT_BLOCK_SIZE);}if (lastBlockSize != 0 ){rsaCipher.doFinal(data, blocks * BLOCK_SIZE, lastBlockSize,encryptedData ,blocks * OUTPUT_BLOCK_SIZE);}//System.out.println(encrypted.length); 如果要機密的數據不足128/256位元組,加密後補全成為變為256長度的。//數量比較小時,Base64.GZIP產生的長度更長,沒什麼優勢//System.out.println(Base64.encodeBytes(encrypted,Base64.GZIP).length());//System.out.println(Base64.encodeBytes(encrypted).length());//System.out.println (rsaCipher.getOutputSize(30));//這個getOutputSize 只對 輸入小於最大的block時才能得到正確的結果。其實就是補全 數據為128/256 位元組return Base64.encodeBytes(encryptedData);} catch (InvalidKeyException e) {e.printStackTrace();throw new IOException("InvalidKey") ;}catch (ShortBufferException e) {e.printStackTrace();throw new IOException("ShortBuffer") ;}catch (UnsupportedEncodingException e) {e.printStackTrace();throw new IOException("UnsupportedEncoding") ;} catch (IllegalBlockSizeException e) {e.printStackTrace();throw new IOException("IllegalBlockSize") ;} catch (BadPaddingException e) {e.printStackTrace();throw new IOException("BadPadding") ;}finally {//catch 中 return 或者throw之前都會先調用一下這里}}public String DecryptMessage(String Message) throws IOException {byte[] decoded = Base64.decode(Message);PrivateKey prikey = keys.getPrivate();try {rsaCipher.init(Cipher.DECRYPT_MODE, prikey, secrand);int blocks = decoded.length / OUTPUT_BLOCK_SIZE;ByteArrayOutputStream decodedStream = new ByteArrayOutputStream(decoded.length);for (int i =0 ;i < blocks ; i ++ ){decodedStream.write (rsaCipher.doFinal(decoded,i * OUTPUT_BLOCK_SIZE, OUTPUT_BLOCK_SIZE));}return new String(decodedStream.toByteArray(), "UTF-8");} catch (InvalidKeyException e) {e.printStackTrace();throw new IOException("InvalidKey");} catch (UnsupportedEncodingException e) {e.printStackTrace();throw new IOException("UnsupportedEncoding");} catch (IllegalBlockSizeException e) {e.printStackTrace();throw new IOException("IllegalBlockSize");} catch (BadPaddingException e) {e.printStackTrace();throw new IOException("BadPadding");} finally {// catch 中 return 或者throw之前都會先調用一下這里。}}public boolean AddKey(String user, String key) {PublicKey publickey;try {publickey = DecodePublicKey(key);} catch (Exception e) {return false;}allUserKeys.put(user, publickey);SaveKeys();return true;}private boolean LoadKeys() {BufferedReader input;try {input = new BufferedReader(new InputStreamReader(new FileInputStream(OTHERS_KEY_FILENAME)));} catch (FileNotFoundException e1) {// e1.printStackTrace();return false;}
2. java RSA演算法實現256位密鑰怎麼做
【下載實例】本文介紹RSA2加密與解密,RSA2是RSA的加強版本,在密鑰長度上採用2048, RSA2比RSA更安全,更可靠, 本人的另一篇文章RSA已經發表,有想了解的可以點開下面的RSA文章
3. java中RSA用私鑰加密公鑰解密問題
公鑰和私鑰可以互換的用,用公鑰加密私鑰解密,用私鑰加密公鑰解密都ok,方法一樣
4. JAVA寫RSA加密,公鑰私鑰都是一樣的,為什麼每次加密的結果不一樣
肯定會不一樣啊,因為加密過程中使用了salt,防止已知密文攻擊,你兩次加密的結果,用相同的私鑰去解密,會得到同樣的結果,前提是你的加密演算法沒寫錯
5. JAVA寫RSA加密,公鑰私鑰都是一樣的,為什麼每次加密的結果不一樣
RSA 的 PKCS #1 padding 方案在加密前對明文信息進行了隨機數填充。 這個博客解析這個的
w屏w蔽w.cnblogs.com/spencerN/archive/2012/10/18/2729602.html
6. Java中RSA的方式如何實現非對稱加密的示例
代碼如下,需要依賴一個jar包commons-codec-1.9.jar,用於Base64轉換,請自行下載。
importorg.apache.commons.codec.binary.Base64;
importjavax.crypto.BadPaddingException;
importjavax.crypto.Cipher;
importjavax.crypto.IllegalBlockSizeException;
importjava.io.ByteArrayOutputStream;
importjava.io.UnsupportedEncodingException;
importjava.security.*;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjava.security.spec.PKCS8EncodedKeySpec;
importjava.security.spec.X509EncodedKeySpec;
publicclassRSAUtils{
//加密方式
="RSA";
//簽名演算法
_ALGORITHM="SHA1WithRSA";
//創建密鑰對初始長度
privatestaticfinalintKEY_SIZE=512;
//字元編碼格式
="UTF-8";
//RSA最大加密明文大小
privatestaticfinalintMAX_ENCRYPT_BLOCK=117;
//RSA最大解密密文大小
privatestaticfinalintMAX_DECRYPT_BLOCK=128;
privateKeyFactorykeyFactory;
publicRSAUtils(){
keyFactory=KeyFactory.getInstance(ALGORITHM);
}
/**
*私鑰加密
*
*@paramcontent待加密字元串
*@paramprivateKey私鑰
*@return加密後字元串(BASE64編碼)
*/
(Stringcontent,StringprivateKey)throwsException{
Stringresult;
try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeypKey=keyFactory.generatePrivate(pkcs8KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,pKey);
byte[]data=content.getBytes(CHARSET);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();
result=Base64.encodeBase64String(resultBytes);
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
/**
*公鑰解密
*
*@paramcontent已加密字元串(BASE64加密)
*@parampublicKey公鑰
*@return
*/
(Stringcontent,StringpublicKey)throwsException{
Stringresult="";
try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypKey=keyFactory.generatePublic(x509KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,pKey);
byte[]data=Base64.decodeBase64(content);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();
result=newString(resultBytes);
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
/**
*公鑰加密
*
*@paramcontent待加密字元串
*@parampublicKey公鑰
*@return加密後字元串(BASE64編碼)
*/
(Stringcontent,StringpublicKey)throwsException{
Stringresult="";
try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpecx509KeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypKey=keyFactory.generatePublic(x509KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,pKey);
byte[]data=content.getBytes(CHARSET);
write2Stream(cipher,
data,out);
byte[]resultBytes=out.toByteArray();
result=Base64.encodeBase64String(resultBytes);
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
/**
*私鑰解密
*
*@paramcontent已加密字元串
*@paramprivateKey私鑰
*@return解密後字元串
*/
(Stringcontent,StringprivateKey)throwsException{
Stringresult="";
try(ByteArrayOutputStreamout=newByteArrayOutputStream()){
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeypKey=keyFactory.generatePrivate(pkcs8KeySpec);
Ciphercipher=Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,pKey);
byte[]data=Base64.decodeBase64(content);
write2Stream(cipher,data,out);
byte[]resultBytes=out.toByteArray();
result=newString(resultBytes);
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
privatestaticvoidwrite2Stream(Ciphercipher,byte[]data,ByteArrayOutputStreamout)throws
BadPaddingException,IllegalBlockSizeException{
intdataLen=data.length;
intoffSet=0;
byte[]cache;
inti=0;
//對數據分段解密
while(dataLen-offSet>0){
if(dataLen-offSet>MAX_DECRYPT_BLOCK){
cache=cipher.doFinal(data,offSet,MAX_DECRYPT_BLOCK);
}else{
cache=cipher.doFinal(data,offSet,dataLen-offSet);
}
out.write(cache,0,cache.length);
i++;
offSet=i*MAX_DECRYPT_BLOCK;
}
}
/**
*用私鑰對信息生成數字簽名
*
*@paramdata已加密數據
*@paramprivateKey私鑰(BASE64編碼)
*@returnsign
*/
publicStringsign(Stringdata,StringprivateKey)throwsException{
Stringresult="";
try{
byte[]keyBytes=newBase64().decode(privateKey);
=newPKCS8EncodedKeySpec(keyBytes);
PrivateKeyprivateK=keyFactory.generatePrivate(pkcs8KeySpec);
Signaturesignature=Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(privateK);
signature.update(parse2HexStr(data).getBytes(CHARSET));
result=newBase64().encodeToString(signature.sign());
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
/**
*校驗數字簽名
*
*@paramdata已加密數據
*@parampublicKey公鑰(BASE64編碼)
*@paramsign數字簽名
*@return
*@throwsException
*/
publicbooleanverify(Stringdata,StringpublicKey,Stringsign)throwsException{
booleanresult;
try{
byte[]keyBytes=newBase64().decode(publicKey);
X509EncodedKeySpeckeySpec=newX509EncodedKeySpec(keyBytes);
PublicKeypublicK=keyFactory.generatePublic(keySpec);
Signaturesignature=Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(publicK);
signature.update(parse2HexStr(data).getBytes(CHARSET));
result=signature.verify(newBase64().decode(sign));
}catch(Exceptione){
thrownewException(e);
}
returnresult;
}
/**
*將二進制轉換成16進制
*
*@paramdata
*@return
*/
(Stringdata)throwsException{
Stringresult="";
try{
byte[]buf=data.getBytes(CHARSET);
StringBuffersb=newStringBuffer();
for(inti=0;i<buf.length;i++){
Stringhex=Integer.toHexString(buf[i]&0xFF);
if(hex.length()==1){
hex='0'+hex;
}
sb.append(hex.toUpperCase());
}
result=sb.toString();
}catch(UnsupportedEncodingExceptione){
thrownewException(e);
}
returnresult;
}
/**
*生成公鑰與私鑰
*/
publicstaticvoidcreateKey()throwsException{
try{
=KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
KeyPairkeyPair=keyPairGenerator.generateKeyPair();
RSAPublicKeyrsaPublicKey=(RSAPublicKey)keyPair.getPublic();
RSAPrivateKeyrsaPrivateKey=(RSAPrivateKey)keyPair.getPrivate();
StringpublicKey=Base64.encodeBase64String(rsaPublicKey.getEncoded());
StringprivateKey=Base64.encodeBase64String(rsaPrivateKey.getEncoded());
System.out.println("publicKey="+publicKey+" privateKey="+privateKey);
}catch(NoSuchAlgorithmExceptione){
thrownewException(e);
}
}
publicstaticvoidmain(String[]args)throwsException{
StringPRIVATE_KEY="+m+/fNs1bmgfJhI8lhr/o/Hy8EFB/I/DDyLcCcU4bCLtxpki8edC+KJR2WvyYfnVmWEe//++W5C+lesEOAqdO5nahRZsL8BIDoxTEn2j+DSa///1qX+t8f5wD8i/8GU702PeCwkGI5ymrARq+/+/nkefTq0SNpUDVbGxVpJi9/FOUf";
StringPUBLIC_KEY="+lc///NfOvKvQndzDH60DzLGOMdE0NBrTn/5zEjGwJbVdlvCfOiHwIDAQAB";
RSAUtilsrsaUtil=newRSAUtils();
StringencryptByPublicKey=rsaUtil.encryptByPublicKey("你好!",PUBLIC_KEY);
System.out.println(encryptByPublicKey);
StringdecryptByPrivateKey=rsaUtil.decryptByPrivateKey(encryptByPublicKey,PRIVATE_KEY);
System.out.println(decryptByPrivateKey);
StringencryptByPrivateKey=rsaUtil.encryptByPrivateKey("你好!",PRIVATE_KEY);
System.out.println(encryptByPrivateKey);
StringdecryptByPublicKey=rsaUtil.decryptByPublicKey(encryptByPrivateKey,PUBLIC_KEY);
System.out.println(decryptByPublicKey);
Stringsign=rsaUtil.sign("1234",PRIVATE_KEY);
System.out.println("sign:"+sign);
System.out.println(rsaUtil.verify("1234",PUBLIC_KEY,sign));
}
}
7. java rsa私鑰加密
java rsa私鑰加密是什麼?讓我們一起來了解一下吧!
java rsa私鑰加密是一種加密演算法。私鑰加密演算法是用私鑰來進行加密與解密信息。私鑰加密也被稱作對稱加密,原因是加密與解密使用的秘鑰是同一個。
RSA加密需要注意的事項如下:
1. 首先產生公鑰與私鑰
2. 設計加密與解密的演算法
3. 私鑰加密的數據信息只能由公鑰可以解密
4. 公鑰加密的數據信息只能由私鑰可以解密
實戰演練,具體步驟如下: public class RsaCryptTools { private static final String CHARSET = "utf-8"; private static final Base64.Decoder decoder64 = Base64.getDecoder(); private static final Base64.Encoder encoder64 = Base64.getEncoder(); /** * 生成公私鑰 * @param keySize * @return * @throws NoSuchAlgorithmException */ public static SecretKey generateSecretKey(int keySize) throws NoSuchAlgorithmException { //生成密鑰對 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(keySize, new SecureRandom()); KeyPair pair = keyGen.generateKeyPair(); PrivateKey privateKey = pair.getPrivate(); PublicKey publicKey = pair.getPublic(); //這里可以將密鑰對保存到本地 return new SecretKey(encoder64.encodeToString(publicKey.getEncoded()), encoder64.encodeToString(privateKey.getEncoded())); } /** * 私鑰加密 * @param data * @param privateInfoStr * @return * @throws IOException * @throws InvalidCipherTextException */ public static String encryptData(String data, String privateInfoStr) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, getPrivateKey(privateInfoStr)); return encoder64.encodeToString(cipher.doFinal(data.getBytes(CHARSET))); } /** * 公鑰解密 * @param data * @param publicInfoStr * @return */ public static String decryptData(String data, String publicInfoStr) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException { byte[] encryptDataBytes=decoder64.decode(data.getBytes(CHARSET)); //解密 Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, getPublicKey(publicInfoStr)); return new String(cipher.doFinal(encryptDataBytes), CHARSET); } private static PublicKey getPublicKey(String base64PublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes())); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(keySpec); } private static PrivateKey getPrivateKey(String base64PrivateKey) throws NoSuchAlgorithmException, InvalidKeySpecException { PrivateKey privateKey = null; PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.getBytes())); KeyFactory keyFactory = null; keyFactory = KeyFactory.getInstance("RSA"); privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } /** * 密鑰實體 * @author hank * @since 2020/2/28 0028 下午 16:27 */ public static class SecretKey { /** * 公鑰 */ private String publicKey; /** * 私鑰 */ private String privateKey; public SecretKey(String publicKey, String privateKey) { this.publicKey = publicKey; this.privateKey = privateKey; } public String getPublicKey() { return publicKey; } public void setPublicKey(String publicKey) { this.publicKey = publicKey; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } @Override public String toString() { return "SecretKey{" + "publicKey='" + publicKey + '\'' + ", privateKey='" + privateKey + '\'' + '}'; } } private static void writeToFile(String path, byte[] key) throws IOException { File f = new File(path); f.getParentFile().mkdirs(); try(FileOutputStream fos = new FileOutputStream(f)) { fos.write(key); fos.flush(); } } public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, InvalidKeySpecException { SecretKey secretKey = generateSecretKey(2048); System.out.println(secretKey); String enStr = encryptData("你好測試測試", secretKey.getPrivateKey()); System.out.println(enStr); String deStr = decryptData(enStr, secretKey.getPublicKey()); System.out.println(deStr); enStr = encryptData("你好測試測試hello", secretKey.getPrivateKey()); System.out.println(enStr); deStr = decryptData(enStr, secretKey.getPublicKey()); System.out.println(deStr); } }
8. java 中的Cipher類RSA方式能不能用私鑰加密公鑰解密,完整解釋下
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//把第二個參數改為 key.getPrivate()
cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
byte[] cipherText = cipher.doFinal("Message".getBytes("UTF8"));
System.out.println(new String(cipherText, "UTF8"));
//把第二個參數改為key.getPublic()
cipher.init(Cipher.DECRYPT_MODE, key.getPrivate());
byte[] newPlainText = cipher.doFinal(cipherText);
System.out.println(new String(newPlainText, "UTF8"));
正常的用公鑰加密私鑰解密就是這個過程,如果按私鑰加密公鑰解密,只要按備注改2個參數就可以。
但是我要提醒樓主,你要公鑰解密,公鑰是公開的,相當於任何人都查到公鑰可以解密。
你是想做簽名是吧。
9. JAVA寫RSA加密,公鑰私鑰都是一樣的,為什麼每次加密的結果不一樣
因為rsa是非對稱加密,它使用的是隨機大素數的抽取,每次隨機生成的,所以每次加密的結果不可能一樣
10. JAVA寫RSA加密,公鑰私鑰都是一樣的,為什麼每次加密的結果不一樣
http://blog.csdn.net/defonds/article/details/42775183
這個博客寫的很好。