PointyCastle / pointycastle

Moved into the Bouncy Castle project: https://github.com/bcgit/pc-dart
MIT License
270 stars 76 forks source link

block Decrypt Error #224

Open xdnice opened 4 years ago

xdnice commented 4 years ago

The following code is the class of RSAEngine. There is problem for the code:

// line 25
int get inputBlockSize {
    if (_key == null) {
      throw new StateError(
          "Input block size cannot be calculated until init() called");
    }

    var bitSize = _key.modulus.bitLength;
    if (_forEncryption) {
      return ((bitSize + 7) ~/ 8) - 1;    // why is not  (bitSize  ~/ 8) - 11;
    } else {
      return (bitSize + 7) ~/ 8;       //  why  is not   bitSize  ~/ 8
    }
  }

// line 41
  int get outputBlockSize {
    if (_key == null) {
      throw new StateError(
          "Output block size cannot be calculated until init() called");
    }

    var bitSize = _key.modulus.bitLength;
    if (_forEncryption) {
      return (bitSize + 7) ~/ 8;            //  why  is not   bitSize  ~/ 8
    } else {
      return ((bitSize + 7) ~/ 8) - 1;    //why is not  (bitSize  ~/ 8) - 11;
    }
  }

when Encryp the inputBlockSize is ((bitSize + 7) ~/ 8) - 1; why is not (bitSize ~/ 8) - 11;

The following code is about block encryption,
in this example: when the length of the bits of the encrypted string over 117 bits, Decrypt ERORR. Why?
For example,

import "package:pointycastle/export.dart";

Uint8List rsaEncrypt(RSAPublicKey myPublic, Uint8List dataToEncrypt) {
  final encryptor = OAEPEncoding(RSAEngine())
    ..init(true, PublicKeyParameter<RSAPublicKey>(myPublic)); // true=encrypt

  return _processInBlocks(encryptor, dataToEncrypt);
}

Uint8List rsaDecrypt(RSAPrivateKey myPrivate, Uint8List cipherText) {
  final decryptor = OAEPEncoding(RSAEngine())
    ..init(false, PrivateKeyParameter<RSAPrivateKey>(myPrivate)); // false=decrypt

  return _processInBlocks(decryptor, cipherText);
}

Uint8List _processInBlocks(AsymmetricBlockCipher engine, Uint8List input) {
  final numBlocks = input.length ~/ engine.inputBlockSize +
      ((input.length % engine.inputBlockSize != 0) ? 1 : 0);

  final output = Uint8List(numBlocks * engine.outputBlockSize);

  var inputOffset = 0;
  var outputOffset = 0;
  while (inputOffset < input.length) {
    final chunkSize = (inputOffset + engine.inputBlockSize <= input.length)
        ? engine.inputBlockSize
        : input.length - inputOffset;

    outputOffset += engine.processBlock(
        input, inputOffset, chunkSize, output, outputOffset);

    inputOffset += chunkSize;
  }

  return (output.length == outputOffset)
      ? output
      : output.sublist(0, outputOffset);
}