如何在Go语言中使用Java代码进行RSA多重解密?

huangapple 未分类评论81阅读模式
英文:

How to do rsa multiple decryption in go from this java code

问题

以下是翻译好的内容:

提供者有这个样例JAVA代码来使用公钥解密RSA。并且通过将输入拆分成多个片段来执行。此外,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;
        // 获取公钥
        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;
        // 通过多次迭代进行加密
        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代码实际上是有效的。

英文:

Provider has this sample JAVA code to decrypt RSA using public key. And doing it by splitting the input into multiple segments. Besides, the rsa Algorithm is not specified clearly.

 public static String Encrypt(String dataStr, String publicKeyStr) throws Exception {
        ByteArrayOutputStream out = null;
        String encodedDataStr = null;
        try {
            out = new ByteArrayOutputStream();
            byte[] data = dataStr.getBytes(&quot;utf-8&quot;);
            String KEY_ALGORITHM = &quot;RSA&quot;;
            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 &gt; 0) {
                if (inputLen - offSet &gt; 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;
    }

below is my translation to go code, but the result is said invalid for them to decode. I assumed that the Algorithm is PKCS1v15.
what is the right way to do it in golang?

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 &lt; srcSize {
        endIndex := offSet + once
        if endIndex &gt; srcSize {
            endIndex = srcSize
        }
        bytesOnce, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, src[offSet:endIndex])
        if err != nil {
            return &quot;&quot;, err
        }
        buffer.Write(bytesOnce)
        offSet = endIndex
    }
    bytesEncrypt := buffer.Bytes()
    return base64.StdEncoding.EncodeToString(bytesEncrypt), nil

}

UPDATE: it seems that the java code above uses RSA/ECB/PKCS1PADDING
so the go code above actually works

huangapple
  • 本文由 发表于 2022年9月14日 11:25:06
  • 转载请务必保留本文链接:https://java.coder-hub.com/73711179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定