encryptRsaPkcs1v15 function

Future<Uint8List> encryptRsaPkcs1v15(
  1. String publicKey,
  2. dynamic message,
  3. {HashName digest = HashName.sha256,
  4. bool cleanupTempDirectory = true}
)

openssl pkeyutl -encrypt -pkeyopt rsa_padding_mode:pkcs1 -in message.txt -pubin -inkey publickey.pem

Implementation

Future<Uint8List> encryptRsaPkcs1v15(String publicKey, message,
    {HashName digest = HashName.sha256,
      bool cleanupTempDirectory = true}) async {
  if (message is String) {
    message = utf8.encode(message);
  }

  final tempDir = await Directory.systemTemp.createTemp();
  final publicKeyPath = path.join(tempDir.path, 'publickey.pem');
  await File(publicKeyPath).writeAsString(publicKey, encoding: utf8);
  final messagePath = path.join(tempDir.path, 'message.txt');
  await File(messagePath).writeAsBytes(message);

  final res = await Process.run(
      'openssl',
      [
        'pkeyutl',
        '-encrypt',
        '-pkeyopt',
        'rsa_padding_mode:pkcs1',
        '-in',
        messagePath,
        '-pubin',
        '-inkey',
        publicKeyPath,
      ],
      stdoutEncoding: null,
      includeParentEnvironment: true,
      runInShell: true);

  if (res.exitCode != 0) {
    if (cleanupTempDirectory) {
      await tempDir.delete(recursive: true);
    }
    throw OpensslException(res.exitCode, res.stdout, res.stderr);
  }

  if (cleanupTempDirectory) {
    await tempDir.delete(recursive: true);
  }

  return Uint8List.fromList(res.stdout);
}