gpt4 book ai didi

java - C++/Openssl 从编码字节中获取 RSA key (由 java 编码)

转载 作者:太空宇宙 更新时间:2023-11-04 13:06:03 26 4
gpt4 key购买 nike

有人知道如何使用 C++ 从编码字节数组创建 RSA key 吗?

我的问题是我尝试开发一个 C++ 客户端,它与用 Java 编码的服务器进行交互。在 Java 中,客户端接收编码为字节数组的 rsa key ,将其解码为 RSA RSAPublicKey 并使用此 key 加密消息。

java服务器/客户端代码:

public static PublicKey decodePublicKey(byte[] p_75896_0_)
{
try
{
X509EncodedKeySpec var1 = new X509EncodedKeySpec(p_75896_0_);
KeyFactory var2 = KeyFactory.getInstance("RSA");
return var2.generatePublic(var1);
}
catch (NoSuchAlgorithmException var3)
{
;
}
catch (InvalidKeySpecException var4)
{
;
}

field_180198_a.error("Public key reconstitute failed!");
return null;
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

this.publicKey = CryptManager.decodePublicKey(data.readByteArray());

之后,客户使用他的 key 进行一些加密。

key 是这样发送的:

public static final KeyPair keys;
static
{
try
{
KeyPairGenerator generator = KeyPairGenerator.getInstance( "RSA" );
generator.initialize( 1024 );
keys = generator.generateKeyPair();
} catch ( NoSuchAlgorithmException ex )
{
throw new ExceptionInInitializerError( ex );
}
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
byte[] pubKey = keys.getPublic().getEncoded();
writeBytes(pubKey);

我的问题是如何从 C++ 中的字节数组中获取 key 。

更新:我目前正在处理这段代码:

    char* publicKey = ...
int publicKeyLength = 162;
EVP_PKEY* key = EVP_PKEY_new();

if(d2i_PUBKEY(&key, (const unsigned char**) &publicKey, publicKeyLength) != 0){
logError("Problem!");
}
logMessage("Key: "+to_string((uint64_t) (void*) key));

我现在的问题是我在第三行有一个 SIGSEGV 错误并且不知道这门类(class)是什么。那么 key 应该是有效的。

最佳答案

Java 为公钥返回的是一个 SubjectPublicKeyInfo 结构,它不仅包含公钥的(PKCS#1 编码)值,还包含 key 标识符等。

因此,要对此进行解码,您必须在您最喜欢的搜索引擎中键入“decode SubjectPublicKeyInfo openssl”。然后你会发现(在一些滚动之后)来自 here 的以下信息:

d2i_PUBKEY() and i2d_PUBKEY() decode and encode an EVP_PKEY structure
using SubjectPublicKeyInfo format. They otherwise follow the conventions
of other ASN.1 functions such as d2i_X509().

显然您需要解码算法。


请注意,openssl 是 C 语言,因此在解码内容时要小心缓冲区溢出。我宁愿使用 1024 位 RSA key 用于安全软件,也不愿使用 2048 位 key 用于充满缓冲区溢出的软件。

不用说,您需要在导入之前信任公钥。它被称为公钥基础设施 (PKI) 是有原因的。

关于java - C++/Openssl 从编码字节中获取 RSA key (由 java 编码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42327704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com