/**
* @Brief: RSA加解密
* @Author: springIce
* @Date: 2024-01-31
**/
static void RSAEncrpyt(const QString& decryptData, QString &outData);
static void RSADecrypt(const QString& encryptData, QString &outData);
void Algorithm::RSAEncrpyt(const QString &decryptData, QString &outData)
{
//私钥 长度为512 (使用自己生成的公秘钥)
char private_key[] = "xxxxx";
//将字符串键加载到bio对象上
BIO* pKeyBio = BIO_new_mem_buf(private_key, strlen(private_key));
if (pKeyBio == NULL) {
return;
}
RSA* pRsa = RSA_new();
pRsa = PEM_read_bio_RSAPrivateKey(pKeyBio, &pRsa, NULL, NULL);
if (pRsa == NULL ) {
BIO_free_all(pKeyBio);
return;
}
int nLen = RSA_size(pRsa);
char* pEncryptBuf = new char[nLen];
memset(pEncryptBuf, 0, nLen);
QByteArray clearDataArry = decryptData.toUtf8();
int nClearDataLen = clearDataArry.length();
uchar* pClearData = (uchar*)clearDataArry.data();
int nSize = RSA_private_encrypt(nClearDataLen,
pClearData,
(uchar*)pEncryptBuf,
pRsa,
RSA_PKCS1_PADDING);
if (nSize >= 0 ) {
QByteArray arry(pEncryptBuf, nSize);
outData = arry.toBase64();
}
// 释放内存
delete pEncryptBuf;
BIO_free_all(pKeyBio);
RSA_free(pRsa);
}
void Algorithm::RSADecrypt(const QString &encryptData, QString &outData)
{
//公钥解密
char public_key[] = "xxxxxx";
//将字符串键加载到bio对象
BIO* pKeyBio = BIO_new_mem_buf(public_key, strlen(public_key));
if (pKeyBio == NULL) {
return;
}
RSA* pRsa = RSA_new();
pRsa = PEM_read_bio_RSA_PUBKEY(pKeyBio, &pRsa, NULL, NULL);
if (pRsa == NULL ) {
BIO_free_all(pKeyBio);
return;
}
int nLen = RSA_size(pRsa);
char* pClearBuf = new char[nLen];
memset(pClearBuf, 0, nLen);
//解密
QByteArray decryptDataArry = encryptData.toUtf8();
decryptDataArry = QByteArray::fromBase64(decryptDataArry);
int nDecryptDataLen = decryptDataArry.length();
uchar* pDecryptData = (uchar*)decryptDataArry.data();
int nSize = RSA_public_decrypt(nDecryptDataLen,
pDecryptData,
(uchar*)pClearBuf,
pRsa,
RSA_PKCS1_PADDING);
if (nSize >= 0 ){
outData = QByteArray(pClearBuf, nSize);
}
// 释放内存
delete pClearBuf;
BIO_free_all(pKeyBio);
RSA_free(pRsa);
}
评论