pernacentus
07-06-2010, 19:38
Salve a tutti, è il mio primo post in questa sezione. Per un progetto universitario devo implementare l'algoritmo di firma RSA. Il codice è il seguente:
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKeySpec ks =(RSAPrivateKeySpec)kf.getKeySpec(priv,RSAPrivateKeySpec.class);
BigInteger exponent = ks.getPrivateExponent();
BigInteger modulus = ks.getModulus();
byte[] messaggio = new String("Ciao").getBytes("UTF8");
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(messaggio);
byte[] hashBytes = digest.digest();
BigInteger hash = new BigInteger(hashBytes);
BigInteger signature = hash.modPow(exponent, modulus);
byte[] signatureBytes = signature.toByteArray();
Signature sig = Signature.getInstance("MD5WithRSA");
sig.initVerify(pub);
sig.update(messaggio);
boolean verified = false;
try{
verified = sig.verify(signatureBytes);
}
catch (SignatureException se){
System.out.println("La firma non ha un formato valido!");
}
if(verified)
System.out.println("Documento autentico");
else
System.out.println("Documento falso");
Come potete vedere, per prima cosa vado a fare l'hash con MD5 del messaggio, quindi con l'esponente ed il modulo ricavati dalla chiave privata eseguo la trasformazione RSA dell'hash. Quando però vado a verificare la firma utilizzando la classe Signature di Java, mi viene stampato a video Documento falso. C'è qualche buon'anima che sa spiegarmi il perchè?
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKeySpec ks =(RSAPrivateKeySpec)kf.getKeySpec(priv,RSAPrivateKeySpec.class);
BigInteger exponent = ks.getPrivateExponent();
BigInteger modulus = ks.getModulus();
byte[] messaggio = new String("Ciao").getBytes("UTF8");
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(messaggio);
byte[] hashBytes = digest.digest();
BigInteger hash = new BigInteger(hashBytes);
BigInteger signature = hash.modPow(exponent, modulus);
byte[] signatureBytes = signature.toByteArray();
Signature sig = Signature.getInstance("MD5WithRSA");
sig.initVerify(pub);
sig.update(messaggio);
boolean verified = false;
try{
verified = sig.verify(signatureBytes);
}
catch (SignatureException se){
System.out.println("La firma non ha un formato valido!");
}
if(verified)
System.out.println("Documento autentico");
else
System.out.println("Documento falso");
Come potete vedere, per prima cosa vado a fare l'hash con MD5 del messaggio, quindi con l'esponente ed il modulo ricavati dalla chiave privata eseguo la trasformazione RSA dell'hash. Quando però vado a verificare la firma utilizzando la classe Signature di Java, mi viene stampato a video Documento falso. C'è qualche buon'anima che sa spiegarmi il perchè?