栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

错误的填充例外-pkcs11中的RSA / ECB / OAEPWITHSHA-256ANDMGF1PADDING

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

错误的填充例外-pkcs11中的RSA / ECB / OAEPWITHSHA-256ANDMGF1PADDING

P11Key.P11PrivateKey
从加密狗获得了不可提取的私钥。不能在PKCS11提供程序之外使用它,因此,应将SunPKCS11提供程序用于具有该密钥的操作。

不幸的是,SunPKCS11提供程序不支持OAEP填充,因此更加困难。仍然可以使用BouncyCastle进行加密,但是可以在没有填充和SunPKCS11提供程序的情况下进行解密。keyLength参数是以位(1024、2048等)为单位的RSA密钥模数长度。

private void testEncryption(byte[] plainText, PrivateKey privateKey, PublicKey publicKey, int keyLength) throws GeneralSecurityException {    System.out.println("Plain text: " + DatatypeConverter.printHexBinary(plainText));    Provider bcProvider = new BouncyCastleProvider();    Cipher rsaCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING", bcProvider);    rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);    byte[] cipherText = rsaCipher.doFinal(plainText);    System.out.println("Cipher text: " + DatatypeConverter.printHexBinary(cipherText));    Provider pkcs11provider = new SunPKCS11("C:\Users\manishs525\pkcs11.cfg");    Cipher rsaCipher2 = Cipher.getInstance("RSA/ECB/NoPadding", pkcs11provider);    rsaCipher2.init(Cipher.DECRYPT_MODE, privateKey);    byte[] paddedPlainText = rsaCipher2.doFinal(cipherText);        if (paddedPlainText.length < keyLength / 8) {        byte[] tmp = new byte[keyLength / 8];        System.arraycopy(paddedPlainText, 0, tmp, tmp.length - paddedPlainText.length, paddedPlainText.length);        System.out.println("Zero padding to " + (keyLength / 8));        paddedPlainText = tmp;    }    System.out.println("OAEP padded plain text: " + DatatypeConverter.printHexBinary(paddedPlainText));    OAEPParameterSpec paramSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);    RSAPadding padding = RSAPadding.getInstance(RSAPadding.PAD_OAEP_MGF1, keyLength / 8, new SecureRandom(), paramSpec);    byte[] plainText2 = padding.unpad(paddedPlainText);    System.out.println("Unpadded plain text: " + DatatypeConverter.printHexBinary(plainText2));}

笔记:

  • 在JDK1.7之前,SunPKCS11尚未实现RSA / ECB / NoPadding。
  • 此示例已通过BouncyCastle 1.50和JDK 1.7进行了测试


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/497945.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号