PointyCastle / pointycastle

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

RSA: Decrypt got different result from original text when long string #230

Closed adc-developer closed 4 years ago

adc-developer commented 4 years ago
final pair = _generateRSAkeyPair(_secureRandom());
final public = pair.publicKey;
final private = pair.privateKey;

String testing = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkh1vrlsUmYT92sX27r7NuzVj0LY+VymGhyxOYhVSrUPd1m27xPGIqI2QxMEKJxVLLxWQKGGd5a6neAhOj6VigjSKKN/2DM/FGBQY8s25nN77LOOZAPKZwXeegq9sDqbl4aQAdoAPbG9FAqhEXhn9NwQozsRIYsa74U+zczUeEKDLc0K0PsjkGxS7miDuaDcErD2/iqWebQcP4KyLOfEV7Sf0XFRhVPOJZBN+wR5CR/GsqXmsee/q4YaCImgTVNDlZmQco50U0mrqZd1NEbR592cQg77ytwpCUIgRBS8GIZQqXfc/AlF/adMkA6NY0CTRFdRGwR6DHw1TtJmNJLI+pQIDAQAB";

var encryptedBytes = rsaEncrypt(public, Uint8List.fromList(testing.codeUnits));
var decryptedBytes = rsaDecrypt(private, encryptedBytes);
var encrypted = base64.encode(encryptedBytes);
var decrypted = String.fromCharCodes(decryptedBytes);

AsymmetricKeyPair<RSAPublicKey, RSAPrivateKey> _generateRSAkeyPair(
    SecureRandom secureRandom,
    {int bitLength = 2048}) {
  // Create an RSA key generator and initialize it

  final keyGen = RSAKeyGenerator()
      ..init(ParametersWithRandom(
          RSAKeyGeneratorParameters(BigInt.parse('65537'), bitLength, 64),
          secureRandom));

    // Use the generator

    final pair = keyGen.generateKeyPair();

    // Cast the generated key pair into the RSA key types

    final myPublic = pair.publicKey as RSAPublicKey;
    final myPrivate = pair.privateKey as RSAPrivateKey;

    return AsymmetricKeyPair<RSAPublicKey, RSAPrivateKey>(myPublic, myPrivate);
  }

  SecureRandom _secureRandom() {
    final secureRandom = FortunaRandom();

    final seedSource = Random.secure();
    final seeds = <int>[];
    for (int i = 0; i < 32; i++) {
      seeds.add(seedSource.nextInt(255));
    }
    secureRandom.seed(KeyParameter(Uint8List.fromList(seeds)));

    return secureRandom;
  }

  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);
  }
adc-developer commented 4 years ago

I found the dependency got from pub get command was different from Github repository. Now it is working after I copy and replace source dependency.