使用JKS文件中的私钥解密密钥

时间:2017-06-14 14:03:02

标签: java encryption public-key-encryption private-key

所以我在keytool中生成了一个密钥对,生成了一个对称密钥,并使用对称密钥加密了一个String,然后加密了对称密钥。现在我必须解密对称密钥,我遇到了一些麻烦。我用于解密的代码并没有丢弃任何错误,但它实际上并没有做任何事情,我不确定我做错了什么。

    package ReadFileExample;


    import java.io.BufferedOutputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.ObjectOutputStream;
    import java.security.Key;
    import java.security.KeyException;
    import java.security.KeyPair;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.UnrecoverableKeyException;
    import java.security.cert.CertificateFactory;
    import java.security.cert.X509Certificate;
    import java.util.Base64;

    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.security.cert.Certificate;

    import java.security.KeyStore;
    import java.security.Key;
    import java.io.FileInputStream;



    public class generatekey {


       static Cipher cipher;
       public static void main(String[] args) throws Exception {






    // generating a symmetric key using the AES algorithm
     KeyGenerator generator = KeyGenerator.getInstance("AES");
    // 128 bit key
     generator.init(128);
    //generates a secret key
     SecretKey secretkey = generator.generateKey();
    // returns an AES cipher
     cipher = Cipher.getInstance("AES");
    //print key
     System.out.println("Key: " + cipher);







     String plainText = "Hello World";
    // call to method encrypt 
     String encryptedText  = encrypt(plainText, secretkey);
    // print orignial text and encrypted text
     System.out.println("Plain Text: " + plainText);
     System.out.println("Encrypted Text: " + encryptedText);





     String publicKey = "C:/Users/girgich/public.cert";










    // allows to write data to a file
     FileOutputStream fos = null;
    // write bytes to file
     BufferedOutputStream bos = null;
    // create file to which data needs to be written
     String fileName = "C:/Users/girgich/newFile.txt";

     try{
        // allows written data to go into the written path
         fos = new FileOutputStream(fileName);
        // converts written data into bytes
         bos = new BufferedOutputStream(fos);


        // writes the encrypted text into file
         bos.write(encryptedText.getBytes());                


         System.out.println("encryptedText has been written successfully in "
                     +fileName);

        // allows to catch bug in code
     } catch (IOException e) {
        e.printStackTrace();
     } finally {
         try{
            // check for null exception
             if (bos != null){
                bos.close();

             }
            // check for null exception
             if (fos != null){
                fos.close();
             }
         } catch (IOException e){
             e.printStackTrace();

         }



     }






    // creates a file input stream by opening a path to the file needed
     FileInputStream fin = new 
                           FileInputStream("C:/Users/girgich/public.cert");
    // implements the X509 certificate type
     CertificateFactory f = CertificateFactory.getInstance("X.509");
    // initalizes data found in the file
     X509Certificate certificate = 
                    (X509Certificate)f.generateCertificate(fin);
    // gets public key from this certificate 
     PublicKey pk = certificate.getPublicKey();
     System.out.println(pk);

     String encryptedTextKey = encryptedKey(pk, secretkey);
     System.out.println("Encrypted Key: " + encryptedTextKey);


    // allows to write data to a file
     FileOutputStream newFos = null;
    // write bytes to file
     BufferedOutputStream newBos = null;
    // create file to which data needs to be written
     String fileNameKey = "C:/Users/girgich/symmetric.txt";

     try{
        // allows written data to go into the written path
         newFos = new FileOutputStream(fileNameKey);
        // converts written data into bytes
         newBos = new BufferedOutputStream(newFos);



        // writes the encrypted text into file
        newBos.write(encryptedTextKey.getBytes());                


        System.out.println("encryptedKey has been written successfully in "
                     +fileNameKey);






        // allows to catch bug in code
     } catch (IOException e) {
        e.printStackTrace();
     } finally {
         try{
            // check for null exception
             if (newBos != null){
                 newBos.close();

            }
            // check for null exception
             if (newFos != null){
                 newFos.close();
            }
         } catch (IOException e){
             e.printStackTrace();

        }
    }

     String decrypt = (encryptedTextKey);

}







 public static String encrypt(String plainText, SecretKey secretkey) throws 
  Exception {
    //Encodes the string into a sequence of bytes
    byte[] plainTextByte = plainText.getBytes();
    //intialize cipher to encryption mode
    cipher.init(Cipher.ENCRYPT_MODE, secretkey);
    //data is encrypted 
    byte[] encryptedByte = cipher.doFinal(plainTextByte);
    Base64.Encoder encoder = Base64.getEncoder();
    //encodes bytes into a string using Base64
    String encryptedText = encoder.encodeToString(encryptedByte);
    // return the string encrypted text to the main method
    return encryptedText;

}

public static String encryptedKey(PublicKey pk, SecretKey secretkey) throws Exception {
    // data written to byte array
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // writes data types to the output stream
    ObjectOutputStream writter = new ObjectOutputStream(baos);
    //specific object of secretkey is written to the output stream
    writter.writeObject(secretkey);

    //creates a byte array  
    byte[] plainTextByteKey = baos.toByteArray();

    //creates a cipher using the RSA algorithm 
    Cipher cipher = Cipher.getInstance("RSA");
    // initalizes cipher for encryption using the public key 
    cipher.init(Cipher.ENCRYPT_MODE, pk);
    //encrypts data
    byte[] encryptedByteKey = cipher.doFinal(plainTextByteKey);

    Base64.Encoder encoderKey = Base64.getEncoder();
    // encodes the byte array into a string.
    String encryptedTextKey = encoderKey.encodeToString(encryptedByteKey);
    return encryptedTextKey;

}


public void decrypt(String encryptedTextKey) {
    byte[] decryptedData = null;
    String password = "******";


    try {
        FileInputStream is = new FileInputStream("C:/Users/girgich/keystore.jks");
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(is, password.toCharArray());
        String alias = "mykey";
        Key key = keystore.getKey(alias, password.toCharArray());

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        decryptedData = cipher.doFinal(encryptedTextKey.getBytes());
        System.out.println("Decrypted Key: " + decryptedData);

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

}

0 个答案:

没有答案
相关问题