How to calculate sha256 hash in Groovy 2.4

Viewed 5415

I'm trying to calculate a sha256 hash in Groovy version 2.4.16. This is part of a jmeter test and that is the version of Groovy it supports, and I don't think I can change that. I'm aware that in Groovy 2.5 you can use code like this:

def challenge = verifier.digest('SHA-256');
log.info 'challenge' + challenge

but this doesn't work/exist in 2.4. How can I do this in Groovy 2.4?

The error I get with the above code is:

javax.script.ScriptException: groovy.lang.MissingMethodException: No signature of method: java.lang.String.digest() is applicable for argument types: (java.lang.String) values: [SHA-256]
Possible solutions: getAt(java.lang.String), next(), size(), toSet(), size(), toList()
    at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:324) ~[groovy-all-2.4.16.jar:2.4.16]
    at org.codehaus.groovy.jsr223.GroovyCompiledScript.eval(GroovyCompiledScript.java:72) ~[groovy-all-2.4.16.jar:2.4.16]
    at javax.script.CompiledScript.eval(Unknown Source) ~[?:1.8.0_221]
    at org.apache.jmeter.util.JSR223TestElement.processFileOrScript(JSR223TestElement.java:223) ~[ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.modifiers.JSR223PreProcessor.process(JSR223PreProcessor.java:44) [ApacheJMeter_components.jar:5.1.1 r1855137]
    at org.apache.jmeter.threads.JMeterThread.runPreProcessors(JMeterThread.java:935) [ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:537) [ApacheJMeter_core.jar:5.1.1 r1855137]
    at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:486) [ApacheJMeter_core.jar:5.1.1 r1855137]
...
2 Answers

You can use DigestUtils class functions for encryption in general and in particular for your case it would be DigestUtils.sha256Hex()

The following statement:

vars.put('foo', org.apache.commons.codec.digest.DigestUtils.sha256Hex('bar'))

will store SHA-256 encoded hash of bar line into foo JMeter Variable, you will be able to access it as ${foo} where required

vars stands for JMeterVariables class instance and it provides read/write access to all JMeter Variables in current thread context. Check out Top 8 JMeter Java Classes You Should Be Using with Groovy article to learn more about this and other JMeter API shorthands available for Groovy scripts.

Use JMeter's function digest instead for SHA-256

${__digest(SHA-256,Felix qui potuit rerum cognoscere causas,mysalt,,)}

digest function returns an encrypted value in the specific hash algorithm with the optional salt, upper case and variable name.

Example of usage in Parameters field and using output with args[0]

Related