-1

I want to encrypt the String “this is a simple string” by modPow, but I don't find the method in BigInt API, How can I convert String to BigInt in Dart?

String original = "this is a simple string";

BigInt modulusInt = BigInt.parse(n, radix: 16);
BigInt exponentInt = BigInt.parse(e, radix: 16);

now when the original can be converted to BigInt, I can use modPow

Mohit Kushwaha
  • 1,003
  • 1
  • 10
  • 15
shaoml
  • 1

1 Answers1

0

Edited to add some clarification and comments to code

First you have to define a map from String to BigInt. In other word, you have to use an encoding scheme to encode characters to numbers. The String class in dart provides a getter codeUnits to convert a string to a List of UTF-16 code of characters, thus if you want to adopt the UTF-16 encoding, you can take advantage of this getter method, and you can turn the list back to string with the factory constructor fromCharCodes of String:

BigInt uint16SeqToBigInt(List<int> seq){
  var ret = BigInt.from(0);
  int offset = 0;
  for(int i in seq){
    // Shift the UTF-16 code of each character to "slots" of 16-bit size
    ret += (BigInt.from(i)) << offset;
    offset += 16;
  }
  return ret;
}

List<int> bigIntToUint16Seq(BigInt val){
  final ret = <int>[];
  int cur;
  while(true){
    // 0xFFFF is a bit mask to extract the lower 16-bit value from val
    cur = (val & BigInt.from(0xFFFF)).toInt();
    if(cur != 0){
      ret.add(cur);
      // The last 16 bits is interpreted, now discard them
      val = val >> 16;
    }else{
      break;
    }
  }
  
  return ret;
}

void main() {
  String original = "this is a simple string";
  final utf16BigInt = uint16SeqToBigInt(original.codeUnits);
  final decoded = String.fromCharCodes(bigIntToUint16Seq(utf16BigInt));
  print(decoded);
  // "this is a simple string"
}
SdtElectronics
  • 566
  • 4
  • 8