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

Java分段RSA加密转Go实现:问题排查与正确方案

RSA分段加密的Java转Go实现问题

服务商提供了如下用于通过公钥进行分段RSA加密的Java示例代码,但未明确指定RSA算法:

public static String Encrypt(String dataStr, String publicKeyStr) throws Exception {
        ByteArrayOutputStream out = null;
        String encodedDataStr = null;
        try {
            out = new ByteArrayOutputStream();
            byte[] data = dataStr.getBytes("utf-8");
            String KEY_ALGORITHM = "RSA";
            int MAX_ENCRYPT_BLOCK = 117;
            // get public key
            byte[] keyBytes = Base64.decodeBase64(publicKeyStr);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            Key publicKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(x509KeySpec);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            int inputLen = data.length;
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // do encryption by multiple iterates
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            encodedDataStr = Base64.encodeBase64String(encryptedData);
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                out.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }
        return encodedDataStr;
    }

我将其转换为如下Go代码,但对方反馈解密结果无效。我原本假设算法为PKCS1v15,请问正确的Go实现方式是什么?

func Encrypt(srcStr string, publicKey *rsa.PublicKey) (string, error) {
    src := []byte(srcStr)
    keySize, srcSize := publicKey.Size(), len(src)
    offSet := 0
    once := 117
    buffer := bytes.Buffer{}
    for offSet < srcSize {
        endIndex := offSet + once
        if endIndex > srcSize {
            endIndex = srcSize
        }
        bytesOnce, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, src[offSet:endIndex])
        if err != nil {
            return "", err
        }
        buffer.Write(bytesOnce)
        offSet = endIndex
    }
    bytesEncrypt := buffer.Bytes()
    return base64.StdEncoding.EncodeToString(bytesEncrypt), nil

}

更新说明

经确认,上述Java代码实际使用的是RSA/ECB/PKCS1PADDING,因此我的Go代码其实是有效的。

内容的提问来源于stack exchange,提问作者user10200598

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:20:28