DS-Lab / src / main / java / dslab / crypto / RSA.java
RSA.java
Raw
package dslab.crypto;

import dslab.util.ComponentId;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.io.File;
import java.util.Base64;

import static dslab.util.Keys.readPrivateKey;
import static dslab.util.Keys.readPublicKey;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;

/**
 * Offers encryption and decryption of Srings via RSA
 */
public class RSA {

    private final Cipher decryptCipher;
    private final Cipher encryptCipher;

    public RSA(ComponentId componentId) {
        try {

            decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            decryptCipher.init(
                    DECRYPT_MODE,
                    readPrivateKey(new File("keys/server/" + componentId + ".der")));

            encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            encryptCipher.init(
                    ENCRYPT_MODE,
                    readPublicKey(new File("keys/client/" + componentId + "_pub.der")));

        } catch (Exception e) {
            throw new RuntimeException("Error when trying to set up RSA encryption", e);
        }
    }

    public String decrypt(String ciphertext) {
        try {
            return new String(decryptCipher.doFinal(Base64.getDecoder().decode(ciphertext)));
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException(e);
        }
    }

    public String encrypt(String cleartext) {
        try {
            return Base64.getEncoder().encodeToString(encryptCipher.doFinal(cleartext.getBytes()));
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException(e);
        }
    }
}