I am trying to generate OTP, but after I tried to rewrite code from python to java, I have got different outputs. I do not understand why, because some of outputs characters are same (when I change uname or ctr).
PYTHON CODE:
from Crypto.Hash import SHA256
def get_otp(uname, ctr):
inp = uname+str(ctr)
binp = inp.encode('ascii')
hash=SHA256.new()
hash.update(binp)
dgst=bytearray(hash.digest())
out = ''
for x in range(9):
out += chr(ord('a')+int(dgst[x])%26)
if x % 3 == 2 and x != 8:
out += '-'
return out
print(get_otp('78951', 501585052583))
JAVA CODE:
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Main
{
public static void main(String[] args) throws NoSuchAlgorithmException
{
System.out.println(get_otp("78951", "501585052583"));
}
public static String get_otp(String uname, String otp) throws NoSuchAlgorithmException
{
String input = uname + otp;
byte[] binInput = input.getBytes(StandardCharsets.US_ASCII);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(binInput);
String retVal = "";
for(int i = 0; i < 9; ++i)
{
retVal += ((char)(((int)'a') + Math.floorMod((int)hash[i], 26)));
if(i % 3 == 2 && i != 8)
retVal += '-';
}
return retVal;
}
}
Thank you for help.