3

I'm trying to replicate the output of the following Python code in R:

import hashlib

x = hashlib.sha256()
x.update("asdf".encode("utf8"))
print(x.digest())
# b'\xf0\xe4\xc2\xf7lX\x91n\xc2X\xf2F\x85\x1b\xea\t\x1d\x14\xd4$z/\xc3\xe1\x86\x94F\x1b\x18\x16\xe1;'

This is my R code:

library(digest)
digest("asdf", algo="sha256", serialize=FALSE)
# "f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b"

I'm able to get this same output in python by using x.hexdigest() instead of x.digest(). How do I get the output of x.digest() in my R code?

Jealie
  • 6,157
  • 2
  • 33
  • 36
ytk
  • 2,787
  • 4
  • 27
  • 42

1 Answers1

6

The Python output is the raw bytes of the digest. The R digest function also supports this with the raw argument.

digest("asdf", algo="sha256", serialize=FALSE, raw=TRUE)
Travis Gockel
  • 26,877
  • 14
  • 89
  • 116
  • I should've mentioned that I tried this already. This is the output I get: `f0 e4 c2 f7 6c 58 91 6e c2 58 f2 46 85 1b ea 09 1d 14 d4 24 7a 2f c3 e1 86 94 46 1b 18 16 e1 3b` – ytk Sep 27 '17 at 20:29
  • 2
    The difference is how R and Python print byte strings -- they represent the same code. – Travis Gockel Sep 27 '17 at 20:30