2

can someone please explain me how to sign a string or byte array using private key? PLEASE. two weeks I'm trying to achieve it. I have code:

private static byte[] createSignature(byte[] file) {
    byte[] signature = null;

    try {
        java.security.KeyStore keyStoreFile = java.security.KeyStore
                .getInstance("PKCS12");
        keyStoreFile.load(new FileInputStream("keyStore.pfx"),
                "password".toCharArray());

        // nuskaitomas privatus raktas iš failo
        PrivateKey privateKey = (PrivateKey) keyStoreFile.getKey(
                "alais", "password".toCharArray());

        Signature dsa = Signature.getInstance(SHA1withRSA);
        dsa.initSign(privateKey);
        dsa.update(file, 0, file.length);
        signature = dsa.sign();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return signature;
}

but this is just a signature. .

Marcus
  • 12,296
  • 5
  • 48
  • 66
innspiron
  • 163
  • 1
  • 3
  • 12
  • 1
    That code will give you the signature. You should be able to verify it using the public key. What else do you need? – Thilo Dec 16 '11 at 07:42
  • what do you mean by "but this is just a signature"? your code seems to be doing what you have asked for. please make yourself clearer if you mean something else – Neal Dec 16 '11 at 07:49
  • thank to all. I have to post two variables: 1.signed data (string) using private key and 2.signature. I do not understand the difference then. Which is which? – innspiron Dec 16 '11 at 08:12

2 Answers2

0

Change return signature; for this instead:

byte[] encryptedByteValue = Base64.encodeBase64(signature);
return new String(encryptedByteValue, "UTF-8");
Maroun
  • 94,125
  • 30
  • 188
  • 241
0

With your code example you generate the signature of the input data.

If you want to return also the data in an encrypted form, you can use asymmetric (or symmetric) encryption.

In your case, you can return the data encrypted with your PrivateKey: you can find an example here.

marcogramy
  • 586
  • 5
  • 8