Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash a string in Declarative Pipeline

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?

like image 813
abergmeier Avatar asked May 02 '26 15:05

abergmeier


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.

like image 141
StephenKing Avatar answered May 08 '26 09:05

StephenKing


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

like image 44
Joerg S Avatar answered May 08 '26 09:05

Joerg S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!