-2

I am trying to make a program where you encrypt a piece of data and then subtract the last 16 characters from the output.

import hashlib

# initializing string
str2hash = "test" #input

# encoding GeeksforGeeks using encode()
# then sending to md5()
result = hashlib.md5(str2hash.encode())
# printing the equivalent hexadecimal value.
print("The hexadecimal equivalent of hash is : ", end="")
print(result.hexdigest())

some stuff that I've tried are

print(result.hexdigest()) -16
 str2hash = "test" -16

I'm pretty new to coding in python so any help I can get from this will help.

4 Answers4

0

Depends what you mean by "repeats"

You are hashing 51 times, and only (trying to) remove the last 16 characters 50 times. Is that what you intended?

Secondly, as @B Remmelzwaal points out, you are only printing the reduced string, not saving it.

Try replacing

print(string_result[:-16])

with

string_result = string_result[:-16]

But do check how many times you actually need to do each thing.

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
0

Given my previous comment and what @Eureka suggested, this would be your fixed code:

import hashlib

str2hash = 'MjhjMmRmMTIzMWFlOWVkMA=='
result = str2hash

for _ in range(50):
    result = str(hashlib.md5(result.encode()).hexdigest())[:-16]

print(result)

Output:

7675a9ba7938ca55
B Remmelzwaal
  • 1,581
  • 2
  • 4
  • 11
-1

You can use slicing. Specifically, a "stop" index of -16 indicates that you wish to stop 16 characters before the end of the string.

print(result[:-16])
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
-1

Since your result result.hexdigest() is a string you can simply get all elements except the last 16 by slicing from the end:

    h = result.hexdigest()[:-16]

Here, -16 is 16 characters from the end and : denotes all characters before that.