java—没有安装的提供程序支持这个密钥:sun.security.rsa.rsapublickeyimpl,也没有这样的算法:aes/gcm/nopadding

but5z9lq  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(778)

我试图创建一个密码,以便对我创建的aes密钥进行编码。我从存储公钥的文件中读入了公钥,并将其从字节转换为公钥对象。当我尝试使用这个公钥初始化密码时,我得到错误“没有安装的提供程序支持这个密钥:sun.security.rsa.rsapublickeyimpl” cipherAES.init(Cipher.ENCRYPT_MODE, DecodedPublicKey); 因此,当我创建一个rsa2048密钥生成器对象来获取提供者时(这是我在另一个程序中创建前一个密钥时使用的规范),我在下面得到错误“no-such-algorithm:aes/gcm/nopadding” Cipher cipherAES = Cipher.getInstance("AES/GCM/NoPadding", kpgenProv.getName()); 我需要使用aes/gcm/nopadding转换,并且从.getprovider提供的提供者似乎是正确的,这就是sunrsasign。有人知道这个问题吗?当没有提供程序时,它可以识别转换,但当有提供程序时,它会拒绝转换。

String pubAlgo = publicKeyScanner.nextLine(); // not used
      String PublicKey = publicKeyScanner.nextLine(); // this will stop when it hits a newline and the encoded key may have the newline char value causing the private key to be piecemeal
      byte[] decodedPublicKey = Base64.getDecoder().decode(PublicKey);
      KeyFactory kf = KeyFactory.getInstance("RSA"); // or "EC" or whatever
      PublicKey DecodedPublicKey = kf.generatePublic(new X509EncodedKeySpec(decodedPublicKey));
      publicKeyScanner.close();
      System.out.println(DecodedPublicKey.toString());

      KeyGenerator keyGen = KeyGenerator.getInstance("AES");
      keyGen.init(128); // for example
      SecretKey AESKey = keyGen.generateKey();

      KeyPairGenerator kpgen = KeyPairGenerator.getInstance("RSA");
      kpgen.initialize(2048);
      Provider kpgenProv = kpgen.getProvider();
      System.out.println(kpgenProv.getName());
      Cipher cipherAES = Cipher.getInstance("AES/GCM/NoPadding", kpgenProv.getName());
      cipherAES.init(Cipher.ENCRYPT_MODE, DecodedPublicKey);
      byte[] AESKEYBYTES = AESKey.getEncoded();```
f2uvfpb9

f2uvfpb91#

javajdk通常与一些负责加密操作的安全提供者一起提供。由于历史原因,它们没有合并/捆绑,而是存在于彼此之下。如果您通过示例化java来选择一个算法,您将发现哪个提供者对这个算法“负责”,并接受他。
另一方面,如果您想使用特定的提供程序,可以在示例化过程中命名该提供程序(这就是您对第二个参数“kpgenprov.getname”所做的操作):

Cipher.getInstance("AES/GCM/NoPadding", kpgenProv.getName())

正如您在我的简单程序中看到的,“rsa”和“aes/gcm/nopadding”有两个不同的提供程序,但是当强制某个特定的提供程序时,您会收到“未安装提供程序支持…”异常。
因此,通常您会忽略提供程序名称,让java为该算法选择“最佳”提供程序。
我的系统上的输出(openjdk11):

Get security provider
provider for RSA encryption: SunRsaSign version 11
provider for AES/GCM/NoPadding: SunJCE version 11

代码:

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException {
        System.out.println("Get security provider");

        KeyFactory kf = KeyFactory.getInstance("RSA");
        System.out.println("provider for RSA encryption: " + kf.getProvider());

        Cipher cipherAES = Cipher.getInstance("AES/GCM/NoPadding");
        System.out.println("provider for AES/GCM/NoPadding: " + cipherAES.getProvider());
    }
}

相关问题