使用JAVA中的公共和私有RSA密钥进行加密和解密

时间:2015-06-22 09:43:24

标签: java java-ee encryption cryptography rsa

我正在尝试使用RSA密钥在JAVA中使用非对称密钥进行简单的加密/解密,我遇到了一些麻烦。这是我的代码:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;

public class AsymmetricCipherTestFiles 
{
    public static void main(String[] unused) throws Exception 
    {
        // 1. Generating keys
        System.out.println("Generating keys ...");
        PublicKey publicKey;
        PrivateKey privateKey;
        // generateKeys(512);

        // 2. read them from file
        System.out.println("Read from file");
        publicKey = readPublicKeyFromFile("public.key");
        privateKey = readPrivateKeyFromFileTest("private.key");

        System.exit(0);

        // 3. encrypt data
        System.out.println("Encrypt data");
        byte[] dataBytes = "some string to encrypt".getBytes();
        byte[] encBytes = encrypt(dataBytes, publicKey, "RSA");
        printByteArray(encBytes);

        // 4. decrypt data
        byte[] decBytes = decrypt(encBytes, privateKey, "RSA");
        printByteArray(decBytes);
        // String decryptedThing = convert(decBytes);

    }

    public static void generateKeys(int keySize) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException 
    {
        // Create key
        // System.out.println("Generating keys");
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(keySize);
        KeyPair kp = kpg.genKeyPair();

        /*
        Key publicKey = kp.getPublic();
        Key privateKey = kp.getPrivate();
        */

        KeyFactory fact = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),RSAPublicKeySpec.class);
        RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),RSAPrivateKeySpec.class);

        saveKeyToFile("bin/public.key", pub.getModulus(), pub.getPublicExponent());
        saveKeyToFile("bin/private.key", priv.getModulus(),priv.getPrivateExponent());

        // System.out.println("Keys generated");
    }

    private static byte[] encrypt(byte[] inpBytes, PublicKey key,String xform) throws Exception 
    {
        Cipher cipher = Cipher.getInstance(xform);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(inpBytes);
    }

    private static byte[] decrypt(byte[] inpBytes, PrivateKey key,String xform) throws Exception 
    {
        Cipher cipher = Cipher.getInstance(xform);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(inpBytes);
    }

    public static String convert(byte[] data) 
    {
        StringBuilder sb = new StringBuilder(data.length);
        for (int i = 0; i < data.length; ++ i) 
        {
            if (data[i] < 0) throw new IllegalArgumentException();
            sb.append((char) data[i]);
        }
        return sb.toString();
    }

    public static PublicKey readPublicKeyFromFile(String keyFileName) throws IOException 
    {
        InputStream in = (InputStream) AsymmetricCipherTestFiles.class.getResourceAsStream(keyFileName);
        ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream( in ));
        try 
        {
            BigInteger m = (BigInteger) oin.readObject();
            BigInteger e = (BigInteger) oin.readObject();
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
            KeyFactory fact = KeyFactory.getInstance("RSA");
            PublicKey pubKey = fact.generatePublic(keySpec);
            return pubKey;
        } 
        catch (Exception e) 
        {
            throw new RuntimeException("Spurious serialisation error", e);
        } finally {
            oin.close();
        }
    }

    public static PrivateKey readPrivateKeyFromFile(String keyFileName) throws IOException 
    {
        InputStream in = (InputStream) AsymmetricCipherTestFiles.class.getResourceAsStream(keyFileName);
        ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream( in ));
        try 
        {
            BigInteger m = (BigInteger) oin.readObject();
            BigInteger e = (BigInteger) oin.readObject();

            byte[] byteArray = new byte[512];
            byteArray = m.toByteArray();

            KeySpec keySpec = new PKCS8EncodedKeySpec(byteArray);
            // RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
            KeyFactory fact = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = fact.generatePrivate(keySpec);
            return privateKey;
        } 
        catch (Exception e) 
        {
            throw new RuntimeException("Spurious serialisation error", e);
        } finally {
            oin.close();
        }
    }

    public static PrivateKey readPrivateKeyFromFileTest(String filename) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException
    {
        RandomAccessFile raf = new RandomAccessFile(filename, "r");
        byte[] buf = new byte[(int)raf.length()];
        raf.readFully(buf);
        raf.close();
        PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(buf);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey privKey = kf.generatePrivate(kspec);

        return privKey;
    }

    public static void saveKeyToFile(String fileName,BigInteger mod, BigInteger exp) throws IOException 
    {
        ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
        try 
        {
            oout.writeObject(mod);
            oout.writeObject(exp);
        } 
        catch (Exception e) 
        {
            throw new IOException("Unexpected error", e);
        } 
        finally 
        {
            oout.close();
        }
    }

    public static void printByteArray(byte[] byteArray)
    {
        int increment = 0;
        for(byte b : byteArray)
        {
            System.out.println("B["+increment+"] = "+b);
            increment++;
        }
    }
}

当我运行它时,它给了我这个错误:

Generating keys ...
Read from file
Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DerInputStream.getLength(): lengthTag=109, too big.
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(Unknown Source)
    at java.security.KeyFactory.generatePrivate(Unknown Source)
    at AsymmetricCipherTestFiles.readPrivateKeyFromFileTest(AsymmetricCipherTestFiles.java:160)
    at AsymmetricCipherTestFiles.main(AsymmetricCipherTestFiles.java:40)
Caused by: java.security.InvalidKeyException: IOException : DerInputStream.getLength(): lengthTag=109, too big.
    at sun.security.pkcs.PKCS8Key.decode(Unknown Source)
    at sun.security.pkcs.PKCS8Key.decode(Unknown Source)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(Unknown Source)
    at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(Unknown Source)
    at sun.security.rsa.RSAKeyFactory.generatePrivate(Unknown Source)
    ... 4 more

生成/阅读/加密 公钥一切顺利,读取私钥并尝试时出错把它变成PrivateKey对象。

我做错了什么以及如何解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:2)

您要通过两次writeObject()来电保存该密钥,但只需通过一次readFully()次呼叫即可恢复该密钥。你需要:

  • 使用write(byte[])保存密钥,提供getEncoded()的结果,并使用readFully(),
  • 使用writeObject()保存并使用readObject().
  • 进行阅读

不是两者的混合物。