Calculate a checksum from hex string?

I have a hex string with 23 two-character hex byte representations (so 46 characters long in total).

I need to calculate a simple bitwise checksum (adding each hex byte and discarding the overflow) and add it to the end.

And good guidance on how to do this? A simple for loop iterating over the string probably won’t cut it as it may make the rule execution time too long.

Hi Dave,
If the use case allows it, I would advise using a more common checksum algorithm such as MD5, SHA1, SHA256, etc. They are fast and reliable and usually easy to integrate. Please find a JSR223 Groovy example attached:

import groovy.time.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory

// init logger
Logger log = LoggerFactory.getLogger('GroovyScript')

// test value
String value = '4f70656e48414220697320617765736f6d65'

// start stopwatch
Date startTime= new Date()

// calculate check-sums and log result
log.warn('MD2: {}', value.digest('MD2'))
log.warn('MD5: {}', value.md5())
log.warn('SHA1: {}', value.digest('SHA-1'))
log.warn('SHA256: {}', value.digest('SHA-256'))

// stop stopwatch & log total execution time
TimeDuration duration = TimeCategory.minus(new Date(), startTime)
log.warn('Execution Time: {}', duration)

Result:

2021-01-16 18:17:17.258 [INFO ] [me.core.service.AbstractWatchService] - Loading script 'hash.groovy'
2021-01-16 18:17:17.381 [WARN ] [GroovyScript                        ] - MD2: 821bd7d25f600f94d98058db6ab578bb
2021-01-16 18:17:17.382 [WARN ] [GroovyScript                        ] - MD5: 85dec2c871de462a096594aba51c637a
2021-01-16 18:17:17.383 [WARN ] [GroovyScript                        ] - SHA1: 5428967961bc28567f19f501d3579f4a59de6d30
2021-01-16 18:17:17.384 [WARN ] [GroovyScript                        ] - SHA256: bd94203e730ee01a854eff32d1559e1375a5989b7f390d447d93bf40adc7a2b0
2021-01-16 18:17:17.385 [WARN ] [GroovyScript                        ] - Execution Time: 0.004 seconds

If you really need a custom algorithm, I would still recommend using a JSR223 rule written in JavaScript, Groovy or Python. If I understand your requirement correctly, you should not encounter performance issues.

Using bash:

#!/bin/bash
a="0123456789ABCDEF0123456789ABCDEF01234567ABCDEF"
b=`echo -n $a | sed 's/\(..\)/0x\1 + /g' | sed -e 's/$/0/'`
c=$((0xFF & $b))
printf '%x\n' $c