skip to Main Content

I have a sha256 hash which is
5d753fd209b8cb9dff6801edbc60f2fdc00abff56bf3ef8c0f7cf9b975a2a1f9

and i know what i should get at the end which is this base64 encoded String
N7m2mKF7vY8tM8PVvkPONqnu5gdXWPm+vcT3lkpBWZ8=

but can’t figure out how to get this.
Just now i have tryed this

var hexString = '5d753fd209b8cb9dff6801edbc60f2fdc00abff56bf3ef8c0f7cf9b975a2a1f9';
var hexArray = HexUtils.decode(hexString);
var base64String = base64Encode(hexArray);
print('base64String: $base64String');

which print’s to the console

XXU/0gm4y53/aAHtvGDy/cAKv/Vr8++MD3z5uXWiofk=

what is not what i want. It should give me

N7m2mKF7vY8tM8PVvkPONqnu5gdXWPm+vcT3lkpBWZ8=

Any help is very much appreciated. Thank you so much.

I use the package basic_utils for HexUtils.decode and dart:convert for base64Encode

2

Answers


  1. I think you should use <string>.codeUnits property to get the List<int> and use it for base64encode.
    Example

    var hexString = '5d753fd209b8cb9dff6801edbc60f2fdc00abff56bf3ef8c0f7cf9b975a2a1f9';
    var base64String = base64Encode(hexString.codeUnits);
    print('base64String: $base64String');
    

    Output :

    base64String: NWQ3NTNmZDIwOWI4Y2I5ZGZmNjgwMWVkYmM2MGYyZmRjMDBhYmZmNTZiZjNlZjhjMGY3Y2Y5Yjk3NWEyYTFmOQ==
    

    However, this is not 100% the same as you required. Tried using https://www.base64encode.org/, and encoded your hex string, the output is same as mine and not yours.

    Login or Signup to reply.
  2. It looks like you’re on the right track, but there might be a small issue with how the hex string is being decoded. Let’s try a different approach to ensure the hex string is correctly converted to bytes before encoding it to base64.

    Here’s a complete example using Dart:

    import 'dart:convert';
    import 'dart:typed_data';
    
    void main() {
      var hexString = '5d753fd209b8cb9dff6801edbc60f2fdc00abff56bf3ef8c0f7cf9b975a2a1f9';
      
      // Convert hex string to bytes
      Uint8List hexToBytes(String hex) {
        var length = hex.length;
        var bytes = Uint8List(length ~/ 2);
        for (var i = 0; i < length; i += 2) {
          bytes[i ~/ 2] = int.parse(hex.substring(i, i + 2), radix: 16);
        }
        return bytes;
      }
    
      var bytes = hexToBytes(hexString);
      
      // Encode bytes to base64
      var base64String = base64Encode(bytes);
      print('base64String: $base64String');
    }
    

    This should give you the correct base64 encoded string. Let me know if this works for you!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search