⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 liyuxin.java

📁 加密算法
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
			     Exponent=e;
			     Modulus=n;
			     int keysize=(Modulus.bitLength()+7)/8;


			      if ((params != null) && (!(params instanceof RSAKeyGenParameterSpec)))
				      {
				       throw new InvalidAlgorithmParameterException("Unsupported RSA AlgorithmParameterSpec!");
				     }

		                       BigInteger publicExp=e;
				       params_ = new RSAKeyGenParameterSpec(keysize, publicExp);

				     random_ = _random;


				     if((opmode == Cipher.DECRYPT_MODE)
				             || (opmode == Cipher.ENCRYPT_MODE))
				      {

				      }
				     else
				      {
				       throw new InvalidKeyException("Unsupported opmode!");
				      }
                     opmode_ = opmode;
           }



  /**父类中的方法,不必要。*/
  protected void engineSetMode(String mode)
          throws NoSuchAlgorithmException
   {

    if (!mode.equalsIgnoreCase("ECB"))
     {
      throw new NoSuchAlgorithmException(
        "RSA supports only ECB mode");
    }
  }

  /**设置填充模式只支持一种模式  */
  protected void engineSetPadding(String s)
          throws NoSuchPaddingException
   {

    if (!s.equalsIgnoreCase("PKCS1_V1_5"))
     {
      throw new NoSuchPaddingException("Unknown padding: "
                                       + s);
    }
  }//PKCS1_V1_5: 缺省填充模式

  /**
   * Method engineUpdate
   * Description: See CipherSpi
   */
  protected byte[] engineUpdate(byte[] input, int inputOffset,
                             int inputLen)
   {//这个函数的意思:将input数组加密,加密范围从第一个字节到inputOffset+inputLen,也就是说后面的内容加密不加密暂时不考虑.

    try
     {
      if (inputOffset > 0)
       {
        int    outputSize = inputOffset + inputLen;
        byte[] tmp        = new byte[outputSize];
        internal_buffer_ = new byte[inputLen];
        if(TESTNEEDED)
        {
			System.out.println("input.length is  "+input.length+"inputOffset is"+inputOffset+"internal_buffer_ .length   "+internal_buffer_.length+";   inputLen is "+inputLen);
	    }
        System.arraycopy(input, inputOffset, internal_buffer_,
                         0, inputLen);

        if ((opmode_ == Cipher.ENCRYPT_MODE)
                || (opmode_ == Cipher.WRAP_MODE))
         {
		  if(KeyInited==1)
		  {
			  return (encrypt(internal_buffer_));
		  }
		  else if(IntegerInited==1)
		  {

              return(newencrypt(internal_buffer_));
		  }
         }
        else
         {
			  if(KeyInited==1)
		      {
                return (decrypt(internal_buffer_));
		      }
		      else if(IntegerInited==1)
		      {
                return (newdecrypt(internal_buffer_));
			  }
         }
       }
      else//inpuOffset<=0
       {
        internal_buffer_ = new byte[inputLen];//第一次,需要初始化,所以和上面的分开,因为没有初始化必须初始化,上面的函数是已经初始化了的,不能再初始化

        System.arraycopy(input, 0, internal_buffer_,0, inputLen);
        //System.out.println("input.length is  "+inputLen);
        if (opmode_ == Cipher.ENCRYPT_MODE)

         {
          if(TESTNEEDED){
           System.out.println("RichRSACipher:engineUpdate:encrypting");
          }
          		  if(KeyInited==1)
		  		  {
		  			  return (encrypt(internal_buffer_));
		  		  }
		  		  else if(IntegerInited==1)
		  		  {
					  //System.out.println("internal_buffer_ is   "+internal_buffer_);
                      byte[] jackbyte=(newencrypt(internal_buffer_));
                      //System.out.println("jackbyte is  "+jackbyte);
                      return jackbyte;
		          }
        }
        else
         {
          if(TESTNEEDED){
           System.out.println("RichRSACipher:engineUpdate:decrypting");
          }
          			  if(KeyInited==1)
		  		      {
		                  return (decrypt(internal_buffer_));
		  		      }
		  		      else if(IntegerInited==1)
		  		      {
                          return (newdecrypt(internal_buffer_));
			          }
        }
      }
    }

    /*
     * Catches
     */
    catch (Exception ex)
     {
      ex.printStackTrace();
    }

    return null;
  }

  /**
该方法暂时不需要,父类中有就实现了。
   */
  protected int engineUpdate(
          byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset)
            throws ShortBufferException
   {

    byte[] buffer;

    buffer = engineUpdate(input, inputOffset, inputLen);

    if (output.length - outputOffset < buffer.length)
     {
      throw new ShortBufferException(
        "Output longer than buffer");
    }

    System.arraycopy(buffer, 0, output, outputOffset,
                     buffer.length);

    return buffer.length;
  }

  /**整数转换成字符串。   */
  private byte[] I2OSP(BigInteger x, int l)//********************************
          throws IllegalBlockSizeException
   {



    int j = (x.bitLength() + 7) / 8;

  /*if (l == -1)
     {
      l = j;
    }
*/
    if ((j > l) || (x.signum() == -1))
     {
      throw new IllegalBlockSizeException("Block too large");
    }


    byte[] C = x.toByteArray();

    int index = 0;

    for (; (index < C.length) && (C[index] == 0); index++);

    if (index > 0)
     {
      byte[] temp = new byte[C.length - index];

      System.arraycopy(C, index, temp, 0, temp.length);

      C = temp;
    }
    else if (C.length > l)
     {
      throw new IllegalBlockSizeException("Block too large");
    }

    if (C.length == l)
     {
      return C;
    }

    byte[] result = new byte[l];

    System.arraycopy(C, 0, result, l - C.length, C.length);

    return result;
  }


  /**   关键方法,对数组M进行加密   */
  private byte[] encrypt(byte[] M)
          throws IllegalBlockSizeException
   {

    int    k  = params_.getKeysize();
    byte[] EM = EME_PKCS1_V1_5_ENCODE(M, k-1);//填充。

    //转换成大数字。
    BigInteger m = new BigInteger(1, EM);
    BigInteger c = RSAEP((RSAPrivateKey) key_, m);
    byte[] C = I2OSP(c, k);

    return C;
  }

  private byte[] newencrypt(byte[] M)
  throws IllegalBlockSizeException
  {
	  int k=params_.getKeysize();
	  byte[] EM=EME_PKCS1_V1_5_ENCODE(M, k-1);
      BigInteger m = new BigInteger(1, EM);
      BigInteger c = newRSAEP(Exponent,Modulus, m);
      byte[] C = I2OSP(c, k);
	  return C;
  }

  /**解密,对数组C,使用的公钥时该类中的。初始化的时候就已经赋值了。   */
  private byte[] decrypt(byte[] C)
          throws BadPaddingException, IllegalBlockSizeException
   {
    int k = params_.getKeysize();
    if (k != C.length)
     {
      throw new IllegalBlockSizeException("decryption error");
     }
    BigInteger c = new BigInteger(1, C);

    BigInteger m = RSADP((RSAPublicKey) key_, c);

    byte[] EM = I2OSP(m, k - 1);

    byte[] M = EME_PKCS1_V1_5_DECODE(EM);

    return M;
  }


//如果不是用密钥而是用大整数初始化该类,则调用下面这个方法
 private byte[] newdecrypt(byte[] C)
 throws BadPaddingException, IllegalBlockSizeException
 {
	 int k = params_.getKeysize();

	     if (k != C.length)
	      {
	       throw new IllegalBlockSizeException("decryption error");
	     }

	 BigInteger c = new BigInteger(1, C);
	 BigInteger m = newRSADP(Exponent,Modulus, c);
     byte[] EM = I2OSP(m, k - 1);
     byte[] M = EME_PKCS1_V1_5_DECODE(EM);
     return M;

 }




  private byte[] EME_PKCS1_V1_5_ENCODE(byte[] M, int emLen)
          throws IllegalBlockSizeException
   {

    //不能过短!
    if (M.length > emLen - 10)
     {
      throw new IllegalBlockSizeException("message too long");
    }


    byte[]                PS   =
      new byte[(emLen - M.length - 2)];

    // 填充,一个起始标记,一个终止标记,其余为随机字符串,随机字符串至少为八个字节。
    for (int i = 0; i < PS.length; i++)
     {
      PS[i] = (byte) (random_.nextInt(255) + 1);
    }

    /*消息 EM的形式: 02 || PS || 00 || M    */
    byte[] EM = new byte[emLen];
    int index = 0;
    EM[index++] = (byte) 0x02;
    for (int i = 0; i < PS.length; i++)
     {
      EM[index++] = PS[i];
    }
    EM[index++] = (byte) 0x00;
    for (int i = 0; i < M.length; i++)
     {
      EM[index++] = M[i];
    }


    return EM;
  }

  /**对填充过的一堆数组,删除不必要的,相对于拆包一样   */
  private byte[] EME_PKCS1_V1_5_DECODE(byte[] EM)
          throws BadPaddingException
   {

//光填充就有10个字节,所以不能小于10!
    if (EM.length < 10)
     {
      throw new BadPaddingException("message too short");
    }


    if (EM[0] != (byte) 0x02)
     {
      throw new BadPaddingException(
        "message not formatted properly");
    }

      int start = 0;

    while (EM[start] != (byte) 0x00)
     {
      start++;

      if (start >= EM.length)
       {
        throw new BadPaddingException("bad padding");
      }
    }

    start++;

    if (start < 10)
     {
      throw new BadPaddingException("bad padding");
    }

    byte[] M = new byte[EM.length - start];

    System.arraycopy(EM, start, M, 0, M.length);

    return M;
  }

  /**指数运算*/
  private BigInteger RSAEP(RSAPrivateKey privateKey, BigInteger m)
          throws IllegalBlockSizeException
   {

    BigInteger e = privateKey.getPrivateExponent();
    BigInteger n = privateKey.getModulus();


    BigInteger nMinusOne = n.subtract(BigInteger.ONE);


    if (m.compareTo(BigInteger.ZERO) < 0)
     {
      throw new IllegalBlockSizeException(
        "Ciphertext too small");
    }

    if (m.compareTo(nMinusOne) > 0)
     {
      throw new IllegalBlockSizeException(
        "Ciphertext too large");
    }


    BigInteger c = m.modPow(e, n);


    return c;
  }


//如果用大数字初始化的时候,调用该方法
  private BigInteger newRSAEP(BigInteger Exponent,BigInteger Modulus, BigInteger m)
          throws IllegalBlockSizeException
  {
	 BigInteger nMinusOne = Modulus.subtract(BigInteger.ONE);

	 if (m.compareTo(BigInteger.ZERO) < 0)
	      {
	       throw new IllegalBlockSizeException(
	         "Ciphertext too small");
	      }
	 if (m.compareTo(nMinusOne) > 0)
	      {
	       throw new IllegalBlockSizeException(
	         "Ciphertext too large");
          }

     BigInteger c = m.modPow(Exponent, Modulus);
    return c;

  }





  /**
  解密的时候的指数运算,起始跟上面方法差不多。  */
  private BigInteger RSADP(RSAPublicKey K,
                          BigInteger c)
   {


      BigInteger d = K.getPublicExponent();
      BigInteger n = K.getModulus();

      BigInteger m = c.modPow(d, n);

      return m;


  }

//用大整数初始化的时候
  private BigInteger newRSADP(BigInteger Exponent,BigInteger Modulus,BigInteger c)
  {

	   BigInteger m = c.modPow(Exponent, Modulus);
	   return m;

  }


}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -