In a script inside a Declarative Pipeline (Groovy 2.4.11) I want to hash a string (preferably SHA-256). Does anyone know a way of doing this without needing a signature approval?
2 Answers
The Pipeline Utility Steps plugin comes with a sha1
step.
Unfortunately, other SHA variants seem to be not available by community plugins.
EDIT: as of now (2021), also sha256
is available.

- 36,187
- 11
- 83
- 112
-
1This seems to require the string to first be written to a file – cowlinator Jun 20 '19 at 22:46
-
1Why oh why does it not accept a text parameter, ugh – justin.m.chase Sep 10 '21 at 12:13
-
Probably because Groovy code of the pipeline is executed on the Jenkins master, and only the steps on the build agents. If one would then want to calculate the SHA of a big file, the file's contents would have to be copied over to the master (`sha(readFile(...))`). So for me it makes sense how it is. Sure, inconvenient for you. Does maybe this help? https://stackoverflow.com/questions/58527804/how-to-calculate-sha256-hash-in-groovy-2-4#58534678 – StephenKing Sep 12 '21 at 21:16
Had the same issue. For me, using the Java approach is working (if you do not need the sandbox, or are willing to white-list the used methods):
import java.security.MessageDigest
@NonCPS
String getDigest(String input, String algorithm) {
MessageDigest digest = MessageDigest.getInstance(algorithm)
digest.update(input.bytes)
digest.digest().encodeHex().toString()
}
echo getDigest('foo', 'SHA256')
We'll use this method from within a Jenkins shared library defined globally in the Jenkins configuration, so it will be able to run outside the sandbox. Actually, we use the MD5 hash - but other algorithms are supported, too.
For a list of possible digest algorithms, you may check the official documentation for MessageDigest
, which at the time of writing can be found here:
https://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html

- 4,730
- 3
- 24
- 43
-
Worked for me, but I had to grant 4 approvals (groovy 2.9, jenkins master 2.301) – Nikolai Ehrhardt Nov 09 '21 at 10:34
-
As an alternative, you still can put this into a global shared library... – Joerg S Nov 09 '21 at 14:46