在读取我的公钥和私钥文件时遇到问题

inn6fuwd  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(533)

我在一个加密类中有一个方法,负责读取我的rsa密钥文件和相应的组件。要做到这一点,请使用 InputStream 带有 ObjectInputStream 对象。这些被称为 in 以及 input 分别。我的问题是我可能对如何使用这些有错误的想法。当我尝试从我的加密方法调用这个类来加密一些二进制数据时,出现了我的错误。我将在下面的链接 ReadKey 以及 Encrypt 方法。
两种方法:

  1. PublicKey ReadKey(String File) throws IOException{
  2. PublicKey publicKey = null;
  3. InputStream in = Encryption.class.getResourceAsStream(File);
  4. ObjectInputStream input = new ObjectInputStream(new BufferedInputStream(in));
  5. try {
  6. BigInteger m = (BigInteger) input.readObject();
  7. BigInteger e = (BigInteger) input.readObject();
  8. RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
  9. KeyFactory fact = KeyFactory.getInstance("RSA");
  10. publicKey = fact.generatePublic(keySpec);
  11. return publicKey;
  12. }catch (Exception e){
  13. }finally{
  14. // input.close();
  15. }
  16. return null;
  17. }
  18. public byte[] Encrypt(byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException, BadPaddingException, IllegalBlockSizeException{
  19. PublicKey publicKey = ReadKey("/public.key");
  20. Cipher cipher = Cipher.getInstance("RSA");
  21. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  22. byte[] cipherData = cipher.doFinal(data);
  23. return cipherData;
  24. }

为了补充我的问题,我将解释如何使用这些。我有其他方法可以创建一个公共和私有的rsa密钥。现在,我使用的加密程序是一个简单的消息传递程序,它通过套接字将消息从服务器发送到客户机。我想使用rsa来实现端到端的加密,这就是所有这些的用武之地。当用户单击send(另存为变量)时,我获取输入的文本 message )然后跑这条线 sendMessage(Encryption.Encrypt(Converter(message))); 它首先将字符串交给我的converter方法,该方法将消息从字符串转换为字节数组[]。这是然后交给我的加密方法上面。当我的加密方法调用 PublicKey publicKey = ReadKey("/public.key"); 似乎是围绕这个问题的 ObjectInputStream input = new ObjectInputStream(new BufferedInputStream(in));ReadKey 方法。我对这个有点困惑,因为我对这些工具还比较陌生。我将在下面留下错误片段的链接:

  1. java.io.IOException: Stream closed
  2. at java.base/java.io.BufferedInputStream.getInIfOpen(BufferedInputStream.java:157)
  3. at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:244)
  4. at java.base/java.io.BufferedInputStream.read1(BufferedInputStream.java:284)
  5. at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:343)
  6. at java.base/java.io.ObjectInputStream$PeekInputStream.read(ObjectInputStream.java:2914)
  7. at java.base/java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2930)
  8. at java.base/java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3427)
  9. at java.base/java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:962)
  10. at java.base/java.io.ObjectInputStream.<init>(ObjectInputStream.java:405)
  11. at oserver.Encryption.ReadKey(Encryption.java:114)
  12. at oserver.Encryption.Encrypt(Encryption.java:133)
  13. at oserver.Server.jButton1ActionPerformed(Server.java:172)
  14. at oserver.Server$1.actionPerformed(Server.java:105)

我知道读到这篇文章很长很抱歉。任何帮助都会非常感激,如果你需要更多的信息,我没有问题。非常感谢:)
如何储存钥匙:

  1. public void KeyStorage() throws NoSuchAlgorithmException, InvalidKeySpecException{
  2. KeyFactory factory = KeyFactory.getInstance("RSA"); // creating a key factory object
  3. RSAPublicKeySpec publ = factory.getKeySpec(Pairs.getPublic(),RSAPublicKeySpec.class); // Creat a RSAPublicKeySpec object that allows us to translate between keys and there specification
  4. RSAPrivateKeySpec priv = factory.getKeySpec(Pairs.getPrivate(),RSAPrivateKeySpec.class); // Creat a RSAPublicKeySpec object that allows us to translate between keys and there specification
  5. try{
  6. FileSave("public.key", publ.getModulus(),publ.getPublicExponent()); // Saving the Exponent and Modulus to file public.key
  7. FileSave("private.key", priv.getModulus(),priv.getPrivateExponent()); // Saving the Exponent and Modulus to file private.key
  8. }catch(IOException e){
  9. // need to handle this error at some point
  10. }
  11. }
  12. public void FileSave(String fileName, BigInteger mod, BigInteger exp) throws IOException{
  13. ObjectOutputStream out = null;
  14. try{
  15. out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
  16. out.writeObject(mod);
  17. out.writeObject(exp);
  18. }catch(IOException e){
  19. // need to handle this error at some point
  20. }
  21. }
idfiyjo8

idfiyjo81#

多亏了你们的帮助,我终于发明了一种新的算法,目前看来它还可以工作。我会在下面链接让我知道你的想法,并提前为变量名道歉,我正在努力。

  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package oserver;
  7. import java.io.BufferedInputStream;
  8. import java.io.BufferedOutputStream;
  9. import java.security.Key;
  10. import java.security.KeyFactory;
  11. import java.security.KeyPair;
  12. import java.security.KeyPairGenerator;
  13. import java.security.NoSuchAlgorithmException;
  14. import java.security.spec.InvalidKeySpecException;
  15. import java.security.spec.RSAPublicKeySpec;
  16. import java.io.File;
  17. import java.io.FileOutputStream;
  18. import java.io.FileWriter;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.ObjectInputStream;
  22. import java.io.ObjectOutputStream;
  23. import java.math.BigInteger;
  24. import java.security.InvalidKeyException;
  25. import java.security.PrivateKey;
  26. import java.security.PublicKey;
  27. import java.security.spec.PKCS8EncodedKeySpec;
  28. import java.security.spec.RSAPrivateKeySpec;
  29. import java.security.spec.X509EncodedKeySpec;
  30. import java.util.Base64;
  31. import javax.crypto.BadPaddingException;
  32. import javax.crypto.Cipher;
  33. import javax.crypto.IllegalBlockSizeException;
  34. import javax.crypto.NoSuchPaddingException;
  35. /**
  36. *
  37. * @author sgmud
  38. */
  39. public class Encryption {
  40. public static PrivateKey privateKey;
  41. public static PublicKey publicKey;
  42. public void KeyGeneration() throws NoSuchAlgorithmException{
  43. KeyPairGenerator Generator = KeyPairGenerator.getInstance("RSA"); // Creat the Generator object with RSA
  44. Generator.initialize(1024); // Set the generator to make the 2048 bit key
  45. KeyPair Pair = Generator.genKeyPair(); // Generate the key pair
  46. publicKey = Pair.getPublic(); // Set the Public Key
  47. privateKey = Pair.getPrivate(); // Set the private Key
  48. System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
  49. System.out.println(Base64.getEncoder().encodeToString(privateKey.getEncoded()));
  50. }
  51. public void writeToFile(String filePath, byte[] key) throws IOException{
  52. File fileToWriteto = new File(filePath);
  53. fileToWriteto.getParentFile().mkdirs();
  54. FileOutputStream FoutputStream = new FileOutputStream(fileToWriteto);
  55. FoutputStream.write(key);
  56. FoutputStream.flush();
  57. FoutputStream.close();
  58. }
  59. public static PublicKey getPublicKey(String base64PublicKey){
  60. PublicKey publicKey = null;
  61. try{
  62. X509EncodedKeySpec KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes()));
  63. KeyFactory Keyfact = KeyFactory.getInstance("RSA");
  64. publicKey = Keyfact.generatePublic(KeySpec);
  65. return publicKey;
  66. } catch (NoSuchAlgorithmException e) {
  67. e.printStackTrace();
  68. } catch (InvalidKeySpecException e) {
  69. e.printStackTrace();
  70. }
  71. return publicKey;
  72. }
  73. public byte[] Encrypt(String data, String publicKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException, BadPaddingException, IllegalBlockSizeException{
  74. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  75. cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));
  76. return cipher.doFinal(data.getBytes());
  77. }
  78. public static PrivateKey getPrivateKey(String base64PrivateKey){
  79. PrivateKey privateKey = null;
  80. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.getBytes()));
  81. KeyFactory Kfact = null;
  82. try{
  83. Kfact = Kfact.getInstance("RSA");
  84. } catch (NoSuchAlgorithmException e) {
  85. e.printStackTrace();
  86. }
  87. try{
  88. privateKey = Kfact.generatePrivate(keySpec);
  89. }catch(InvalidKeySpecException e){
  90. e.printStackTrace();
  91. }
  92. return privateKey;
  93. }
  94. public static String decrypt(byte[] data, PrivateKey privateKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException, BadPaddingException, IllegalBlockSizeException{
  95. Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  96. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  97. return new String(cipher.doFinal(data));
  98. }
  99. public static String Decrypt(String data, String base64PrivateKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException, BadPaddingException, IllegalBlockSizeException{
  100. return decrypt(Base64.getDecoder().decode(data.getBytes()), getPrivateKey(base64PrivateKey));
  101. }
  102. }
展开查看全部
mf98qq94

mf98qq942#

直接的问题是您正在写入文件并从资源中读取。资源是一个只读文件,包含在java源文件中(例如gui应用程序中的图标)。
您应该使用 key.getEncoded() 相反。然后您可以使用相同的密钥工厂,但是 X509EncodedKeySpec 读回公钥 PKCS8EncodedKeySpec 私钥。
请注意,您当前正在为私钥编写模数和私钥指数。在实践中,还编写了中国剩余定理(crt)参数,这些参数可以用来加速rsa私钥运算。

相关问题