Groovy脚本Base64解码及SHA1摘要生成故障求助
Fixing Your Groovy Base64 Decode + SHA1 Digest Script
Let's break down the issues in your code and fix them step by step to get the 40-character SHA1 hash you need:
Key Issues in Your Original Code
- Variable Typo: You used
decode.getBytes()but your decoded string variable is nameddecoded - Invalid Method:
toVarchar()isn't a valid Groovy/Java method for byte arrays. When decoding Base64 to a string, you need to specify the correct character encoding (critical for handling Unicode) - Missing Leading Zeros: Using
BigInteger.toString(16)can produce a hash shorter than 40 characters because it drops leading zeros from individual bytes
Corrected Groovy Code
import java.security.MessageDigest import java.nio.charset.StandardCharsets import java.util.Base64 def Message processData(Message message) { // Get the input Base64 string String body = message.getBody(String.class) // Step 1: Decode Base64 to bytes, then convert to UTF-8 string (handles Unicode) byte[] decodedBytes = Base64.getDecoder().decode(body) String decoded = new String(decodedBytes, StandardCharsets.UTF_8) // Step 2: Compute SHA1 digest MessageDigest sha1 = MessageDigest.getInstance("SHA1") byte[] digestBytes = sha1.digest(decoded.getBytes(StandardCharsets.UTF_8)) // Step 3: Convert digest to 40-character hex string (preserving leading zeros) String digest = digestBytes.collect { String.format("%02x", it) }.join() // Update message body and return message.setBody(digest) return message }
What Changed & Why
- Proper Base64 Decoding: We use Java's standard
Base64.getDecoder()(more reliable than Groovy's olddecodeBase64()shorthand) to get the raw byte array first, then convert it to a UTF-8 string to correctly handle Unicode characters. - Fixed Variable Reference: Changed
decodetodecodedto match your variable declaration. - Hex String Formatting: Using
collectwithString.format("%02x", it)ensures each byte is converted to a two-digit hex string, so leading zeros aren't lost—guaranteeing a 40-character result. - Explicit Charset: Specifying
StandardCharsets.UTF_8ensures consistent encoding/decoding across environments, which is essential for handling Unicode.
Testing with Your Input
When running this code with your provided Base64 string, you'll get a valid 40-character SHA1 hash. If you need to debug further, add print statements for decoded (to verify the Unicode content is correctly loaded) or digestBytes (to check the raw digest bytes).
内容的提问来源于stack exchange,提问作者Rajesh
相关产品推荐
相关产品推荐

