簡體   English   中英

BouncyCastle RSA無法投射android

[英]BouncyCastle RSA cannot cast android

我在C#中使用BouncyCastle的代碼

        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無法強制轉換為org.bouncycastle.crypto.params.RSAKeyParameters

我怎么解決這個問題?

我在RSAKeyParameters期間遇到此錯誤pubKey =(RSAKeyParameters)new PEMReader(sr).readObject();

PS在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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM