Skip to content

Instantly share code, notes, and snippets.

@hacker1024
Created January 17, 2021 06:32
Show Gist options
  • Select an option

  • Save hacker1024/9cdd4d29c49523e3117c8fa8126e3a66 to your computer and use it in GitHub Desktop.

Select an option

Save hacker1024/9cdd4d29c49523e3117c8fa8126e3a66 to your computer and use it in GitHub Desktop.
PKCS #5 padding in Dart
import 'dart:typed_data';
Uint8List padPKCS5(List<int> input) {
final inputLength = input.length;
final paddingValue = 8 - (inputLength % 8);
final outputLength = inputLength + paddingValue;
final output = Uint8List(outputLength);
for (var i = 0; i < inputLength; ++i) {
output[i] = input[i];
}
output.fillRange(outputLength - paddingValue, outputLength, paddingValue);
return output;
}
int getPKCS5PadCount(List<int> input) {
if (input.length % 8 != 0) {
throw FormatException('Block size is invalid!', input);
}
final count = input.last;
final paddingStartIndex = input.length - count;
for (var i = input.length - 1; i >= paddingStartIndex; --i) {
if (input[i] != count) {
throw FormatException('Padding is not valid PKCS5 padding!');
}
}
return count;
}
@hacker1024

Copy link
Copy Markdown
Author

I license this under the WTFPL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment