gpt4 book ai didi

java - BouncyCasSTLe RSA 无法转换 android

转载 作者:太空宇宙 更新时间:2023-11-04 12:09:20 25 4
gpt4 key购买 nike

我有使用 BouncyCaSTLe 的 C# 代码

        var jsonToSend = "{\"Number\":\"string\",\"Name\":\"string\",\"NameOnCard\":\"string\",\"ExpMonth\":0,\"ExpYear\":0}";
var PemBase64string = "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0NCk1JR2ZNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0R05BRENCaVFLQmdRQ1lrTnVuSGx0dkI1Vm5TamVJZ0hJNEx4bmkNCjlzVzZoL0d0TXRld2pGaWFrUVYxSUg2QUlEeHgzRU9LYW85Tk85LzZ4ZlFzZWVLN2lXbFRUajd4M0VqNmpBOFYNCkExTmJzTEZGVkNuVEpsWHQ0M012N0dYQVovQTZpVEtCQSt5eGREYXJkVUVObmJQSnJFMEJvMEkvNTFnLzJKemQNCkJIRUFpN3c3ZDhCRGRCN1FiUUlEQVFBQg0KLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tDQo = ";


var pemKey = Encoding.UTF8.GetString(Convert.FromBase64String(PemBase64string));
var sr = new StringReader(pemKey);
var pubKey = (RsaKeyParameters)new PemReader(sr).ReadObject();

//Setup encryption engine
IAsymmetricBlockCipher eng = new Pkcs1Encoding(new RsaEngine());
eng.Init(true, pubKey);

byte[] encdata = Encoding.UTF8.GetBytes(jsonToSend); //convert json string to bytes
encdata = eng.ProcessBlock(encdata, 0, encdata.Length); //encrypt bytes
string result = Convert.ToBase64String(encdata); //convert encrypted bytes to Base64 string to send

我尝试用java重写这段代码

    byte[] pemKey = Base64.decode(PemBase64String, Base64.DEFAULT);

String result;
try {
Reader sr = new StringReader(new String(pemKey, "UTF-8"));
RSAKeyParameters pubKey = (RSAKeyParameters) new PEMReader(sr).readObject();

PKCS1Encoding eng = new PKCS1Encoding(new RSAEngine());
eng.init(true, pubKey);

byte[] encData = jsonToSend.getBytes("UTF-8");
encData = eng.processBlock(encData, 0, encData.length);
result = new String(Base64.decode(encData, Base64.DEFAULT), "UTF-8");
} catch (Exception e) {
Logger.e(TAG, e.getMessage(), e);
throw new CryptoException(e.getMessage());
}

但是,这给了我

com.android.org.bouncycastle.jcajce.provider.asymmetric.rsa.BCRSAPublicKey cannot be cast to org.bouncycastle.crypto.params.RSAKeyParameters

如何解决这个问题?

I get this error during RSAKeyParameters pubKey = (RSAKeyParameters) new PEMReader(sr).readObject();

附注在 java 中,我使用相同的 BouncyCaSTLe 库

最佳答案

正确的代码是

        RSAPublicKey pubKey = (RSAPublicKey) new PEMReader(sr).readObject();

RSAKeyParameters rsaKeyParameters = new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent());

AsymmetricBlockCipher eng = new PKCS1Encoding(new RSAEngine());
eng.init(true, rsaKeyParameters);

关于java - BouncyCasSTLe RSA 无法转换 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40020067/

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