I just started learn Nim and can not find information on how to sign a message using the public key. Before I used Golang and this was simple using stdlib like
block, _ := pem.Decode(publicKey)
if block == nil {
log.Fatal("public key error")
}
pubInt, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
pub := pubInt.(*rsa.PublicKey)
return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
Can you help me do this with Nim? Found this https://forum.nim-lang.org/t/7711
Thanks!
the code you posted isn't enough by itself to sign a message, it encrypts a block of data (that data being shorter than 128 - 11 bytes) with a public key, probably as part of a key exchange.
So I may not be answering your actual question, but here's the equivalent of that code, building on @PMunch's post in your linked example:
import openssl
var rsa_pub: PRSA
var public_key: string = """-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALFj4XCZ2Cvb4vbPl0KJvkeFP8Lqit7q
E1eA8US3ev/ziPlED5juC9IIBl69AOgxDHm1SjhceAxwG86Y8DkN7asCAwEAAQ==
-----END PUBLIC KEY-----"""
var bio_pub = BIO_new_mem_buf(addr publickey[0], -1)
rsa_pub = PEM_read_bio_RSA_PUBKEY(bio_pub, rsa_pub.addr, nil, nil)
if rsa_pub.isNil:
echo "ERROR: Could not load PUBLIC KEY! PEM_read_bio_RSA_PUBKEY FAILED"
echo ERR_error_string(ERR_get_error(), nil)
var plainText = "I love you"
var cipherText = newString(RSA_size(rsa_pub))
doAssert plainText.len < RSA_size(rsa_pub)-11
let sz = RSA_public_encrypt(plainText.len.cint,plainText[0].addr,cipherText[0].addr,rsa_pub,RSA_PKCS1_PADDING)
if sz != RSA_size(rsa_pub):
echo "ERROR: RSA_public_encrypt FAILED!"
echo ERR_error_string(ERR_get_error(),nil)
echo '<',cipherText,'>'
and just for testing, (you probably don't want to hard code a private key, and definitely dont use RSA512 for anything) here's the same in reverse:
var private_key = """----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBALFj4XCZ2Cvb4vbPl0KJvkeFP8Lqit7qE1eA8US3ev/ziPlED5ju
C9IIBl69AOgxDHm1SjhceAxwG86Y8DkN7asCAwEAAQJAIwGH6pWhkD4rUvNycSIH
l8uW4pswXn8o4/rBIgNnVXzgq5W8DWGImJfP2iEIIZVgJvYCYBv5dR9UKPVk4/5g
KQIhANif39IKfHQjYMgCndZ23h/eLorZC90eieic2dZfNPcXAiEA0aJTXPKrq2UW
6hOoMl42XcPYHYgVkTpolGD2+7xymo0CIQCA1JQIFrRtXZzxVp0ILylrSnfjm7Gy
j7b04FOtanHVgQIhALxRXyPbV73zZN9IY0tD+QDIYwc8bWt2FeZdKOJBio4tAiB/
VnttnNeXN77r9UgOU7FKXluDJiiM9mK6zoZhULXAMQ==
-----END RSA PRIVATE KEY-----"""
var rsa_priv:PRSA
var bio_priv = BIO_new_mem_buf(private_key[0].addr,-1)
rsa_priv = PEM_read_bio_RSAPrivatekey(bio_priv,rsa_priv.addr,nil,nil)
if rsa_priv.isNil:
echo "ERROR: Could not load PRIVATE KEY! PEM_read_bio_RSAPrivatekey FAILED"
echo ERR_error_string(ERR_get_error(), nil)
var decrypted = newString(RSA_size(rsa_priv))
let sz_dec = RSA_private_decrypt(cipherText.len.cint,cipherText[0].addr,decrypted[0].addr,rsa_priv,RSA_PKCS1_PADDING)
if sz < 0:
echo "ERROR: RSA_private_decrypt FAILED!"
echo ERR_error_string(ERR_get_error(),nil)
decrypted.setLen(sz_dec)
echo decrypted