消息加密使用公钥:BER 解码错误
时间:2024-03-06
浏览:254
作者:佚名
学习Golang要努力,但是不要急!今天的这篇文章《消息加密使用公钥:BER 解码错误》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!
我在使用公钥加密消息时遇到问题。
我想使用字符串中包含的公钥 rsa-4096 加密一个字符串(让我们说 "test")。
让我们说:
-----开始公钥-----
miicijanbgkqhkig9w0baqefaaocag8amiiccgkcageam9ggfej3dhazihcvhtna
vnu38kbdxvioswyxcjewq8yhlqol6e5he1dxx5uqvnklr7+gamzzbxeqlocrsyi6
nrexgxe4wftjd+pqlh5ba9dio8vbspisg66zymfdztmfgn2dl0euvuiijguqwkja
e5p8ebjsnodomx1763p8k50ahhizaubd+iwavdezbew7efopt5wj6c5a1kwkv4bx
+viqoc7mfnjqzii+sg/8yjnt++zv5fo+jwe6pyxwzcabwgsbyq9cv2imc4zxafvo
glytixok/7rmy6nie+miuafrevbgg8k0yt3u1jn1knqyv++qtnaqqmcvtogc1se6
s8pwihgrgh+zg3ewudzvqjadbdl/cgdz8wnfps8ssant1kcjyq3ogp12fx0axenf
vklcm5jlcm1v6/kyqpyk0fvarh6rt7e5qzcwzxaoxmz1bze97cz9+pqgbglyyrqo
cqbewkvuei/neboqdifrgok/ku43lmurxbtbybseoxvn4d+3jgn0bs1cmxqsljml
kupv87oljzzggqw8lrs3owkqf9trs9fyljujst3f2osyaphedyx9xdkjnhgbh+af
47kocpxg6olpotram5cw/0zwsgtvhxfbldo+xfnzddsklwfyl2jx8wifz6txa/mp
/aloyzkx/wadqaeqlhbs3smcaweaaq==
-----结束公钥-----
为此,我尝试使用 c++ 中的 cryptopp 库 (https://www.cryptopp.com/wiki/keys_and_formats),但是当我尝试读取和解码我的公钥时,出现以下错误: ber 解码错误 。
这是我正在使用的完整源代码:
#include <string>
#include <iomanip>
#include <iostream>
#include <exception>
#include <fstream>
#include <cryptopp/queue.h>
using cryptopp::bytequeue;
#include <cryptopp/filters.h>
using cryptopp::redirector;
#include <cryptopp/files.h>
using cryptopp::filesource;
using cryptopp::filesink;
#include <cryptopp/cryptlib.h>
using cryptopp::privatekey;
using cryptopp::publickey;
using cryptopp::bufferedtransformation;
#include <cryptopp/sha.h>
#include <cryptopp/rsa.h>
using cryptopp::rsa;
#include <cryptopp/base64.h>
using cryptopp::base64encoder;
using cryptopp::base64decoder;
#include <cryptopp/osrng.h>
using cryptopp::autoseededrandompool;
using namespace std;
int main(int argc, char** argv) {
bytequeue queue;
string rsa_public_key ="-----begin public key-----miicijanbgkqhkig9w0baqefaaocag8amiiccgkcageam9ggfej3dhazihcvhtnavnu38kbdxvioswyxcjewq8yhlqol6e5he1dxx5uqvnklr7+gamzzbxeqlocrsyi6nrexgxe4wftjd+pqlh5ba9dio8vbspisg66zymfdztmfgn2dl0euvuiijguqwkjae5p8ebjsnodomx1763p8k50ahhizaubd+iwavdezbew7efopt5wj6c5a1kwkv4bx+viqoc7mfnjqzii+sg/8yjnt++zv5fo+jwe6pyxwzcabwgsbyq9cv2imc4zxafvoglytixok/7rmy6nie+miuafrevbgg8k0yt3u1jn1knqyv++qtnaqqmcvtogc1se6s8pwihgrgh+zg3ewudzvqjadbdl/cgdz8wnfps8ssant1kcjyq3ogp12fx0axenfvklcm5jlcm1v6/kyqpyk0fvarh6rt7e5qzcwzxaoxmz1bze97cz9+pqgbglyyrqocqbewkvuei/neboqdifrgok/ku43lmurxbtbybseoxvn4d+3jgn0bs1cmxqsljmlkupv87oljzzggqw8lrs3owkqf9trs9fyljujst3f2osyaphedyx9xdkjnhgbh+af47kocpxg6olpotram5cw/0zwsgtvhxfbldo+xfnzddsklwfyl2jx8wifz6txa/mp/aloyzkx/wadqaeqlhbs3smcaweaaq==-----end public key-----";
static string header = "-----begin public key-----";
static string footer = "-----end public key-----";
size_t pos1 = rsa_public_key.find(header);
if(pos1 == string::npos) throw runtime_error("pem header not found");
size_t pos2 = rsa_public_key.find(footer, pos1+1);
if(pos2 == string::npos) throw runtime_error("pem footer not found");
// start position and length
pos1 = pos1 + header.length();
pos2 = pos2 - pos1;
string keystr = rsa_public_key.substr(pos1, pos2);
/*base64encoder decoder;
decoder.attach(new redirector(queue));*/
queue.put((const byte*)keystr.data(), keystr.length());
queue.messageend();
cout << keystr << endl;
try {
rsa::publickey public_key;
public_key.berdecodepublickey(queue, false /*paramspresent*/, queue.maxretrievable());
if(queue.isempty()) {
cerr << "the queue is empty...";
}
autoseededrandompool prng;
bool valid = public_key.validate(prng, 3);
if(!valid) cerr << "rsa public key is not valid" << endl;
cout << "n:" << public_key.getmodulus() << endl;
cout << "e:" << public_key.getpublicexponent() << endl;
} catch (exception& e) {
printf( "caught exception: %s\n", e.what() );
exit (1);
}
}
非常感谢那些可以帮助我理解为什么公钥没有被正确读取的人。
对于那些说 golang 的人来说,我基本上是在尝试重现以下功能:
func WriteEncryptedWithPublicKeyInformation(filename string, information string, publicKey string) error {
f, err := os.Create(filename)
block, _ := pem.Decode([]byte(publicKey))
if block == nil {
return errors.New("Failed to parse PEM block containing the public key")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return errors.New("Failed to parse DER encoded public key: " + err.Error())
}
key := pub.(*(rsa.PublicKey))
ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, key, []byte(information), nil)
if err != nil {
return err
}
_, err = f.WriteString(b64.StdEncoding.EncodeToString(ciphertext))
if err != nil {
return err
}
f.Close()
return nil
}
其中 filename 是我的输出文件,information 是我要加密的字符串,publickey 是包含公钥的字符串。
解决方案
您的程序解码 base64 的方式不正确,函数 rsafunction::berdecodepublickey 根据参考
berdecodepublickey() 解码 subjectpublickeyinfo 的 subjectpublickey 部分,不带 bit string 标头。
您应该使用 x509publickey::berdecode 函数,因为类 rsa::publickey 继承自 x509publickey
尝试一下这个程序,它应该可以工作。
#include <string>
#include <iomanip>
#include <iostream>
#include <exception>
#include <fstream>
#include <cryptopp/queue.h>
using CryptoPP::ByteQueue;
#include <cryptopp/filters.h>
using CryptoPP::Redirector;
#include <cryptopp/files.h>
using CryptoPP::FileSource;
using CryptoPP::FileSink;
#include <cryptopp/cryptlib.h>
using CryptoPP::PrivateKey;
using CryptoPP::PublicKey;
using CryptoPP::BufferedTransformation;
#include <cryptopp/sha.h>
#include <cryptopp/rsa.h>
#include <cryptopp/asn.h>
using CryptoPP::RSA;
#include <cryptopp/base64.h>
using CryptoPP::Base64Encoder;
using CryptoPP::Base64Decoder;
#include <cryptopp/osrng.h>
using CryptoPP::AutoSeededRandomPool;
using namespace std;
int main() {
ByteQueue queue;
string RSA_PUBLIC_KEY ="-----BEGIN PUBLIC KEY-----MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAm9GgFeJ3DhazIHCVHtNaVnu38KBdxViOswyXcJEwQ8yHlQOL6e5He1dxx5uqvnKLR7+gAMzZBXEQlOCrSYi6nREXGxE4WFTjd+PqLh5bA9DIO8vbsPIsG66zYmFdztmFGn2dl0EUvUiIjGUqwkJAE5P8ebjsNOdomX1763p8k50AHhIzaUbD+IWAVDEzbew7efOPt5Wj6C5a1kwkv4bX+viqoC7mFNjQziI+Sg/8yjnT++Zv5fo+JWE6pyXwZCabwgsBYq9Cv2iMC4ZXAFVoGLYtixok/7rMY6NIe+MIUafrEVbgG8K0YT3U1Jn1knqYV++qtnaqqmcvtoGC1SE6s8pwiHGRgh+ZG3EwuDZVqJadBdl/CGDz8WnfPs8sSANT1kCJYq3ogp12Fx0axENFvklCM5jLcm1v6/kyqPYk0fVArH6RT7e5QZCWZXAoxMz1bZe97CZ9+PQGbGLyYrQOCqBeWkVUEI/NeBoQdifrgok/Ku43LMUrxbTByBSEoXVn4d+3jgN0BS1CmxQslJmlkUPv87OLjzzggQW8lRs3owKQF9TRs9fYljuJSt3f2osYaPhedYx9XdkJNhgbH+AF47kocpxg6olpOtRaM5cW/0zWSGtVHXfblDO+XFNzddSKLwFyL2Jx8WIfZ6tXa/MP/aLOyzKX/WADqAEqlHbs3SMCAwEAAQ==-----END PUBLIC KEY-----";
static string HEADER = "-----BEGIN PUBLIC KEY-----";
static string FOOTER = "-----END PUBLIC KEY-----";
size_t pos1 = RSA_PUBLIC_KEY.find(HEADER);
if(pos1 == string::npos) throw runtime_error("PEM header not found");
size_t pos2 = RSA_PUBLIC_KEY.find(FOOTER, pos1+1);
if(pos2 == string::npos) throw runtime_error("PEM footer not found");
// Start position and length
pos1 = pos1 + HEADER.length();
pos2 = pos2 - pos1;
string keystr = RSA_PUBLIC_KEY.substr(pos1, pos2);
CryptoPP::StringSource ss{keystr.c_str(), true};
Base64Decoder decoder;
decoder.Attach(new Redirector(queue));
ss.TransferTo(decoder);
decoder.MessageEnd();
cout << keystr << endl;
try {
RSA::PublicKey public_key;
if(queue.IsEmpty()) {
cerr << "The queue is empty...";
}
public_key.BERDecode(queue);
AutoSeededRandomPool prng;
bool valid = public_key.Validate(prng, 3);
if(!valid) cerr << "RSA public key is not valid" << endl;
cout << "N:" << public_key.GetModulus() << endl;
cout << "E:" << public_key.GetPublicExponent() << endl;
} catch (exception& e) {
printf( "Caught exception: %s\n", e.what() );
exit (1);
}
}我没有看到你解码中间的base 64。 ber 是二进制格式,您首先必须转换为二进制才能读取它。
到这里,我们也就讲完了《消息加密使用公钥:BER 解码错误》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
