尝试从证书

时间:2016-04-27 05:28:46

标签: java android rsa public-key-encryption private-key

我在我的应用程序中执行 RSA加密和解密。我有两个文件放在assets文件夹中,public_key.cer用于加密,private_key.cer用于解密。从中获取公钥文件我在下面做了。

CertificateFactory certFactory = CertificateFactory.getInstance(X.509, BC);
InputStream is = context.getAssets().open("public_Key.cer");
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(is);
publicKey = cert.getPublicKey();

RSA加密工作正常,而我在尝试从证书获取私钥时遇到问题.Below是用于获取私钥的代码

InputStream is = context.getAssets().open("private_key.cer");
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(is));
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
PrivateKey privateKey = keyFactory.generatePrivate(privSpec);

我得到例外。

    com.android.org.bouncycastle.jcajce.provider.asymmetric.util.ExtendedInvalidKeySpecException: unable to process key spec: java.lang.IllegalArgumentException: unknown object in getInstance: com.android.org.bouncycastle.asn1.DERApplicationSpecific
 at com.android.org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePrivate(KeyFactorySpi.java:105)
 at java.security.KeyFactory.generatePrivate(KeyFactory.java:186)
 at com.teknospire.ndasenda_agent.utils.Conversion.decryptUsingPrivateKey(Conversion.java:111)
 at com.teknospire.ndasenda_agent.utils.Conversion.getDecryptedSkey(Conversion.java:243)
 at com.teknospire.ndasenda_agent.json.JsonCreationAndExtraction.readLoginParams(JsonCreationAndExtraction.java:40)
 at com.mockUp.ndasenda.LoginActivity$LoginRequest.doInBackground(LoginActivity.java:283)
 at com.mockUp.ndasenda.LoginActivity$LoginRequest.doInBackground(LoginActivity.java:1)
 at android.os.AsyncTask$2.call(AsyncTask.java:288)
 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
 at java.lang.Thread.run(Thread.java:848)
 Caused by: java.lang.IllegalArgumentException: unknown object in getInstance: com.android.org.bouncycastle.asn1.DERApplicationSpecific
 at com.android.org.bouncycastle.asn1.ASN1Sequence.getInstance(ASN1Sequence.java:50)
 at com.android.org.bouncycastle.asn1.ASN1Sequence.getInstance(ASN1Sequence.java:33)
 at com.android.org.bouncycastle.asn1.pkcs.PrivateKeyInfo.getInstance(PrivateKeyInfo.java:45)
 at com.android.org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePrivate(KeyFactorySpi.java:91)
 ... 12 more
 java.lang.NullPointerException
 at org.bouncycastle.crypto.params.KeyParameter.<init>(KeyParameter.java:13)
 at com.teknospire.ndasenda_agent.utils.Conversion.decryptUsingSessionKey(Conversion.java:145)
 at com.teknospire.ndasenda_agent.utils.Conversion.getDecryptionData(Conversion.java:185)
 at com.teknospire.ndasenda_agent.json.JsonCreationAndExtraction.readLoginParams(JsonCreationAndExtraction.java:41)
 at com.mockUp.ndasenda.LoginActivity$LoginRequest.doInBackground(LoginActivity.java:283)
 at com.mockUp.ndasenda.LoginActivity$LoginRequest.doInBackground(LoginActivity.java:1)
 at android.os.AsyncTask$2.call(AsyncTask.java:288)
 at java.util.concurrent.FutureTask.run(FutureTask.java:237)
 at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
 at java.lang.Thread.run(Thread.java:848)

任何人都可以帮助我,如何从.cer文件中读取私钥。

提前致谢。

2 个答案:

答案 0 :(得分:0)

检查this的基本实现

摘自网站

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    byte[] input = new byte[] { (byte) 0xbe, (byte) 0xef };
    Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC");

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
        "12345678", 16), new BigInteger("11", 16));
    RSAPrivateKeySpec privKeySpec = new RSAPrivateKeySpec(new BigInteger(
        "12345678", 16), new BigInteger("12345678",
        16));

    RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
    RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privKeySpec);

    cipher.init(Cipher.ENCRYPT_MODE, pubKey);

    byte[] cipherText = cipher.doFinal(input);
    System.out.println("cipher: " + new String(cipherText));

    cipher.init(Cipher.DECRYPT_MODE, privKey);
    byte[] plainText = cipher.doFinal(cipherText);
    System.out.println("plain : " + new String(plainText));

答案 1 :(得分:0)

从文件中获取私钥的代码:

    private KeyStore.PrivateKeyEntry getKeyFromFile(String keyStoreFile,
    String Password, Context cntx) {
    KeyStore.PrivateKeyEntry entry = null;
    try {
        AssetManager am = cntx.getAssets();
        char[] keyStorePassword = Password.toCharArray();
        // Load the KeyStore and get the signing key and certificate.
        KeyStore ks = KeyStore.getInstance("PKCS12");

        ks.load(am.open(keyStoreFile), keyStorePassword);
        String alias = ks.aliases().nextElement();

        Entry entry1 = ks.getEntry(alias, new KeyStore.PasswordProtection(
                keyStorePassword));
        entry = (KeyStore.PrivateKeyEntry) entry1;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return entry;
}

您可以使用以下方法解密数据:

  public byte[] decryptUsingPrivateKey(String encryptedData, Context cntx) {

    byte[] utf8 = null;
    try {
        KeyStore.PrivateKeyEntry privateKey = getKeyFromFile(
                "PrivateKeyFile.pfx", "privatekeypassword", cntx);

        Cipher rsa;
        rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsa.init(Cipher.DECRYPT_MODE, privateKey.getPrivateKey());
        utf8 = rsa.doFinal(Base64.decode(encryptedData));

    } catch (Exception e) {
        System.out.println(e);
    }

    return utf8;
}

注意:

  1. 要使用此功能,您必须编译库&#39; bcprov-jdk15on-152.jar&#39;在您的申请中
  2. 在android中使用私钥文件不是一个好习惯。希望您在测试服务器中使用它。