encrypt method
Encrypts the clearText
with a randomly generated salt of the length
saltLength
.
see decrypt() for reverse encryption.
Implementation
String encrypt(String clearText,
{int saltLength = 4,
CharClass charClass = CharClass.chars95,
String charSetMembers = ''}) {
if (charSetMembers.isEmpty) {
charSetMembers = BaseRandom.getCharClassMembers(charClass) ?? '';
}
var rc = saltLength == 0 ? '' : trueRandom.nextString(saltLength);
final currentState = firstState.toList();
currentState[0] =
random.maskOperand(random.maskOperand(rc.hashCode) + currentState[0]);
random.restoreState(currentState);
if (charClass == CharClass.chars95 || charClass == CharClass.chars96) {
// the charset is ordered like ASCII: we can calculate the index
final upperBound = charClass == CharClass.chars95 ? 127 : 128;
final max = charClass == CharClass.chars95 ? 95 : 96;
for (var ix = 0; ix < clearText.length; ix++) {
final code = clearText.codeUnitAt(ix);
if (code < 32 || code >= upperBound) {
rc += clearText[ix];
} else {
final rand = random.nextInt(max: max);
final value = 32 + ((code - 32 + rand) % max);
rc += String.fromCharCode(value);
}
}
} else {
// the charset is not ordered like ASCII: we must search the index
final max = charClass == CharClass.chars95 ? 95 : 96;
for (var ix = 0; ix < clearText.length; ix++) {
final index = charSetMembers.indexOf(clearText[ix]);
if (index < 0) {
rc += clearText[ix];
} else {
final rand = random.nextInt(max: max);
final value = (index + rand) % max;
rc += charSetMembers[value];
}
}
}
return rc;
}