Java RSA加密失败

Java RSA加密失败,java,security,encryption,rsa,public-key-encryption,Java,Security,Encryption,Rsa,Public Key Encryption,我正在尝试使用字符串公钥加密某些数据 它失败了,错误为:java.security.spec.InvalidKeySpecException:java.security.InvalidKeyException:invalid key format 我的代码是: public class Encryptor { public static void main(String[] args) { String pk = "<here goes my public key&

我正在尝试使用字符串公钥加密某些数据 它失败了,错误为:java.security.spec.InvalidKeySpecException:java.security.InvalidKeyException:invalid key format

我的代码是:

public class Encryptor {
    public static void main(String[] args) {
        String pk = "<here goes my public key>";
        String data = encryptData("Israel", pk);
        System.out.println(data);
    }

    public static String encryptData(String rawData, String publicKey){
        String encryptedString = null;
        try {
            System.out.println("Start of encryptData with data length:" + rawData.length());
            System.out.println("Public Key: " + publicKey);
            X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKey.getBytes());
            KeyFactory factory= KeyFactory.getInstance("RSA");
            Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
            RSAPublicKey pubKey = (RSAPublicKey)factory.generatePublic(spec);        
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            byte[] encryptedByteData =  cipher.doFinal(rawData.getBytes("UTF-8"));
            encryptedString = Base64.getEncoder().encodeToString(encryptedByteData);
            encryptedString = encryptedString.replaceAll("\\s", "");
        } catch (Throwable e) {
            System.out.println("Exception in encryptData." + e);
        }finally{
            System.out.println("End of encryptData with result length:" + (encryptedString==null?"null":encryptedString.length()));
        }
        return encryptedString;  
    }     
}
公共类加密机{
公共静态void main(字符串[]args){
字符串pk=“”;
字符串数据=加密数据(“以色列”,主键);
系统输出打印项次(数据);
}
公共静态字符串encryptData(字符串rawData、字符串公钥){
字符串encryptedString=null;
试一试{
System.out.println(“使用数据长度加密数据的开始:+rawData.length());
System.out.println(“公钥:+公钥”);
X509EncodedKeySpec=新的X509EncodedKeySpec(publicKey.getBytes());
KeyFactory=KeyFactory.getInstance(“RSA”);
Cipher Cipher=Cipher.getInstance(“RSA/ECB/OAEPWITHSHA-256和MGF1padding”);
RSAPublicKey publikey=(RSAPublicKey)工厂.generatePublic(规范);
cipher.init(cipher.ENCRYPT_模式,pubKey);
byte[]encryptedByteData=cipher.doFinal(rawData.getBytes(“UTF-8”);
encryptedString=Base64.getEncoder().encodeToString(encryptedByteData);
encryptedString=encryptedString.replaceAll(“\\s”,即“”);
}捕获(可丢弃的e){
System.out.println(“加密数据中的异常。”+e);
}最后{
System.out.println(“结果长度为+(encryptedString==null?“null”:encryptedString.length())的EncryptedData的结尾);
}
返回encryptedString;
}     
}

有人能帮忙吗?

请包含公钥字符串。这是一个编码问题
X509EncodedKeySpec
需要DER编码,这是一种二进制编码。此编码与字符串不直接兼容。我从给定的.cer文件中提取了公钥,得到了类似于:-开始公钥-----结束公钥-----二进制码编码是当你在你所拥有的PEM编码字符串的中间解码基64时得到的。尝试解码并输入结果。Bouncy Castle拥有处理PEM的实用程序类。