【问题标题】:BouncyCastle RSA cannot cast androidBouncyCastle RSA 无法投射 android
【发布时间】:2016-10-13 11:45:33
【问题描述】:

我有使用 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 不能转换为 org.bouncycastle.crypto.params.RSAKeyParameters

我该如何解决这个问题?

我在 RSAKeyParameters pubKey = (RSAKeyParameters) 期间收到此错误 新 PEMReader(sr).readObject();

附:在 java 中我使用相同的 BouncyCastle 库

【问题讨论】:

    标签: java android encryption rsa bouncycastle


    【解决方案1】:

    正确的代码是

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 2016-12-15
      相关资源
      最近更新 更多