Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'package:crypto/crypto.dart';
- import 'dart:convert';
- class Sha1Encryptor {
- /// This method will change the List<int> into a Big Int.
- /// I did not write this myself
- ///
- /// Source: https://github.com/PointyCastle/pointycastle/blob/master/lib/src/utils.dart
- BigInt _decodeBigInt(List<int> bytes) {
- var result = BigInt.from(0);
- for (var i = 0; i < bytes.length; i++) {
- result += BigInt.from(bytes[bytes.length - i - 1]) << (8 * i);
- }
- return result;
- }
- String _removeFirstZeros(String str) {
- var split = str.split('');
- for (var i = 0; i < split.length; i++) {
- if (split[i] == '0') {
- str = str.replaceFirst('0', '');
- } else {
- if(i >1){
- print('wtf : ' + i.toString());
- }
- break;
- }
- }
- return str;
- }
- String getEncrypted(String str) {
- //First we convert the string into bytes (UTF-8) and then encrypt them with the SHA-1 algrorithm.
- var digest = sha1.convert(utf8.encode(str));
- //If the first byte is smaller than 128, it should be seen as a negative number.
- if (digest.bytes[0] < 128) {
- return _removeFirstZeros(digest.toString());
- }
- //We turn the result from the encryption into a big int.
- var bytesAsBigInt = _decodeBigInt(digest.bytes);
- //As we want to perform two's complement, we first have to turn the big int into bits and then changing
- //all the 0's to 1's and the other way around.
- var bytesReversed = bytesAsBigInt
- .toRadixString(2)
- .replaceAll('0', '2')
- .replaceAll('1', '0')
- .replaceAll('2', '1');
- //Since we need to add 1 to the bit series (two's complement), we will split each bit from eachother into a List.
- var split = bytesReversed.split('');
- //We will loop through every bit in the list to make sure we correctly add the bit.
- //The is a very small chance of carry overloading, but the chance is too small to care about it.
- //A better developer would've looked into that.
- var addedOne = '';
- var carry = true;
- for (var i = split.length - 1; i >= 0; i--) {
- var char = split[i];
- if (carry) {
- if (char == '0') {
- char = '1';
- carry = false;
- } else {
- //Keep the carry
- char = '0';
- }
- }
- addedOne = (char + addedOne);
- }
- //Return the bit series as HEX values
- return '-' +
- _removeFirstZeros(BigInt.parse(addedOne, radix: 2).toRadixString(16));
- }
- String getServerHash(String serverID, List PublicKey, List SecretKey)
- {
- byte[] hash = digest(new byte[][] { Encoding.GetEncoding("iso-8859-1").GetBytes(serverID), SecretKey, PublicKey });
- bool negative = (hash[0] & 0x80) == 0x80;
- if (negative) { hash = TwosComplementLittleEndian(hash); }
- string result = GetHexString(hash).TrimStart('0');
- if (negative) { result = "-" + result; }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement