RSA關於加密長度限制的解決辦法


RSA關於加密長度限制的解決辦法
 
因為rsa采用分塊進行加密的,所以有長度限制.如果加密信息較多,可分段加解密(不建議對大量信息rsa加密,效率低效):
正常加密情形如下:
      public  static  String encrypt(String  source , String  publicKey )
                  throws  Exception {
           Key  key  getPublicKey( publicKey );
             /** 得到Cipher對象來實現對源數據的RSA加密 */
           Cipher  cipher  = Cipher.getInstance( "RSA/ECB/PKCS1Padding" );
             cipher .init(Cipher.  ENCRYPT_MODE ,  key );
             byte []  b  =  source .getBytes();
             /** 執行加密操作 */
             byte []  b1  =  cipher .doFinal(  b );
             return  new  String(Base64. encodeBase64( b1 ), "UTF-8" );
     }
 
分段加密如下:
   public  static  byte [] encryptByPublicKey(  byte []  data , String  publicKeyStr )  throws  Exception
    {
        PublicKey  publicKey  = RSAEncrypt.loadPublicKeyByStr( publicKeyStr );
        Cipher  cipher  =  null ;
         // 使用默認RSA
         cipher  = Cipher.getInstance( "RSA"  );
         cipher .init(Cipher. ENCRYPT_MODE ,  publicKey );
         int  inputLen  =  data . length ;
        ByteArrayOutputStream  out  =  new  ByteArrayOutputStream();
         int  offSet  = 0;
         byte []  cache ;
         int  i  = 0;
         // 對數據分段加密
         while  ( inputLen  -  offSet  > 0)
        {
             if  (  inputLen  -  offSet  >  MAX_ENCRYPT_BLOCK )
            {
                 cache  =  cipher .doFinal(  data ,  offSet ,  MAX_ENCRYPT_BLOCK );
            }
             else
            {
                 cache  =  cipher .doFinal(  data ,  offSet ,  inputLen  -  offSet );
            }
             out .write(  cache , 0,  cache .  length );
             i ++;
             offSet  =  i  *  MAX_ENCRYPT_BLOCK ;
        }
         byte []  encryptedData  =  out .toByteArray();
         out .close();
         return  encryptedData ;
    }
即把超過117(加密)和128(解密)長度的原文內容分割成多個部分,依次加解密,再合並.
參考下面文件
 
ApiAbstractResource.java


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM