Skip to content

Instantly share code, notes, and snippets.

@blaubaer
Created September 26, 2016 12:32
Show Gist options
  • Save blaubaer/1c6074bc674348249ab43710554f1ee4 to your computer and use it in GitHub Desktop.
Save blaubaer/1c6074bc674348249ab43710554f1ee4 to your computer and use it in GitHub Desktop.
import javax.crypto.Cipher;
import java.nio.charset.Charset;
import java.security.*;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
public class TestRsa {
private static final String KEY_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "SHA256WithRSA";
private static final Charset CHARSET = Charset.forName("UTF-8");
private static final String TEST_CONTENT = "This is a test content.";
public static void main(String[] args) throws Exception {
final KeyPair key = generateKeyPair();
final byte[] encrypted1 = encrypt(key.getPrivate(), TEST_CONTENT);
final String decrypted1 = decrypt(key.getPublic(), encrypted1);
if (!TEST_CONTENT.equals(decrypted1)) {
throw new IllegalStateException("There was something going wrong while encrypting/decrypting.");
}
final byte[] encrypted2 = encrypt(key.getPublic(), TEST_CONTENT);
final String decrypted2 = decrypt(key.getPrivate(), encrypted2);
if (!TEST_CONTENT.equals(decrypted2)) {
throw new IllegalStateException("There was something going wrong while encrypting/decrypting.");
}
final byte[] signature = sign(key.getPrivate(), TEST_CONTENT);
if (!verify(key.getPublic(), TEST_CONTENT, signature)) {
throw new IllegalStateException("There was something going wrong while signing/verifying.");
}
}
private static KeyPair generateKeyPair() throws Exception {
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyGen.initialize(4096);
return keyGen.generateKeyPair();
}
private static byte[] encrypt(Key key, String what) throws Exception {
final Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(ENCRYPT_MODE, key);
return cipher.doFinal(what.getBytes(CHARSET));
}
private static String decrypt(Key key, byte[] what) throws Exception {
final Cipher encryptor = Cipher.getInstance(KEY_ALGORITHM);
encryptor.init(DECRYPT_MODE, key);
return new String(encryptor.doFinal(what), CHARSET);
}
private static byte[] sign(PrivateKey key, String what) throws Exception {
final Signature instance = Signature.getInstance(SIGNATURE_ALGORITHM);
instance.initSign(key);
instance.update(what.getBytes(CHARSET));
return instance.sign();
}
private static boolean verify(PublicKey key, String what, byte[] signature) throws Exception {
final Signature instance = Signature.getInstance(SIGNATURE_ALGORITHM);
instance.initVerify(key);
instance.update(what.getBytes(CHARSET));
return instance.verify(signature);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment