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("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;
}
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 < 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
}
UPDATE: it seems that the java code above uses RSA/ECB/PKCS1PADDING
so the go code above actually works