You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 named decoded
  • 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

  1. Proper Base64 Decoding: We use Java's standard Base64.getDecoder() (more reliable than Groovy's old decodeBase64() shorthand) to get the raw byte array first, then convert it to a UTF-8 string to correctly handle Unicode characters.
  2. Fixed Variable Reference: Changed decode to decoded to match your variable declaration.
  3. Hex String Formatting: Using collect with String.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.
  4. Explicit Charset: Specifying StandardCharsets.UTF_8 ensures 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:09:23