javarsa密鑰對
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);      }     }
⑵ Java通過RSA演算法獲取公私鑰對 將公鑰提供出去 如何獲取字元串的公鑰
直接將公匙BYTE數組轉換為16進制的串啊
private static char hexTable[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static String toHexString(byte bytes[])
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++)
        {
            char chars[] = new char[2];
            int d = (bytes[i] & 240) >> 4;
            int m = bytes[i] & 15;
            chars[0] = hexTable[d];
            chars[1] = hexTable[m];
            sb.append(chars);
        }
        
        return sb.toString();
    }
⑶ 高分求java的RSA 和IDEA 加密解密演算法
RSA演算法非常簡單,概述如下:
找兩素數p和q
取n=p*q
取t=(p-1)*(q-1)
取任何一個數e,要求滿足e<t並且e與t互素(就是最大公因數為1)
取d*e%t==1
這樣最終得到三個數: n  d  e
設消息為數M (M <n)
設c=(M**d)%n就得到了加密後的消息c 
設m=(c**e)%n則 m == M,從而完成對c的解密。
註:**表示次方,上面兩式中的d和e可以互換。
在對稱加密中:
n d兩個數構成公鑰,可以告訴別人;
n e兩個數構成私鑰,e自己保留,不讓任何人知道。
給別人發送的信息使用e加密,只要別人能用d解開就證明信息是由你發送的,構成了簽名機制。
別人給你發送信息時使用d加密,這樣只有擁有e的你能夠對其解密。
rsa的安全性在於對於一個大數n,沒有有效的方法能夠將其分解
從而在已知n d的情況下無法獲得e;同樣在已知n e的情況下無法
求得d。
<二>實踐
接下來我們來一個實踐,看看實際的操作:
找兩個素數:
p=47
q=59
這樣
n=p*q=2773
t=(p-1)*(q-1)=2668
取e=63,滿足e<t並且e和t互素
用perl簡單窮舉可以獲得滿主 e*d%t ==1的數d:
C:\Temp>perl -e "foreach $i (1..9999){ print($i),last if $i*63%2668==1 }"
847
即d=847
最終我們獲得關鍵的
n=2773
d=847
e=63
取消息M=244我們看看
加密:
c=M**d%n = 244**847%2773
用perl的大數計算來算一下:
C:\Temp>perl -Mbigint -e "print 244**847%2773"
465
即用d對M加密後獲得加密信息c=465
解密:
我們可以用e來對加密後的c進行解密,還原M:
m=c**e%n=465**63%2773 :
C:\Temp>perl -Mbigint -e "print 465**63%2773"
244
即用e對c解密後獲得m=244 , 該值和原始信息M相等。
<三>字元串加密
把上面的過程集成一下我們就能實現一個對字元串加密解密的示例了。
每次取字元串中的一個字元的ascii值作為M進行計算,其輸出為加密後16進制
的數的字元串形式,按3位元組表示,如01F
代碼如下:
#!/usr/bin/perl -w
#RSA 計算過程學習程序編寫的測試程序
#watercloud 2003-8-12
#
use strict;
use Math::BigInt;
my %RSA_CORE = (n=>2773,e=>63,d=>847); #p=47,q=59
my $N=new Math::BigInt($RSA_CORE{n});
my $E=new Math::BigInt($RSA_CORE{e});
my $D=new Math::BigInt($RSA_CORE{d});
print "N=$N D=$D E=$E\n";
sub RSA_ENCRYPT 
{
    my $r_mess = shift @_;
    my ($c,$i,$M,$C,$cmess);
    for($i=0;$i < length($$r_mess);$i++)
    {
        $c=ord(substr($$r_mess,$i,1));
        $M=Math::BigInt->new($c);
        $C=$M->(); $C->bmodpow($D,$N);
        $c=sprintf "%03X",$C;
        $cmess.=$c;
    }
    return \$cmess;
}
sub RSA_DECRYPT 
{
    my $r_mess = shift @_;
    my ($c,$i,$M,$C,$dmess);
    for($i=0;$i < length($$r_mess);$i+=3)
    {
        $c=substr($$r_mess,$i,3);
        $c=hex($c);
        $M=Math::BigInt->new($c);
        $C=$M->(); $C->bmodpow($E,$N);
        $c=chr($C);
        $dmess.=$c;
    }
    return \$dmess;
}
my $mess="RSA 娃哈哈哈~~~";
$mess=$ARGV[0] if @ARGV >= 1;
print "原始串:",$mess,"\n";
my $r_cmess = RSA_ENCRYPT(\$mess);
print "加密串:",$$r_cmess,"\n";
my $r_dmess = RSA_DECRYPT($r_cmess);
print "解密串:",$$r_dmess,"\n";
#EOF
測試一下:
C:\Temp>perl rsa-test.pl
N=2773  D=847  E=63
原始串:RSA 娃哈哈哈~~~
加密串:
解密串:RSA 娃哈哈哈~~~
C:\Temp>perl rsa-test.pl 安全焦點(xfocus)
N=2773  D=847  E=63
原始串:安全焦點(xfocus)
加密串:
解密串:安全焦點(xfocus)
<四>提高
前面已經提到,rsa的安全來源於n足夠大,我們測試中使用的n是非常小的,根本不能保障安全性,
我們可以通過RSAKit、RSATool之類的工具獲得足夠大的N 及D E。
通過工具,我們獲得1024位的N及D E來測試一下:
n=EC3A85F5005D
4C2013433B383B
A50E114705D7E2
BC511951
d=0x10001
e=DD28C523C2995
47B77324E66AFF2
789BD782A592D2B
1965
設原始信息
M=
完成這么大數字的計算依賴於大數運算庫,用perl來運算非常簡單:
A) 用d對M進行加密如下:
c=M**d%n :
C:\Temp>perl -Mbigint -e " $x=Math::BigInt->bmodpow(0x11111111111122222222222233
333333333, 0x10001, 
D55EDBC4F0
6E37108DD6
);print $x->as_hex"
b73d2576bd
47715caa6b
d59ea89b91
f1834580c3f6d90898
即用d對M加密後信息為:
c=b73d2576bd
47715caa6b
d59ea89b91
f1834580c3f6d90898
B) 用e對c進行解密如下:
m=c**e%n :
C:\Temp>perl -Mbigint -e " $x=Math::BigInt->bmodpow(0x17b287be418c69ecd7c39227ab
5aa1d99ef3
0cb4764414
,  0xE760A
3C29954C5D
7324E66AFF
2789BD782A
592D2B1965,  CD15F90
4F017F9CCF
DD60438941
);print $x->as_hex"
(我的P4 1.6G的機器上計算了約5秒鍾)
得到用e解密後的m=  == M
C) RSA通常的實現
RSA簡潔幽雅,但計算速度比較慢,通常加密中並不是直接使用RSA 來對所有的信息進行加密,
最常見的情況是隨機產生一個對稱加密的密鑰,然後使用對稱加密演算法對信息加密,之後用
RSA對剛才的加密密鑰進行加密。
最後需要說明的是,當前小於1024位的N已經被證明是不安全的
自己使用中不要使用小於1024位的RSA,最好使用2048位的。
----------------------------------------------------------
一個簡單的RSA演算法實現JAVA源代碼:
filename:RSA.java
/*
* Created on Mar 3, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
import java.math.BigInteger;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;
/**
* @author Steve
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class RSA {
   
    /**
     * BigInteger.ZERO
     */
    private static final BigInteger ZERO = BigInteger.ZERO;
   
    /**
     * BigInteger.ONE
     */
    private static final BigInteger ONE = BigInteger.ONE;
   
    /**
     * Pseudo BigInteger.TWO
     */
    private static final BigInteger TWO = new BigInteger("2");
   
    private BigInteger myKey;
   
    private BigInteger myMod;
   
    private int blockSize;
   
    public RSA (BigInteger key, BigInteger n, int b) {
        myKey = key;
        myMod = n;
        blockSize = b;
    }
   
    public void encodeFile (String filename) {
        byte[] bytes = new byte[blockSize / 8 + 1];
        byte[] temp;
        int tempLen;
        InputStream is = null;
        FileWriter writer = null;
        try {
             is = new FileInputStream(filename);
             writer = new FileWriter(filename + ".enc");
        }
        catch (FileNotFoundException e1){
            System.out.println("File not found: " + filename);
        }
        catch (IOException e1){
            System.out.println("File not found: " + filename + ".enc");
        }
       
        /**
         * Write encoded message to 'filename'.enc
         */
        try {
            while ((tempLen = is.read(bytes, 1, blockSize / 8)) > 0) {
                for (int i = tempLen + 1; i < bytes.length; ++i) {
                    bytes[i] = 0;
                } 
                writer.write(encodeDecode(new BigInteger(bytes)) + " ");
            }
        }
        catch (IOException e1) {
            System.out.println("error writing to file");
        }
       
        /**
         * Close input stream and file writer
         */
        try {
            is.close();
            writer.close();
        }
        catch (IOException e1) {
            System.out.println("Error closing file.");
        }
    }
   
    public void decodeFile (String filename) {
       
        FileReader reader = null;
        OutputStream os = null;
        try {
            reader = new FileReader(filename);
            os = new FileOutputStream(filename.replaceAll(".enc", ".dec"));
        }
        catch (FileNotFoundException e1) {
            if (reader == null)
                System.out.println("File not found: " + filename);
            else
                System.out.println("File not found: " + filename.replaceAll(".enc", "dec"));
        }
       
        BufferedReader br = new BufferedReader(reader);
        int offset;
        byte[] temp, toFile;
        StringTokenizer st = null;
        try {
            while (br.ready()) {
                st = new StringTokenizer(br.readLine());
                while (st.hasMoreTokens()){
                    toFile = encodeDecode(new BigInteger(st.nextToken())).toByteArray();
                    System.out.println(toFile.length + " x " + (blockSize / 8));
                   
                    if (toFile[0] == 0 && toFile.length != (blockSize / 8)) {
                        temp = new byte[blockSize / 8];
                        offset = temp.length - toFile.length; 
                        for (int i = toFile.length - 1; (i <= 0) && ((i + offset) <= 0); --i) {
                            temp[i + offset] = toFile[i];
                        }
                        toFile = temp;
                    }
                   
                    /*if (toFile.length != ((blockSize / 8) + 1)){
                        temp = new byte[(blockSize / 8) + 1];
                        System.out.println(toFile.length + " x " + temp.length);
                        for (int i = 1; i < temp.length; i++) {
                            temp[i] = toFile[i - 1];
                        }
                        toFile = temp;
                    }
                    else
                        System.out.println(toFile.length + " " + ((blockSize / 8) + 1));*/
                    os.write(toFile);
                }
            }
        }
        catch (IOException e1) {
            System.out.println("Something went wrong");
        }
       
        /**
         * close data streams
         */
        try {
            os.close();
            reader.close();
        }
        catch (IOException e1) {
            System.out.println("Error closing file.");
        }
    }
   
    /**
     * Performs <tt>base</tt>^<sup><tt>pow</tt></sup> within the molar
     * domain of <tt>mod</tt>.
     *
     * @param base the base to be raised
     * @param pow the power to which the base will be raisded
     * @param mod the molar domain over which to perform this operation
     * @return <tt>base</tt>^<sup><tt>pow</tt></sup> within the molar
     * domain of <tt>mod</tt>.
     */
    public BigInteger encodeDecode(BigInteger base) {
        BigInteger a = ONE;
        BigInteger s = base;
        BigInteger n = myKey;
       
        while (!n.equals(ZERO)) {
            if(!n.mod(TWO).equals(ZERO))
                a = a.multiply(s).mod(myMod);
           
            s = s.pow(2).mod(myMod);
            n = n.divide(TWO);
        }
       
        return a;
    }
   
}
在這里提供兩個版本的RSA演算法JAVA實現的代碼下載:
1. 來自於 http://www.javafr.com/code.aspx?ID=27020 的RSA演算法實現源代碼包:
       http://zeal.newmenbase.net/attachment/JavaFR_RSA_Source.rar  
2. 來自於 http://www.ferrara.linux.it/Members/lucabariani/RSA/implementazioneRsa/ 的實現:
       http://zeal.newmenbase.net/attachment/sorgentiJava.tar.gz  - 源代碼包
       http://zeal.newmenbase.net/attachment/algoritmoRSA.jar - 編譯好的jar包
另外關於RSA演算法的php實現請參見文章:
       php下的RSA演算法實現
關於使用VB實現RSA演算法的源代碼下載(此程序採用了psc1演算法來實現快速的RSA加密): 
       http://zeal.newmenbase.net/attachment/vb_PSC1_RSA.rar
RSA加密的JavaScript實現: http://www.ohdave.com/rsa/
⑷ 如何實現用javascript實現rsa加解密
服務端生成公鑰與私鑰,保存。
客戶端在請求到登錄頁面後,隨機生成一字元串。
後此隨機字元串作為密鑰加密密碼,再用從服務端獲取到的公鑰加密生成的隨機字元串
將此兩段密文傳入服務端,服務端用私鑰解出隨機字元串,再用此私鑰解出加密的密文。這其中有一個關鍵是解決服務端的公鑰,傳入客戶端,客戶端用此公鑰加密字元串後,後又能在服務端用私鑰解出。
步驟:
服務端的RSAJava實現:
/**
*
*/
packagecom.sunsoft.struts.util;
importjava.io.ByteArrayOutputStream;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.math.BigInteger;
importjava.security.KeyFactory;
importjava.security.KeyPair;
importjava.security.KeyPairGenerator;
importjava.security.NoSuchAlgorithmException;
importjava.security.PrivateKey;
importjava.security.PublicKey;
importjava.security.SecureRandom;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjava.security.spec.InvalidKeySpecException;
importjava.security.spec.RSAPrivateKeySpec;
importjava.security.spec.RSAPublicKeySpec;
importjavax.crypto.Cipher;/**
*RSA工具類。提供加密,解密,生成密鑰對等方法。
*需要到
下載bcprov-jdk14-123.jar。
*
*/
publicclassRSAUtil{
/**
**生成密鑰對*
*
*@returnKeyPair*
*@throwsEncryptException
*/
()throwsException{
try{
KeyPairGeneratorkeyPairGen=KeyPairGenerator.getInstance("RSA",
neworg.bouncycastle.jce.provider.BouncyCastleProvider());
finalintKEY_SIZE=1024;//沒什麼好說的了,這個值關繫到塊加密的大小,可以更改,但是不要太大,否則效率會低
keyPairGen.initialize(KEY_SIZE,newSecureRandom());
KeyPairkeyPair=keyPairGen.generateKeyPair();
saveKeyPair(keyPair);
returnkeyPair;
}catch(Exceptione){
thrownewException(e.getMessage());
}
}
publicstaticKeyPairgetKeyPair()throwsException{
FileInputStreamfis=newFileInputStream("C:/RSAKey.txt");
ObjectInputStreamoos=newObjectInputStream(fis);
KeyPairkp=(KeyPair)oos.readObject();
oos.close();
fis.close();
returnkp;
}
publicstaticvoidsaveKeyPair(KeyPairkp)throwsException{
FileOutputStreamfos=newFileOutputStream("C:/RSAKey.txt");
ObjectOutputStreamoos=newObjectOutputStream(fos);
//生成密鑰
oos.writeObject(kp);
oos.close();
fos.close();
}
/**
**生成公鑰*
*
*@parammolus*
*@parampublicExponent*
*@returnRSAPublicKey*
*@throwsException
*/
(byte[]molus,
byte[]publicExponent)throwsException{
KeyFactorykeyFac=null;
try{
keyFac=KeyFactory.getInstance("RSA",
neworg.bouncycastle.jce.provider.BouncyCastleProvider());
}catch(NoSuchAlgorithmExceptionex){
thrownewException(ex.getMessage());
}
RSAPublicKeySpecpubKeySpec=newRSAPublicKeySpec(newBigInteger(
molus),newBigInteger(publicExponent));
try{
return(RSAPublicKey)keyFac.generatePublic(pubKeySpec);
}catch(InvalidKeySpecExceptionex){
thrownewException(ex.getMessage());
}
}
/**
**生成私鑰*
*
*@parammolus*
*@paramprivateExponent*
*@returnRSAPrivateKey*
*@throwsException
*/
(byte[]molus,
byte[]privateExponent)throwsException{
KeyFactorykeyFac=null;
try{
keyFac=KeyFactory.getInstance("RSA",
neworg.bouncycastle.jce.provider.BouncyCastleProvider());
}catch(NoSuchAlgorithmExceptionex){
thrownewException(ex.getMessage());
}
RSAPrivateKeySpecpriKeySpec=newRSAPrivateKeySpec(newBigInteger(
molus),newBigInteger(privateExponent));
try{
return(RSAPrivateKey)keyFac.generatePrivate(priKeySpec);
}catch(InvalidKeySpecExceptionex){
thrownewException(ex.getMessage());
}
}
/**
**加密*
*
*@paramkey
*加密的密鑰*
*@paramdata
*待加密的明文數據*
*@return加密後的數據*
*@throwsException
*/
publicstaticbyte[]encrypt(PublicKeypk,byte[]data)throwsException{
try{
Ciphercipher=Cipher.getInstance("RSA",
neworg.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE,pk);
intblockSize=cipher.getBlockSize();//獲得加密塊大小,如:加密前數據為128個byte,而key_size=1024
//加密塊大小為127
//byte,加密後為128個byte;因此共有2個加密塊,第一個127
//byte第二個為1個byte
intoutputSize=cipher.getOutputSize(data.length);//獲得加密塊加密後塊大小
intleavedSize=data.length%blockSize;
intblocksSize=leavedSize!=0?data.length/blockSize+1
:data.length/blockSize;
byte[]raw=newbyte[outputSize*blocksSize];
inti=0;
while(data.length-i*blockSize>0){
if(data.length-i*blockSize>blockSize)
cipher.doFinal(data,i*blockSize,blockSize,raw,i
*outputSize);
else
cipher.doFinal(data,i*blockSize,data.length-i
*blockSize,raw,i*outputSize);
//這裡面doUpdate方法不可用,查看源代碼後發現每次doUpdate後並沒有什麼實際動作除了把byte[]放到
//ByteArrayOutputStream中,而最後doFinal的時候才將所有的byte[]進行加密,可是到了此時加密塊大小很可能已經超出了
//OutputSize所以只好用dofinal方法。
i++;
}
returnraw;
}catch(Exceptione){
thrownewException(e.getMessage());
}
}
/**
**解密*
*
*@paramkey
*解密的密鑰*
*@paramraw
*已經加密的數據*
*@return解密後的明文*
*@throwsException
*/
publicstaticbyte[]decrypt(PrivateKeypk,byte[]raw)throwsException{
try{
Ciphercipher=Cipher.getInstance("RSA",
neworg.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(cipher.DECRYPT_MODE,pk);
intblockSize=cipher.getBlockSize();
ByteArrayOutputStreambout=newByteArrayOutputStream(64);
intj=0;
while(raw.length-j*blockSize>0){
bout.write(cipher.doFinal(raw,j*blockSize,blockSize));
j++;
}
returnbout.toByteArray();
}catch(Exceptione){
thrownewException(e.getMessage());
}
}
/**
***
*
*@paramargs*
*@throwsException
*/
publicstaticvoidmain(String[]args)throwsException{
RSAPublicKeyrsap=(RSAPublicKey)RSAUtil.generateKeyPair().getPublic();
Stringtest="helloworld";
byte[]en_test=encrypt(getKeyPair().getPublic(),test.getBytes());
byte[]de_test=decrypt(getKeyPair().getPrivate(),en_test);
System.out.println(newString(de_test));
}
}測試頁面IndexAction.java:
/*
*GeneratedbyMyEclipseStruts
*Templatepath:templates/java/JavaClass.vtl
*/
packagecom.sunsoft.struts.action;
importjava.security.interfaces.RSAPrivateKey;
importjava.security.interfaces.RSAPublicKey;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts.action.Action;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionMapping;
importcom.sunsoft.struts.util.RSAUtil;
/**
*MyEclipseStruts
*Creationdate:06-28-2008
*
*XDocletdefinition:
*@struts.actionvalidate="true"
*/
{
/*
*GeneratedMethods
*/
/**
*Methodexecute
*@parammapping
*@paramform
*@paramrequest
*@paramresponse
*@returnActionForward
*/
publicActionForwardexecute(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)throwsException{
RSAPublicKeyrsap=(RSAPublicKey)RSAUtil.getKeyPair().getPublic();
Stringmole=rsap.getMolus().toString(16);
Stringempoent=rsap.getPublicExponent().toString(16);
System.out.println("mole");
System.out.println(mole);
System.out.println("empoent");
System.out.println(empoent);
request.setAttribute("m",mole);
request.setAttribute("e",empoent);
returnmapping.findForward("login");
}
}通過此action進入登錄頁面,並傳入公鑰的Molus 與PublicExponent的hex編碼形式。
⑸ java ibm jdk rsa 怎麼 加密
android和java webservice RSA處理的不同
1.andorid機器上生成的(密鑰對由伺服器在windows xp下生成並將公鑰發給客戶端保存)密碼無法在伺服器通過私鑰解密。
2.為了測試,在伺服器本地加解密正常,另外,在android上加解密也正常,但是在伺服器中加密(使用相同公鑰)後的密碼同樣無法在android系統解密(使用相同私鑰)。
3.由於對RSA加密演算法不了解,而且對Java RSA的加密過程也不清楚、谷歌一番,才了解到可能是加密過程中的填充字元長度不同,這跟加解密時指定的RSA演算法有關系。
4. 比如,在A機中使用標准RSA通過公鑰加密,然後在B系統中使用「RSA/ECB/NoPadding」使用私鑰解密,結果可以解密,但是會發現解密後的原文前面帶有很多特殊字元,這就是在加密前填充的空字元;如果在B系統中仍然使用標準的RSA演算法解密,這在相同類型的JDK虛擬機環境下當然是完全一樣的,關鍵是android系統使用的虛擬機(dalvik)跟SUN標准JDK是有所區別的,其中他們默認的RSA實現就不同。
5.更形象一點,在加密的時候加密的原文「abc」,直接使用「abc」.getBytes()方法獲得的bytes長度可能只有3,但是系統卻先把它放到一個512位的byte數組里,new byte[512],再進行加密。但是解密的時候使用的是「加密後的密碼」.getBytes()來解密,解密後的原文自然就是512長度的數據,即是在「abc」之外另外填充了500多位元組的其他空字元。
⑹ java RSA演算法實現256位密鑰怎麼做
【下載實例】本文介紹RSA2加密與解密,RSA2是RSA的加強版本,在密鑰長度上採用2048, RSA2比RSA更安全,更可靠, 本人的另一篇文章RSA已經發表,有想了解的可以點開下面的RSA文章
⑺ 關於java中rsa的問題
【實例下載】本文介紹RSA2加密與解密,RSA2是RSA的加強版本,在密鑰長度上採用2048, RSA2比RSA更安全,更可靠, 本人的另一篇文章RSA已經發表,有想了解的可以點開下面的RSA文章
⑻ Java RSA 加密解密中 密鑰保存並讀取,數據加密解密並保存讀取 問題
幫你完善了下代碼。
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.FileReader;
importjava.io.OutputStream;
importjava.io.PrintWriter;
importjava.io.Reader;
importjava.util.Map;
publicclassTest{
staticStringpublicKey;
staticStringprivateKey;
publicTest()throwsException{
//TODOAuto-generatedconstructorstub
Map<String,Object>keyMap=RSAUtils.genKeyPair();
publicKey=RSAUtils.getPublicKey(keyMap);
privateKey=RSAUtils.getPrivateKey(keyMap);
//保存密鑰,名字分別為publicKey。txt和privateKey。txt;
PrintWriterpw1=newPrintWriter(newFileOutputStream(
"D:/publicKey.txt"));
PrintWriterpw2=newPrintWriter(newFileOutputStream(
"D:/privateKey.txt"));
pw1.print(publicKey);
pw2.print(privateKey);
pw1.close();
pw2.close();
//從保存的目錄讀取剛才的保存的公鑰,
Stringpubkey=readFile("D:/publicKey.txt");//讀取的公鑰內容;
Stringdata=readFile("D:/1.txt");//需要公鑰加密的文件的內容(如D:/1.txt)
byte[]encByPubKeyData=RSAUtils.encryptByPublicKey(data.getBytes(),
pubkey);
//將加密數據base64後寫入文件
writeFile("D:/Encfile.txt",Base64Utils.encode(encByPubKeyData).getBytes("UTF-8"));
//加密後的文件保存在
Stringprikey=readFile("D:/privateKey.txt");//從保存的目錄讀取剛才的保存的私鑰,
StringEncdata=readFile("D:/Encfile.txt");//剛才加密的文件的內容;
byte[]encData=Base64Utils.decode(Encdata);
byte[]decByPriKeyData=RSAUtils.decryptByPrivateKey(encData,prikey);
//解密後後的文件保存在D:/Decfile.txt
writeFile("D:/Decfile.txt",decByPriKeyData);
}
privatestaticStringreadFile(StringfilePath)throwsException{
FileinFile=newFile(filePath);
longfileLen=inFile.length();
Readerreader=newFileReader(inFile);
char[]content=newchar[(int)fileLen];
reader.read(content);
System.out.println("讀取到的內容為:"+newString(content));
returnnewString(content);
}
privatestaticvoidwriteFile(StringfilePath,byte[]content)
throwsException{
System.out.println("待寫入文件的內容為:"+newString(content));
FileoutFile=newFile(filePath);
OutputStreamout=newFileOutputStream(outFile);
out.write(content);
if(out!=null)out.close();
}
publicstaticvoidmain(String[]args)throwsException{
//TODOAuto-generatedmethodstub
newTest();
}
}
測試結果:
讀取到的內容為:++lXfZxzNpeA+rHaxmeQ2qI+5ES9AF7G6KIwjzakKsA08Ly+1y3dp0BnoyHF7/Pj3AS28fDmE5piea7w36vp4E3Ts+F9vwIDAQAB
讀取到的內容為:鍩縣ahaha
