使用USB证书进行Java加密(智能卡)

时间:2017-06-22 11:09:42

标签: java encryption smartcard pkcs#11

我正在编写一个用USB证书(智能卡)加密和签名的Java程序。我有一个共享库(Windows上的.dll,Linux上的.so),它为硬件实现了PKCS11。

我正在搜索现有解决方案并找到以下指南http://docs.oracle.com/javase/7/docs/technotes/guides/security/p11guide.html该指南建议使用sun.security.pkcs11.SunPKCS11提供程序。

但是,我遇到了sun.security.pkcs11包的主要问题。我设法使签名工作,但我无法进行加密/解密。我在搜索,发现开发人员不应该使用' sun'包http://www.oracle.com/technetwork/java/faq-sun-packages-142232.html

现在,我想知道我应该使用什么而不是sun.security.pkcs11?

我有一个可用的C ++代码(使用NSS库来处理硬件)。我发现,NSS库正在使用C_WrapKey和C_UnwrapKey进行加密。

以下代码应该使用C_WrapKey和C_UnwrapKey进行加密,但我可以在.so库的日志中看到java代码调用C_DecryptInit,由于某种原因失败(C_DecryptInit()Init操作失败。)。

注意:两者(Cipher.PUBLIC_KEY / Cipher.PRIVATE_KEY和Cipher.WRAP_MODE / Cipher.UNWRAP_MODE适用于软证书)。该代码仅与Java 1.7(Windows机器上的32位Java)一起使用硬证书。

堆栈追踪:

Exception in thread "main" java.security.InvalidKeyException: init() failed
        at sun.security.pkcs11.P11RSACipher.implInit(P11RSACipher.java:239)
        at sun.security.pkcs11.P11RSACipher.engineUnwrap(P11RSACipher.java:479)
        at javax.crypto.Cipher.unwrap(Cipher.java:2510)
        at gem_test.Test.decryptDocument(Test.java:129)
        at gem_test.Test.main(Test.java:81)
Caused by: sun.security.pkcs11.wrapper.PKCS11Exception: CKR_KEY_FUNCTION_NOT_PERMITTED
        at sun.security.pkcs11.wrapper.PKCS11.C_DecryptInit(Native Method)
        at sun.security.pkcs11.P11RSACipher.initialize(P11RSACipher.java:304)
        at sun.security.pkcs11.P11RSACipher.implInit(P11RSACipher.java:237)
        ... 4 more

代码:

package gem_test;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.security.pkcs11.SunPKCS11;

public class Test {
    private static final String ALGORITHM = "RSA";

    static int hard_soft = 1; // 1 - smart card, 2 - soft certificate
    static int sign_encrypt = 2; // 1- sign, 2 - encryption


    public static void main(String[] args) throws Exception {
        PrivateKey privateKey;
        PublicKey pubKey;
        if (hard_soft == 1) {
            String pkcsConf = (
                "name = Personal\n" +
                "library = /usr/local/lib/personal/libP11.so\n" +
//                    "library = c:\\perso\\bin\\personal.dll\n" +
                "slot = 0\n"
            );

            char[] pin = "123456".toCharArray();
            String useCertAlias = "Digital Signature";
//                String useCertAlias = "Non Repudiation";

            SunPKCS11 provider = new SunPKCS11(new ByteArrayInputStream(pkcsConf.getBytes()));
            String providerName = provider.getName();
            Security.addProvider(provider);

            KeyStore keyStore = KeyStore.getInstance("PKCS11", providerName);
            keyStore.load(null, pin);

            privateKey = (PrivateKey) keyStore.getKey(useCertAlias, pin);
            X509Certificate certificate = (X509Certificate) keyStore.getCertificate(useCertAlias);
            pubKey = certificate.getPublicKey();
        } else if (hard_soft == 2) {
            /*
             mkdir /tmp/softkey
             cd /tmp/softkey

             openssl genrsa 2048 > softkey.key
             chmod 400 softkey.key
             openssl req -new -x509 -nodes -sha1 -days 365 -key softkey.key -out softkey.crt
             openssl pkcs12 -export -in softkey.crt -inkey softkey.key -out softkey.pfx
             rm -f softkey.key softkey.crt
             */
            String pfx = "/tmp/softkey/softkey.pfx";
            String useCertAlias = "1";

            KeyStore keyStore1 = KeyStore.getInstance("PKCS12");
            keyStore1.load(new FileInputStream(pfx), new char[]{});

            privateKey = (PrivateKey) keyStore1.getKey(useCertAlias, new char[]{});
            X509Certificate certificate = (X509Certificate) keyStore1.getCertificate(useCertAlias);
            pubKey = certificate.getPublicKey();
        } else {
            throw new IllegalStateException();
        }

        if (sign_encrypt == 1) {
            byte[] sig = signDocument("msg content".getBytes(), privateKey);
            boolean result = verifyDocument("msg content".getBytes(), sig, pubKey);
            System.out.println("RESULT " + result);
        } else if (sign_encrypt == 2) {
            byte[] encrypted = encryptDocument("msg content".getBytes(), pubKey);
            byte[] decryptedDocument = decryptDocument(encrypted, privateKey);
            System.out.println("RESULT " + new String(decryptedDocument));
        } else {
            throw new IllegalStateException();
        }
    }

    private static byte[] signDocument(byte[] aDocument, PrivateKey aPrivateKey) throws Exception {
        Signature signatureAlgorithm = Signature.getInstance("SHA1withRSA");
        signatureAlgorithm.initSign(aPrivateKey);
        signatureAlgorithm.update(aDocument);
        byte[] digitalSignature = signatureAlgorithm.sign();
        return digitalSignature;
    }

    private static boolean verifyDocument(byte[] aDocument, byte[] sig, PublicKey pubKey) throws Exception {
        Signature signatureAlgorithm = Signature.getInstance("SHA1withRSA");
        signatureAlgorithm.initVerify(pubKey);
        signatureAlgorithm.update(aDocument);
        return signatureAlgorithm.verify(sig);
    }


    private static byte[] encryptDocument(byte[] aDocument, PublicKey pubKey) throws Exception {
        int encrypt_wrap = 2;
        if (encrypt_wrap == 1) {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.PUBLIC_KEY, pubKey);
            return cipher.doFinal(aDocument);
        } else if (encrypt_wrap == 2) {
            SecretKey data = new SecretKeySpec(aDocument, 0, aDocument.length, "AES");
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.WRAP_MODE, pubKey);
            return cipher.wrap(data);
        } else {
            throw new IllegalStateException();
        }
    }

    public static byte[] decryptDocument(byte[] encryptedDocument, PrivateKey aPrivateKey) throws Exception {
        int encrypt_wrap = 2;
        if (encrypt_wrap == 1) {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.PRIVATE_KEY, aPrivateKey);
            return cipher.doFinal(encryptedDocument);
        } else if (encrypt_wrap == 2) {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.UNWRAP_MODE, aPrivateKey);
            SecretKey res = (SecretKey) cipher.unwrap(encryptedDocument, "AES", Cipher.SECRET_KEY);
            return res.getEncoded();
        } else {
            throw new IllegalStateException();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我认为解决方案只是使用ENCRYPT代替WRAPDECRYPT代替UNWRAP

要了解原因,请务必了解WRAPUNWRAP的作用。基本上它们只执行ENCRYPTDECRYPT,但它们只返回一个键。现在,如果你在软件中执行此操作,那么除了之外没有任何区别,因为您不需要使用SecretKeySpecSecretKeyFactory来重新生成密钥解密的数据。

但是,如果您在硬件上执行此操作,则生成的密钥通常会保留在硬件设备(或令牌)上。如果您拥有HSM,这当然很好:它只能生成(特定于会话的)密钥并返回句柄。但在智能卡上,这通常是不可能的。即使它是:您也不想将所有消息发送到智能卡以使其加密。

此外,如果您使用Java,则无法直接控制包装或解包调用的PKCS#11输入参数。

请尝试ENCRYPTDECRYPT,然后在软件中重新生成密钥。

或者,您可以使用Open Source IAIK包装程序库复制 PKCS#11 换行和解包调用;模仿C功能。但这与需要Cipher类的调用不兼容。

请注意,Sun提供商中的RSA很可能意味着RSA/ECB/PKCS1Padding。如果您需要不同的RSA算法,那么您应该尝试算法字符串;这也可能是您面临的问题:您使用了错误的算法。

答案 1 :(得分:0)

最后,我们使用此解决方案来解决使用智能卡从Java 8进行签名和加密/解密的问题。它适用于使用64位Java的Linux和Windows。

我们还没有设法修复Wrap / Unwrap部分。我相信可以用java.lang.instrument修复错误,但我们决定更换所有智能卡,以便他们支持" Data Encipherement"。

修补JDK 8 SunPKCS11提供程序错误的代码:

String pkcsConf = (
    "name = \"Personal\"\n" +
    String.format("library = \"%s\"\n", hardCertLib) +
    String.format("slot = %d\n", slotId)
);

SunPKCS11 provider = new SunPKCS11(new ByteArrayInputStream(pkcsConf.getBytes()));
tryFixingPKCS11ProviderBug(provider);

....


/**
 * This a fix for PKCS11 bug in JDK8. This method prefetches the mech info from the driver.
 * @param provider
 */
public static void tryFixingPKCS11ProviderBug(SunPKCS11 provider) {
    try {
        Field tokenField = SunPKCS11.class.getDeclaredField("token");
        tokenField.setAccessible(true);
        Object token = tokenField.get(provider);

        Field mechInfoMapField = token.getClass().getDeclaredField("mechInfoMap");
        mechInfoMapField.setAccessible(true);
        @SuppressWarnings("unchecked")
        Map<Long, CK_MECHANISM_INFO> mechInfoMap = (Map<Long, CK_MECHANISM_INFO>) mechInfoMapField.get(token);
        mechInfoMap.put(PKCS11Constants.CKM_SHA1_RSA_PKCS, new CK_MECHANISM_INFO(1024, 2048, 0));
    } catch(Exception e) {
        logger.info(String.format("Method tryFixingPKCS11ProviderBug failed with '%s'", e.getMessage()));
    }
}