尝试加密时出现此错误。 java.security.InvalidKeyException:传递给RSA的未知密钥类型

时间:2019-03-24 17:17:57

标签: java android firebase cryptography rsa

我使用密钥对生成器来生成公共和私有密钥。我想将公钥存储在Firebase上。为此,我正在使用getModulus和getExponent并稍后重新生成公钥。当我重新生成密钥时,我得到了完全相同的模量和指数,但在尝试加密时仍然收到此错误。

//This is my cryptography class
public class Cryptography {

    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048, new SecureRandom());
        KeyPair pair = generator.generateKeyPair();
        return pair;
    }
    public static String encrypt1(String plainText, PublicKey publicKey) throws Exception {
        Cipher encryptCipher = Cipher.getInstance("RSA");

        encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);

        byte[] cipherText = encryptCipher.doFinal(plainText.getBytes("UTF-8"));
        String str = new String(cipherText, "UTF-8");

        return Base64.encodeToString(cipherText, Base64.NO_WRAP);
    }
    public static String decrypt1(String cipherText, PrivateKey privateKey) throws Exception {
        byte[] bytes = android.util.Base64.decode(cipherText, Base64.DEFAULT);

        Cipher decriptCipher = Cipher.getInstance("RSA");
        decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);

        return new String(decriptCipher.doFinal(bytes), "UTF-8");
    }

    public static String sign(String plainText, PrivateKey privateKey) throws Exception {
        Signature privateSignature = Signature.getInstance("SHA256withRSA");
        privateSignature.initSign(privateKey);
        privateSignature.update(plainText.getBytes("UTF-8"));

        byte[] signature = privateSignature.sign();

        return Base64.encodeToString(signature, Base64.NO_WRAP);
    }

    public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
        Signature publicSignature = Signature.getInstance("SHA256withRSA");
        publicSignature.initVerify(publicKey);
        publicSignature.update(plainText.getBytes("UTF-8"));

        byte[] signatureBytes = android.util.Base64.decode(signature, Base64.DEFAULT);

        return publicSignature.verify(signatureBytes);
    }
}




//Generate  keypair
    try {
      keyPair =  Cryptography.generateKeyPair();
        } catch (Exception e) {
             e.printStackTrace();
          }
          KeyFactory factory = null;
                    try {
                        factory = KeyFactory.getInstance("RSA");
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    }
                    RSAPublicKeySpec pub = null;
                    RSAPrivateKeySpec priv = null;
                    try {
                         pub = factory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
                         Log.e("PublicKey", pub.getModulus() + "\n" + pub.getPublicExponent());
                         priv = factory.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class);
                    } catch (InvalidKeySpecException e) {
                        e.printStackTrace();
                    }
registerUser(display_name, email, password,Publicmod.toString(), Publicexpon.toString());



//Retreving the Modulus and Exponent and regenerating the publicKey


 String expo = getIntent().getStringExtra("expo");
        String mod = getIntent().getStringExtra("mod");
        Log.e("mod", mod);
        Log.e("expo", expo);

        BigInteger PublicExponent = new BigInteger(expo,16);
        BigInteger PublicMod = new BigInteger(mod,16);

        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(PublicMod, PublicExponent);
        KeyFactory fact = null;
        try {
            fact = KeyFactory.getInstance("RSA");

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        PublicKey pubKey = null;
        try {
            pubKey = fact.generatePublic(keySpec);
            Log.e("Public Key", pubKey.toString());
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        Log.e("Public Key", pubKey.toString());

1 个答案:

答案 0 :(得分:0)

我跑了

public static KeyPair generateKeyPair() throws NoSuchAlgorithmException
    {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048, new SecureRandom());
        return generator.generateKeyPair();
    }

    public static void main(String[] args) throws Exception
    {
        //Generate  keypair
        KeyPair keyPair = generateKeyPair();
        KeyFactory factory = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec pub = factory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
        BigInteger PublicExponent = pub.getPublicExponent();
        BigInteger PublicMod = pub.getModulus();

        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(PublicMod, PublicExponent);

        KeyFactory fact = KeyFactory.getInstance("RSA");
        PublicKey pubKey = fact.generatePublic(keySpec);
        System.out.println("Success " + pubKey);
    }

印有“成功...”的字样。

这意味着您的错误是对expo和mod的检索。 它们一定不能与您使用的相同。

还有一些注意事项:

  • 使用常量Charset.forName("UTF-8"),而不要在getBytes中放入“ UTF-8”
  • 生成new SecureRandom时不需要放置KeyPair
  • 如果不使用它,不要创建一个字符串
  • 如果您仍然有权访问数据,请不要获取数据