import (
"crypto/rsa"
"crypto/x509"
"crypto/rand"
"encoding/base64"
"encoding/pem"
"errors"
"strings"
)
func RsaEncrypt(plaintext string, base64PublicKey string) (string, error) {
keyPem := "-----BEGIN PUBLIC KEY-----\n" + insertLineBreaks(base64PublicKey, 64) + "\n-----END PUBLIC KEY-----"
block, _ := pem.Decode([]byte(keyPem))
if block == nil {
return "", errors.New("failed to parse PEM block")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return "", err
}
rsaPub, ok := pub.(*rsa.PublicKey)
if !ok {
return "", errors.New("not RSA public key")
}
encryptedBytes, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPub, []byte(plaintext))
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(encryptedBytes), nil
}
func insertLineBreaks(s string, every int) string {
var b strings.Builder
for i := 0; i < len(s); i += every {
end := i + every
if end > len(s) {
end = len(s)
}
b.WriteString(s[i:end] + "\n")
}
return b.String()
}
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <openssl/buffer.h>
std::string base64Decode(const std::string &input) {
BIO *bio, *b64;
int decodeLen = (int)input.length() * 3 / 4;
std::vector<char> buffer(decodeLen);
bio = BIO_new_mem_buf(input.c_str(), -1);
b64 = BIO_new(BIO_f_base64());
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
int len = BIO_read(bio, buffer.data(), (int)input.length());
BIO_free_all(bio);
return std::string(buffer.data(), len);
}
std::string rsaEncrypt(const std::string &plaintext, const std::string &base64PubKey) {
std::string pubKeyPem = base64Decode(base64PubKey);
BIO* bio = BIO_new_mem_buf((void*)pubKeyPem.c_str(), -1);
RSA* rsa = PEM_read_bio_RSA_PUBKEY(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
if (!rsa) {
throw std::runtime_error("Failed to load public key");
}
std::vector<unsigned char> encrypted(RSA_size(rsa));
int len = RSA_public_encrypt(plaintext.length(),
(const unsigned char*)plaintext.c_str(),
encrypted.data(),
rsa,
RSA_PKCS1_PADDING);
RSA_free(rsa);
if (len == -1) {
throw std::runtime_error("RSA encryption failed");
}
return std::string(encrypted.begin(), encrypted.begin() + len);
}
using System;
using System.Security.Cryptography;
using System.Text;
public class RSAEncryptor
{
public static string Encrypt(string plaintext, string base64PublicKey)
{
byte[] keyBytes = Convert.FromBase64String(base64PublicKey);
using (var rsa = RSA.Create())
{
rsa.ImportSubjectPublicKeyInfo(keyBytes, out _);
var data = Encoding.UTF8.GetBytes(plaintext);
var encrypted = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
return Convert.ToBase64String(encrypted);
}
}
}