Java Programming Security Question

JC724

Weaksauce
Joined
Jan 20, 2016
Messages
118
I am trying to learn how to use Java to do some security stuff. I am taking a security class and I was told I can do some of these things in Java.

1st Question is based around RSA.

I was looking at some youtube videos about how to encrypt and decrypt using RSA Java algorithm

Code:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();

If I don't want to use a KeyPairGenerator, how do I go about creating a public and private key. Like if I wanted to make my own and not use KeyPairGenerator? Like can I just use KeyPair and create my own hard coded public and private key??

My professor told me if I gave you a certificate, you should be able to get the public key from that. So I him to give me one so I can try and I realize I don't really know what to do lol. I have it but it is encoded, when I open it up in notepad ++.

So my question is do I need to install it and after that do I read in the file line by line to get the public key?

I have been looking for youtube videos online that show me how to use Java to verify a certificate. Like show me how to print it out and get the public key?

Does anybody have any good tutorials on how to do this with Java?
 

modi123

Supreme [H]ardness
Joined
Sep 6, 2006
Messages
6,699
You would want to use Keypairgenerator.. barring that you would either have to use a third party software package or write your own, and the latter being strongly advised against.

So I him to give me one so I can try and I realize I don't really know what to do lol.
What?

If he gave you the key file the gist is you read it into a byte array, dump the byte array into PKCS8EncodedKeySpec, and use that.

Some reading:

http://www.novixys.com/blog/rsa-file-encryption-decryption-java/
https://www.javacodegeeks.com/2017/...public-private-key-asymmetric-encryption.html
https://gist.github.com/liudong/3993726
http://www.novixys.com/blog/encrypt-sign-file-using-rsa-java/
 

JC724

Weaksauce
Joined
Jan 20, 2016
Messages
118
You would want to use Keypairgenerator.. barring that you would either have to use a third party software package or write your own, and the latter being strongly advised against.


What?

If he gave you the key file the gist is you read it into a byte array, dump the byte array into PKCS8EncodedKeySpec, and use that.

Some reading:

http://www.novixys.com/blog/rsa-file-encryption-decryption-java/
https://www.javacodegeeks.com/2017/...public-private-key-asymmetric-encryption.html
https://gist.github.com/liudong/3993726
http://www.novixys.com/blog/encrypt-sign-file-using-rsa-java/


Ok thanks this is helpful. This is my first security class and I have been to get most things working. For some reason I am struggling with the Pub/Priv Key stuff.

So he gave me a public certificate file with extension .cer and a private key file with extension .pfx.

So Do I need to install this certificates or anything? He told me I should be able to get the public and private key from this two files. And in the real world I can use that to print and like verify the keys and certificates and encrypt/decrypt files.

So from reading the http://www.novixys.com/blog/how-to-generate-rsa-keys-java/(sections 3.1 and 3.2)

Would I use this code to get the private key? Where the key file is simple the file path to the private key file on my PC?

Code:
/* Read all bytes from the private key file */ Path path = Paths.get(keyFile); byte[] bytes = Files.readAllBytes(path); /* Generate private key. */ PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey pvt = kf.generatePrivate(ks);

And can I basically do the same thing using this code below to get the key from the public certificate file

Code:
/* Read all the public key bytes */ Path path = Paths.get(keyFile); byte[] bytes = Files.readAllBytes(path); /* Generate public key. */ X509EncodedKeySpec ks = new X509EncodedKeySpec(bytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey pub = kf.generatePublic(ks);
 

JC724

Weaksauce
Joined
Jan 20, 2016
Messages
118
So I am trying to print the private key. I keep getting errors when I try to do system.out.println.

Any ideas what I am doing wrong in either test case??

Code:
public static void main(String[] args) throws KeyStoreException, FileNotFoundException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException, InvalidKeySpecException {
        // Trying to print the private key from a file with private key in it Raghupri.pfx.
        //I tried two test cases, one using keyStore and the either using Keyfactory and PrivateKey
       
        //test case 1 for getting private key
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
       
        char[] keyStorePassword = "raghu".toCharArray();
        try(InputStream keyStoreData = new FileInputStream("C:\\Users\\username\\Desktop\\certificate\\certificate\\Raghupri.pfx")){
            keyStore.load(keyStoreData, keyStorePassword);
        }
       
        KeyStore.ProtectionParameter entryPassword =
                new KeyStore.PasswordProtection(keyStorePassword);
       
        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)
                keyStore.getEntry("keyAlias", entryPassword);
       
    //    System.out.println("Private key is " + privateKeyEntry.getPrivateKey());    //NOT WORKING
       
        //test case two for getting private key
        /* Read all bytes from the private key file */
        Path path = Paths.get("C:\\Users\\username\\Desktop\\certificate\\certificate\\Raghupri.pfx");
        byte[] bytes = Files.readAllBytes(path);

        /* Generate private key. */
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey pvt = kf.generatePrivate(ks);
       
        Base64.Encoder encoder = Base64.getEncoder();
       
    //    System.out.println("Private key is " + encoder.encodeToString(pvt.getEncoded()));    //NOT WORKING
    }
 

modi123

Supreme [H]ardness
Joined
Sep 6, 2006
Messages
6,699
What errors?
Why would you be printing the private key file?

So Do I need to install this certificates or anything?
I mean I guess you could, but I would imagine you would just use them as files to encrypt with the public and decrypt with the private.
 

JC724

Weaksauce
Joined
Jan 20, 2016
Messages
118
What errors?
Why would you be printing the private key file?


I mean I guess you could, but I would imagine you would just use them as files to encrypt with the public and decrypt with the private.


Here are the errors I am getting.

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : version mismatch: (supported: 00, parsed: 03
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(Unknown Source)
at java.security.KeyFactory.generatePrivate(Unknown Source)
at keyStorePractice.main(keyStorePractice.java:52)
Caused by: java.security.InvalidKeyException: IOException : version mismatch: (supported: 00, parsed: 03
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)
... 3 more

I want to print the certificate and the private and public key. I feel like I should be able to do that lol
 

Tawnos

2[H]4U
Joined
Sep 9, 2001
Messages
3,808
A .pfx file is a PKCS12 archive that can contain multiple keys. It has to be loaded and handled differently than a PKCS8 text file: https://en.wikipedia.org/wiki/PKCS_12


First case:

Code:
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
     
       char[] keyStorePassword = "raghu".toCharArray();
       try(InputStream keyStoreData = new FileInputStream("C:\\Users\\username\\Desktop\\certificate\\certificate\\Raghupri.pfx")){
           keyStore.load(keyStoreData, keyStorePassword);
       }
     
       KeyStore.ProtectionParameter entryPassword =
               new KeyStore.PasswordProtection(keyStorePassword);
     
       KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry)
               keyStore.getEntry("keyAlias", entryPassword);


You may need to explicitly say that you want the "pkcs12" keystore or even use a library like BouncyCastle on some versions of Java, but I'd start by checking that you're using the right alias for the key using keyStore.aliases()


Second case:

Code:
       //test case two for getting private key
       /* Read all bytes from the private key file */
       Path path = Paths.get("C:\\Users\\username\\Desktop\\certificate\\certificate\\Raghupri.pfx");
       byte[] bytes = Files.readAllBytes(path);

       /* Generate private key. */
       PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes);
You're trying to load the file as PKCS8 file. Try converting it with openssl: openssl pkcs12 -in YourCertName.pfx -nocerts -nodes -out NewName.pem then load the resulting pem file.
 
Top