java.security.UnrecoverableKeyException:不匹配

java.security.UnrecoverableKeyException:不匹配,java,android,encryption,Java,Android,Encryption,问题:需要将RSA私钥保存在加密位置。为此,请尝试使用KeyStore 代码片段: package com.example.encryptiontest; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingExcept

问题:需要将RSA私钥保存在加密位置。为此,请尝试使用
KeyStore

代码片段

package com.example.encryptiontest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.UnrecoverableEntryException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Date;

import javax.security.auth.x500.X500Principal;

import org.bouncycastle.x509.X509V1CertificateGenerator;

import android.content.Context;
import android.util.Base64;

public class Encryption {
    private static final String ALIAS = "myAlias";
    private static final String FILE_NAME="key_store";
    private Context mContext;
    public Encryption(Context context){
        mContext = context;
    }
    public void save() throws NoSuchAlgorithmException, InvalidKeySpecException, CertificateEncodingException, InvalidKeyException, NoSuchProviderException, SignatureException, KeyStoreException, CertificateException, FileNotFoundException, UnsupportedEncodingException, IOException{
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048);
        KeyPair kp = kpg.genKeyPair();

        KeyFactory fact = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
                RSAPublicKeySpec.class);
        RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
                RSAPrivateKeySpec.class);

        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(pub.getModulus(),
                pub.getPublicExponent());
        PublicKey pubKey = fact.generatePublic(keySpec);
        PrivateKey privateKey = fact.generatePrivate(new RSAPrivateKeySpec(
                priv.getModulus(), priv.getPrivateExponent()));

        saveToKeyStore(pubKey,ALIAS,mContext.getFilesDir() + FILE_NAME,privateKey);
    }

    public void load() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException{
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        char[] password = generatePassword(ALIAS);
        FileInputStream in = new FileInputStream(mContext.getFilesDir() + FILE_NAME);
        keyStore.load(in, password);
        KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore
                .getEntry(ALIAS, null);
        PrivateKey pubKey = (PrivateKey) keyEntry.getPrivateKey();
    }

    private void saveToKeyStore(PublicKey publicKey, String alias,
            String fileName, PrivateKey privateKey)
            throws CertificateEncodingException, NoSuchProviderException,
            NoSuchAlgorithmException, SignatureException, InvalidKeyException,
            KeyStoreException, IOException, CertificateException,
            FileNotFoundException, UnsupportedEncodingException {
        X509Certificate cert = getCertificate(publicKey, privateKey);
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        char[] password = generatePassword(alias);

        keyStore.load(null);
        keyStore.setKeyEntry(alias, privateKey, null,
                new Certificate[] { cert });
        FileOutputStream out = new FileOutputStream(fileName);

        keyStore.store(out, password);
        out.close();
    }

    private X509Certificate getCertificate(PublicKey publicKey,
            PrivateKey privateKey) throws CertificateEncodingException,
            NoSuchProviderException, NoSuchAlgorithmException,
            SignatureException, InvalidKeyException {
        Date startDate = new Date(); // time from which certificate is valid
        Date expiryDate = new Date(2050, 3, 3); // time after which certificate
                                                // is not valid
        BigInteger serialNumber = BigInteger.ONE; // serial number for
                                                    // certificate
        KeyPair keyPair = new KeyPair(publicKey, privateKey); // EC
                                                                // public/private
                                                                // key pair
        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        X500Principal dnName = new X500Principal("CN=Test CA Certificate");
        certGen.setSerialNumber(serialNumber);
        certGen.setIssuerDN(dnName);
        certGen.setNotBefore(startDate);
        certGen.setNotAfter(expiryDate);
        certGen.setSubjectDN(dnName); // note: same as issuer
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA512withRSA");
        X509Certificate cert = certGen.generate(keyPair.getPrivate(), "BC");
        return cert;
    }

    private char[] generatePassword(String userName)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        String defaultUdid = android.provider.Settings.System.getString(
                mContext.getContentResolver(),
                android.provider.Settings.Secure.ANDROID_ID);
        MessageDigest md = MessageDigest.getInstance("SHA-512");

        byte[] bSalt = defaultUdid.getBytes("UTF-8");
        byte[] bPw = userName.getBytes("UTF-8");
        md.update(bPw);
        byte[] r = md.digest(bSalt);
        return Base64.encodeToString(r, Base64.URL_SAFE).toCharArray();
    }
}
我使用bouncycastle库生成证书

堆栈跟踪

03-16 14:00:52.106: W/System.err(27883): java.security.UnrecoverableKeyException: no match
03-16 14:00:52.108: W/System.err(27883):    at com.android.org.bouncycastle.jce.provider.JDKKeyStore$StoreEntry.getObject(JDKKeyStore.java:310)
03-16 14:00:52.110: W/System.err(27883):    at com.android.org.bouncycastle.jce.provider.JDKKeyStore.engineGetKey(JDKKeyStore.java:611)
03-16 14:00:52.111: W/System.err(27883):    at java.security.KeyStoreSpi.engineGetEntry(KeyStoreSpi.java:372)
03-16 14:00:52.113: W/System.err(27883):    at java.security.KeyStore.getEntry(KeyStore.java:644)
03-16 14:00:52.114: W/System.err(27883):    at com.example.encryptiontest.Encryption.load(Encryption.java:71)
03-16 14:00:52.115: W/System.err(27883):    at com.example.encryptiontest.MainActivity.onCreate(MainActivity.java:16)
03-16 14:00:52.117: W/System.err(27883):    at android.app.Activity.performCreate(Activity.java:5122)
03-16 14:00:52.118: W/System.err(27883):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
03-16 14:00:52.120: W/System.err(27883):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
03-16 14:00:52.121: W/System.err(27883):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
03-16 14:00:52.123: W/System.err(27883):    at android.app.ActivityThread.access$600(ActivityThread.java:156)
03-16 14:00:52.124: W/System.err(27883):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
03-16 14:00:52.125: W/System.err(27883):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-16 14:00:52.126: W/System.err(27883):    at android.os.Looper.loop(Looper.java:153)
03-16 14:00:52.128: W/System.err(27883):    at android.app.ActivityThread.main(ActivityThread.java:5299)
03-16 14:00:52.129: W/System.err(27883):    at java.lang.reflect.Method.invokeNative(Native Method)
03-16 14:00:52.130: W/System.err(27883):    at java.lang.reflect.Method.invoke(Method.java:511)
03-16 14:00:52.132: W/System.err(27883):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
03-16 14:00:52.133: W/System.err(27883):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
03-16 14:00:52.134: W/System.err(27883):    at dalvik.system.NativeStart.main(Native Method)

可能是一个错误的密码。从
generatePassword
中写出密码进行调试,并使用keytool检查它是否可以读取生成的密钥库的内容

另一位Stack Overflow/Spongy Castle用户表示,在构建密钥库时,它有助于指定构造函数。对他来说:

KeyStore ks = new KeyStore("BKS","SC");
而不是

KeyStore ks = new KeyStore("BKS");

我知道您没有使用构造函数来创建密钥库,但此信息可能会有所帮助。

当我执行您的代码时,我遇到一个例外,即私钥条目必须使用密码进行保护:

java.security.UnrecoverableKeyException: requested entry requires a password
    at java.security.KeyStoreSpi.engineGetEntry(KeyStoreSpi.java:459)
    at java.security.KeyStore.getEntry(KeyStore.java:1290)
    at KeyStorage.load(KeyStorage.java:50)
    at PKI.main(PKI.java:518)
看起来Java(Oracle和Android)的实现允许在没有任何保护的情况下创建私钥条目(在密钥库中,密钥库本身和每个条目可能有自己的密码保护),但在加载过程中,它们需要强制密码。要修复此问题,只需在KeyStore.getEntry()中指定密码

另一个选择是使用

PrivateKey key = (PrivateKey) keyStore.getKey(ALIAS, null);

@Barret所指的链接是


我面临着类似的问题。在我的例子中,存储和检索时的密码与字符串方法不同。尝试为调试目的提供硬编码密码

有几个地方需要改变:

1) 我将bouncycastle库更改为spongycastle

03-16 14:00:52.106: W/System.err(27883): java.security.UnrecoverableKeyException: no match
03-16 14:00:52.108: W/System.err(27883):    at com.android.org.bouncycastle.jce.provider.JDKKeyStore$StoreEntry.getObject(JDKKeyStore.java:310)
03-16 14:00:52.110: W/System.err(27883):    at com.android.org.bouncycastle.jce.provider.JDKKeyStore.engineGetKey(JDKKeyStore.java:611)
03-16 14:00:52.111: W/System.err(27883):    at java.security.KeyStoreSpi.engineGetEntry(KeyStoreSpi.java:372)
03-16 14:00:52.113: W/System.err(27883):    at java.security.KeyStore.getEntry(KeyStore.java:644)
03-16 14:00:52.114: W/System.err(27883):    at com.example.encryptiontest.Encryption.load(Encryption.java:71)
03-16 14:00:52.115: W/System.err(27883):    at com.example.encryptiontest.MainActivity.onCreate(MainActivity.java:16)
03-16 14:00:52.117: W/System.err(27883):    at android.app.Activity.performCreate(Activity.java:5122)
03-16 14:00:52.118: W/System.err(27883):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
03-16 14:00:52.120: W/System.err(27883):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
03-16 14:00:52.121: W/System.err(27883):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
03-16 14:00:52.123: W/System.err(27883):    at android.app.ActivityThread.access$600(ActivityThread.java:156)
03-16 14:00:52.124: W/System.err(27883):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
03-16 14:00:52.125: W/System.err(27883):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-16 14:00:52.126: W/System.err(27883):    at android.os.Looper.loop(Looper.java:153)
03-16 14:00:52.128: W/System.err(27883):    at android.app.ActivityThread.main(ActivityThread.java:5299)
03-16 14:00:52.129: W/System.err(27883):    at java.lang.reflect.Method.invokeNative(Native Method)
03-16 14:00:52.130: W/System.err(27883):    at java.lang.reflect.Method.invoke(Method.java:511)
03-16 14:00:52.132: W/System.err(27883):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
03-16 14:00:52.133: W/System.err(27883):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
03-16 14:00:52.134: W/System.err(27883):    at dalvik.system.NativeStart.main(Native Method)
2) 增加

3) 使用的
keystorekeystore=KeyStore.getInstance(“BKS”、“SC”)

4) 使用


原因是不同的提供者提供不同的密钥二进制表示。因此,如果您使用一个提供程序生成密钥,那么如果尝试使用另一个提供程序从二进制流还原,您可能会遇到问题

能否发布异常的堆栈跟踪?如果不知道Spongy Castle的确切版本,很难说,但看起来在类路径上有多个海绵状的Castle jar,它们相互冲突。@divanov我只使用一个jar文件。这也是图书馆的最新版本
static {
    Security.addProvider(new BouncyCastleProvider());
}
KeyFactory fact1 = KeyFactory.getInstance("RSA","SC");
PublicKey pubKey = fact1.generatePublic(keySpec);
PrivateKey privateKey = fact1.generatePrivate(new RSAPrivateKeySpec(priv
    .getModulus(), priv.getPrivateExponent()));