package org.openslx.satellitedaemon.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyPair; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.security.cert.CertificateException; // TODO: More general naming; this isn't really limited to serverids... // Might also be worth moving this encrypt/decrypt stuff from satserver and masterserver to the shared project (one class doing both) public class EncryptWithServerIdPublicKey { KeyPair pair; public EncryptWithServerIdPublicKey(String alias, String password, String file) throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyStoreException, UnrecoverableKeyException { KeyStore keystore = KeyStore.getInstance("JKS"); keystore.load(new FileInputStream(new File(file)), password.toCharArray()); Certificate cert = null; Key key = keystore.getKey(alias, password.toCharArray()); if (key instanceof PrivateKey) { cert = keystore.getCertificate(alias); PublicKey publicKey = cert.getPublicKey(); pair = new KeyPair(publicKey, (PrivateKey) key); } } public byte[] encryptString(String message) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { Signature signature = Signature.getInstance("SHA256WITHRSA"); signature.initSign(pair.getPrivate()); signature.update(message.getBytes()); return signature.sign(); } }