我尝试在Java程序中实现RSA算法。我面临“ BadPaddingException:数据必须以零开头”的问题。以下是用于加密和解密我的数据的方法:
public byte[] encrypt(byte[] input) throws Exception { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");// cipher.init(Cipher.ENCRYPT_MODE, this.publicKey); return cipher.doFinal(input); } public byte[] decrypt(byte[] input) throws Exception { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");/// cipher.init(Cipher.DECRYPT_MODE, this.privateKey); return cipher.doFinal(input); }
通过以下方式从文件中读取privateKey和publicKey属性:
public PrivateKey readPrivKeyFromFile(String keyFileName) throws IOException { PrivateKey key = null; try { FileInputStream fin = new FileInputStream(keyFileName); ObjectInputStream ois = new ObjectInputStream(fin); BigInteger m = (BigInteger) ois.readObject(); BigInteger e = (BigInteger) ois.readObject(); RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e); KeyFactory fact = KeyFactory.getInstance("RSA"); key = fact.generatePrivate(keySpec); ois.close(); } catch (Exception e) { e.printStackTrace(); } return key; }
私钥和公钥的创建方式如下:
public void Initialize() throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(2048); keyPair = keygen.generateKeyPair(); KeyFactory fact = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pub = fact.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class); RSAPrivateKeySpec priv = fact.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class); saveToFile("public.key", pub.getModulus(), pub.getPublicExponent()); saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent()); }
然后保存在文件中:
public void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException { FileOutputStream f = new FileOutputStream(fileName); ObjectOutputStream oos = new ObjectOutputStream(f); oos.writeObject(mod); oos.writeObject(exp); oos.close(); }
我不知道问题是怎么来的。任何帮助将不胜感激!
提前致谢。
原则上,代码看起来还可以- 我将进行一些登录以确保所生成的密钥是真正从文件中读取的密钥(您所做的事情并不像使用新密钥生成数据那样愚蠢,然后例如尝试用旧的阅读它?)