我使用以下代码生成RSA密钥对并将其转换为PEM。但是当我使用OpenSSL函数时,PEM_read_bio_RSA_PUBKEY
返回null。
Java代码:
public static RSAKeyPair creatKeyPair(int keySize) throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(keySize, new SecureRandom());
return getRSAKeyPair(keyGen.genKeyPair());
}
private static RSAKeyPair getRSAKeyPair(KeyPair keyPair) throws Exception {
RSAKeyPair rsaKeyPair = new RSAKeyPair();
rsaKeyPair.PrivateKey = rsaKeyToPEMFormat(keyPair.getPrivate());
rsaKeyPair.PublicKey = rsaKeyToPEMFormat(keyPair.getPublic());
return rsaKeyPair;
}
private static String rsaKeyToPEMFormat(Key key){
StringWriter writer = new StringWriter();
//org.bouncycastle.openssl.PEMWriter bcprov-ext-jdk16-1.46.jar
PEMWriter pemWriter = new PEMWriter(writer);
try {
pemWriter.writeObject(key);
pemWriter.close();
return writer.toString();
} catch (IOException e) {
LogLIB.error(e.getMessage(), e);
}
return null;
}
C 代码:
RSA * createRSA(unsigned char * key, int flag) {
RSA *rsa = NULL;
BIO *keybio;
int keylength = strlen(key);
keybio = **BIO_new_mem_buf(key, -1);**
if (keybio == NULL) {
LOGV( "Failed to create key BIO" );
return 0;
}
if (flag) {
rsa = PEM_read_bio_RSA_PUBKEY(keybio, &rsa, NULL, NULL); //return null !!!
} else {
rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa, NULL, NULL);
}
if (rsa == NULL) {
LOGV( "Failed to create RSA");
//printf( "Failed to create RSA" );
}
return rsa;
}
我的测试键:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCT9uJpsYJUVbZGwv9mWYJRMnYr
I85SkGm9Wb/3+04xaZxQG2GchjQsLRvAc2ZG/CpTpen1q7E4nQeuNgthwI6/0LnE
lIkn1O2bcBGUGpyiXseGvSeCfbyFiefNkC0xsyW/w5f506nP4ukroWGCDeSKHg5S
PrA6WDXiy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