package org.openslx.imagemaster.util; import java.io.FileNotFoundException; import java.io.IOException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.spec.X509EncodedKeySpec; import org.openslx.imagemaster.db.DbSatellite; public class AsymMessageVerifier { private PublicKey key; /** * Load the key * @param organization the organization to verify * @throws Exception * @throws NoSuchAlgorithmException * @throws CertificateException * @throws FileNotFoundException * @throws IOException * @throws KeyStoreException * @throws UnrecoverableKeyException */ public AsymMessageVerifier(String organization) throws Exception { byte[] b = DbSatellite.getKeyfromOrganization( organization ); if (b == null) throw new Exception("Organization not found."); KeyFactory kf = KeyFactory.getInstance( "RSA" ); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(b); key = kf.generatePublic(keySpec); } /** * Verify an encrypted message. * * @param messageDigest The signed message from hs/uni server * @param expectedCleartext The message that was sent before * @return Whether the message could be verfied or not * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws SignatureException * @throws UnrecoverableKeyException * @throws KeyStoreException */ public boolean verifyMessage( byte[] messageDigest, byte[] expectedCleartext ) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnrecoverableKeyException, KeyStoreException { // verify message Signature signature = Signature.getInstance( "SHA256WITHRSA" ); signature.initVerify( key ); signature.update( expectedCleartext ); return signature.verify( messageDigest ); } }