2

I want to encrypt the message with signed private key.and verify the signature but getting error in verify signature

//importing the crt and key into p12 file and importing into jks file

openssl pkcs12 -export -in D:\cedge_uat\STAR_cedgenetbanking_in.crt -inkey D:\cedge_uat\newcedgenetbanking251920.key -name cedge1 -out D:\cedge_uat\convertedfile1.p12

keytool -importkeystore -deststorepass cedge1 -destkeystore newkeystore.jks -srckeystore D:\cedge_uat\convertedfile1.p12 -srcstoretype PKCS12

 public static PrivateKey generatePrivateKey() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, UnrecoverableKeyException{
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                //Jks file path 
            FileInputStream fis;
            PrivateKey privateKey = null;
            try {
                fis = new FileInputStream("C:/Program Files/Java/jre1.8.0_171/bin/keystore12.jks");
                keyStore.load(fis, "changeit".toCharArray());
                //jks file password 
                 privateKey = (PrivateKey) keyStore.getKey("changeit", "changeit".toCharArray());
                System.out.println("privateKey--"+privateKey);
            } catch (FileNotFoundException e) {
                System.out.println("e--"+e);
                    e.printStackTrace();
            }
            return privateKey;
    }
        
    public static String signature(String sessionkey, PrivateKey privatekey) throws Exception 
    {
            Signature sign = Signature.getInstance("SHA256withRSA");
            sign.initSign(privatekey);
            sign.update(sessionkey.getBytes());
            return new String(Base64.getEncoder().encodeToString(sign.sign()));
    }


 public static PublicKey generatePublicKey() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, UnrecoverableKeyException{
            KeyStore keyStore = KeyStore.getInstance("JKS");
            FileInputStream fis;
            PublicKey publicKey=null;
            try {
                fis = new FileInputStream("C:/Program Files/Java/jre1.8.0_171/bin/newkeystore.jks");
                
                keyStore.load(fis, "cedge1".toCharArray());
                Certificate cert = keyStore.getCertificate("cedge1");
                 publicKey = cert.getPublicKey(); 
            } catch (FileNotFoundException e) {
                System.out.println("e--"+e);
                    e.printStackTrace();
            }
            return publicKey;
    }
    //Signature verification using their public key
    public static boolean verifySignature(String input, String signature, PublicKey publicKey) throws Exception
    {
            Signature verifySig = Signature.getInstance("SHA256withRSA");
            verifySig.initVerify(publicKey);
            byte[] singedData = Base64.getDecoder().decode(signature);
            verifySig.update(Base64.getDecoder().decode(input));
            boolean isVerified = verifySig.verify(singedData);
            System.out.println("isVerified "+ isVerified);
            return isVerified;
    }

Getting below response:

privateKey--sun.security.rsa.RSAPrivateCrtKeyImpl@ffe594cb privateKey=sun.security.rsa.RSAPrivateCrtKeyImpl@ffe594cb Signature=QtFcvROXmFb+SIqi/sFG5BXtMviidqWYP0ae/Z0PQNKbxYg9LiJMAqjU+XB+V7awkpVpeV8/TmrxO2AFi1hDLOOOdL4rVY1xxPTGw77Q==

publicKey=Sun RSA public key, 2048 bits modulus: 2170304779081185713374867545321744099657549785541087943424133659953554520622568213352873219823464920874049569111847413669517192082390131 public exponent: 65537 Exception in thread "main" java.lang.IllegalArgumentException: Last unit does not have enough valid bits at java.util.Base64$Decoder.decode0(Unknown Source)

  public static void main(String[] args) throws Exception 
    {
        //generatePrivateKey();
        PrivateKey privateKey=generatePrivateKey();
        System.out.println("privateKey="+privateKey);
        String signature = signature("hello",privateKey);
        System.out.println("Signature="+signature);
        
        //generatePublicKey();
        PublicKey publicKey=generatePublicKey();
        System.out.println("publicKey="+publicKey);
        System.out.println("verify="+ verifySignature("hello",signature,publicKey));
            
    }
Felipe Augusto
  • 7,733
  • 10
  • 39
  • 73
prathibha.
  • 31
  • 1
  • 6
  • You are trying to load a private key with alias "changeit", the first parameter to getKey(). That is probably not the alias of the key. – Gimby Sep 23 '20 at 10:38
  • @Gimby im not able to understand, can you explain pls. at which place i have to change – prathibha. Sep 23 '20 at 10:54
  • If you don't understand that, then you know almost nothing about public/private key encryption (or signing...). You will have to take the time to learn. – Gimby Sep 23 '20 at 10:59
  • I want to signing the mssage with private key. I have the private key start with -----BEGIN RSA PRIVATE KEY----- . from this file how to fetch the private key. I dont have much idea ,thats why imported into keystore and trying to fetch – prathibha. Sep 23 '20 at 11:08
  • 1
    Use `keytool -list -keystore file.jks [-storepass changeit]` to find out the alias(es) in the keystore, and use the correct one. If you created the pkcs12 with `openssl pkcs12 -export` and didn't specify `-name`, then the (only) alias is actually `1` i.e. the digit one(!) – dave_thompson_085 Sep 23 '20 at 11:11
  • openssl pkcs12 -export -in D:\cedge_uat\STAR_cedgenetbanking_in.crt -inkey D:\cedge_uat\newcedgenetbanking251920.key -name alias -out D:\cedge_uat\convertedfile.p12 keytool -importkeystore -deststorepass cedge1 -destkeystore keystore123.jks -srckeystore D:\cedge_uat\convertedfile.p12 -srcstoretype PKCS12 – prathibha. Sep 23 '20 at 11:49
  • now I have run the above these commands and given password as cedge1 , and mentioning the "cedge1" in coding all places but getting null as private key – prathibha. Sep 23 '20 at 11:50
  • As now im getting the private key and siganature but while verifiying the signature getting errors as java.lang.IllegalArgumentException: Last unit does not have enough valid bits – prathibha. Sep 23 '20 at 13:04
  • @dave_thompson_085 I have edited my answer ,can you check now. getting error in verify signature.. Im not sure whether generated signature using private key is correct or not – prathibha. Sep 23 '20 at 13:09
  • Your signature string is 106 chars, which is not a mutliple; standard base64 is always a multiiple of 4 chars.That's why you are getting an exception from Base64$Decoder. The code you posted couldn't do this, so I don't know what you actually did, but base64 of a 2048-bit RSA signature will always be 342 chars (exactly). I notice you are using different filenames for the privatekey and publickey (cert), and neither is the one shown in your `keytool -importkeystore` command; if you use files that don't actually contain the same keypair this won't work. ... – dave_thompson_085 Sep 24 '20 at 05:06
  • ... Finally, on modern Windows (since at least 8, maybe 7) it's a bad idea to manually write or modify files anywhere under `\Program Files` or `\Program Files (x86)`. MS has recommended against this since last century, but because many viruses and malware do this, recent Windows and various AV have gotten more aggressive about preventing or disabling such writes, meaning that you might think you have stored data there but you haven't really. Since Java installs there by default, either you should put your files somewhere other than 'java.home' or you should install Java somewhere else. ... – dave_thompson_085 Sep 24 '20 at 05:10
  • ... The d\cedge_uat you show in your _commands_ looks like a reasonable location to use, but there are almost certainly many other possibilities. – dave_thompson_085 Sep 24 '20 at 05:12
  • @dave_thompson_085 for testing purpose i have saved there,later i will move to project location. now im getting successful verify signature,error with this line verifySig.update(Base64.getDecoder().decode(input)) changed into verifySig.update(input.getbytes()); – prathibha. Sep 24 '20 at 05:59

0 Answers0