【问题标题】:RSA Encryption/Decryption using JAVA使用 JAVA 进行 RSA 加密/解密
【发布时间】:2020-06-03 18:31:47
【问题描述】:

我正在做一个这样的简单程序:

package rsaexample;

import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class RSAExample {

    private static final String PUBLIC_KEY_FILE = "Public.key";
    private static final String PRIVATE_KEY_FILE = "Private.key";

    public static void main(String[] args) throws IOException {

        try {
            System.out.println("-------Generate public and private key------");
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            System.out.println("\n-------Pulling out parameters------\n");
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec (publicKey, RSAPublicKeySpec.class);
            RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec (privateKey, RSAPrivateKeySpec.class);

            System.out.println("\n---saving keys---\n");
            RSAExample rsaObj = new RSAExample ();
            rsaObj.saveKeys(PUBLIC_KEY_FILE, rsaPubKeySpec.getModulus(), rsaPubKeySpec.getPublicExponent());
            rsaObj.saveKeys(PRIVATE_KEY_FILE, rsaPrivKeySpec.getModulus(), rsaPrivKeySpec.getPrivateExponent());

            byte[] encryptedData = rsaObj.encryptData ("Data to Encrypt");

            rsaObj.decryptData(encryptedData);

        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            System.out.println(e);
        }
    }

    private void savekeys (String fileName, BigInteger mod, BigInteger exp) throws IOException {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;

        try {

            System.out.println("Generating" + fileName + "...");
            fos = new FileOutputStream(fileName);
            oos = new ObjectOutputStream(new BufferedOutputStream(fos));
            oos.writeObject (mod);
            oos.writeObject (exp);
            System.out.println(fileName + "generated successfully");

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (oos != null) {
                oos.close();

                if (fos != null)
                    fos.close();
            }
        }
    }
    private byte[] encryptData (String data) throws IOException {
        System.out.println("\n---ENC STARTED---");
        System.out.println("Data Before Encryption :" + data);
        byte[] dataToEncrypt = data.getBytes();
        byte[] encryptedData = null;

        try {
            PublicKey pubKey = readPublicKeyFromFile(this.PUBLIC_KEY_FILE);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            encryptedData = cipher.doFinal(dataToEncrypt);
            System.out.println("Encrypted Data : " + encryptedData);

        } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }

        System.out.println("---enc complete--");
        return encryptedData;
    }

    private void decryptData (byte[] data) throws IOException {
        System.out.println("\n---DEC STARTED---");
        byte[] decryptedData = null;

        try {
            PrivateKey privateKey = readPrivateKeyFromFile (this.PRIVATE_KEY_FILE);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            decryptedData = cipher.doFinal(data);
            System.out.println("DECRYPTED DATA : " + new String(decryptedData));

        } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }

        System.out.println("---dec complete--");
    }
    public PrivateKey readPrivateKeyFromFile(String fileName) throws IOException {
        FileInputStream fis = null;
        ObjectInputStream ois = null;

        try {
            fis = new FileInputStream(new File(fileName));
            ois = new ObjectInputStream (fis);
            BigInteger modulus = (BigInteger) ois.readObject();
            BigInteger exponent = (BigInteger) ois.readObject();

            RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec (modulus, exponent);
            KeyFactory fact = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);
            return privateKey;
        }

        catch (IOException | ClassNotFoundException | NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();

        } finally {
            if (ois != null) {
                ois.close();

                if (fis != null)
                    fis.close();
            }

        }
    }

}

但它不起作用。输出应该是:

【问题讨论】:

  • 它适用于我,一旦我修正了所有的错别字并添加了缺失的方法。您的代码显然加密了一个不同的字符串,所以我不明白为什么您的示例输出没有那个字符串。你甚至没有给出一点线索来解释你为什么认为 ...它不起作用...
  • 感谢您的回答。我是 Java 新手,只想实现一个 Java 代码,用 RSA 加密和解密文件中的文本。我从:youtube.com/watch?v=uMOq4-s7Ivg 获得此代码。我修正了所有的错别字,还添加了缺失的方法,但输出仍然是:i.stack.imgur.com/EO8uL.png
  • 您正在编写“加密和解密文件中的文本” - 上面的代码是一个简单的示例,如何使用 RSA 加密字符串(“要加密的数据”(不是文件中的字符串))。加密方法在这里调用:"rsaObj.encryptData("Data to Encrypt");"

标签: java algorithm cryptography rsa


【解决方案1】:

首先,你的方法 savekeys 被称为 savekeys 小写,所以它会在你调用 rsaObj.saveKeys 的地方出现编译错误。 您正在调用一个名为 readPublicKeyFromFile 的方法,但您没有该方法的实现。

这应该可以解决问题。

private PublicKey readPublicKeyFromFile(String fileName) throws IOException
{
     FileInputStream fis = null;
     ObjectInputStream ois = null;

     try {
         fis = new FileInputStream(new File(fileName));
         ois = new ObjectInputStream (fis);
         BigInteger modulus = (BigInteger) ois.readObject();
         BigInteger exponent = (BigInteger) ois.readObject();

         RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec (modulus, exponent);
         KeyFactory fact = KeyFactory.getInstance("RSA");
         PublicKey privateKey = fact.generatePublic(rsaPublicKeySpec);
         return privateKey;
     }

     catch (IOException | ClassNotFoundException | NoSuchAlgorithmException | InvalidKeySpecException e) {
         e.printStackTrace();

     } finally {
         if (ois != null) {
                ois.close();
             if (fis != null)
                    fis.close();
         }

     }
    return null;
}

【讨论】:

  • 非常感谢。我已经更改了它并添加了您编写的方法,但输出仍然是这样:i.stack.imgur.com/EO8uL.png.
  • 你是如何运行代码的。你在使用eclipse IDE吗?尝试只需单击代码上的任意位置,然后单击 run as -> java application。
  • 看起来您使用的是 Netbeans,而不是选择“Java 应用程序”,而是使用了“Java 类”。也许这个视频可以帮助你解决这个问题(你不需要构建完整的表单:-):youtube.com/watch?v=htdxODp534I
猜你喜欢
  • 2013-11-06
  • 1970-01-01
  • 2010-11-17
  • 1970-01-01
  • 2017-07-02
  • 2017-06-25
  • 2014-12-13
  • 2012-04-07
  • 2014-06-02
相关资源
最近更新 更多