Created
March 20, 2014 06:09
-
-
Save nicoruti/9658183 to your computer and use it in GitHub Desktop.
Get the hash from the signature. Details can be found here: http://stackoverflow.com/questions/22506131/get-hash-of-java-security-signature-create-signature-of-given-hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.KeyPair; | |
import java.security.KeyPairGenerator; | |
import java.security.Signature; | |
import javax.crypto.Cipher; | |
public class SignatureTest { | |
public static void main(String[] args) throws Exception { | |
/** | |
* Create two keypairs and a dummy data object which we sign | |
*/ | |
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); | |
keyGen.initialize(512); | |
KeyPair keyPair1 = keyGen.generateKeyPair(); | |
KeyPair keyPair2 = keyGen.generateKeyPair(); | |
String data = new String("dummy"); | |
/** | |
* Sign with keypair 1 | |
*/ | |
Signature signature = Signature.getInstance("SHA1withRSA"); | |
signature.initSign(keyPair1.getPrivate()); | |
signature.update(data.getBytes()); | |
byte[] signature1 = signature.sign(); | |
/** | |
* Decrypt signature to get hash of the object | |
*/ | |
Cipher rsa = Cipher.getInstance("RSA"); | |
rsa.init(Cipher.DECRYPT_MODE, keyPair1.getPublic()); | |
byte[] hash = rsa.doFinal(signature1); | |
/** | |
* Encrypt with keypair 2 to get the new signature | |
*/ | |
rsa = Cipher.getInstance("RSA"); | |
rsa.init(Cipher.ENCRYPT_MODE, keyPair2.getPrivate()); | |
byte[] signature2 = rsa.doFinal(hash); | |
/** | |
* Verify with another signature instance | |
*/ | |
signature = Signature.getInstance("SHA1withRSA"); | |
signature.initVerify(keyPair2.getPublic()); | |
signature.update(data.getBytes()); | |
System.out.println("Verified new key: " + signature.verify(signature2)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment