簡體   English   中英

使用 JAVA 進行 RSA 加密/解密

[英]RSA Encryption/Decryption using JAVA

我正在做一個這樣的簡單程序:

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();
            }

        }
    }

}

但它不起作用。 output 應該是:

在此處輸入圖像描述

首先,您的方法 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM