Skip to content

Instantly share code, notes, and snippets.

@wuyisheng
Forked from nielsutrecht/RsaExample.java
Last active March 25, 2019 20:23
Show Gist options
  • Save wuyisheng/f3cbfe7a0dfc8734e95493c00ebfc322 to your computer and use it in GitHub Desktop.
Save wuyisheng/f3cbfe7a0dfc8734e95493c00ebfc322 to your computer and use it in GitHub Desktop.
Example of RSA generation, sign, verify, encryption, decryption and keystores in Java
import javax.crypto.Cipher;
import java.io.InputStream;
import java.security.*;
import java.util.Base64;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.security.spec.X509EncodedKeySpec;
public class RsaExample {
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048, new SecureRandom());
KeyPair pair = generator.generateKeyPair();
return pair;
}
public static KeyPair getKeyPairFromKeyStore() throws Exception {
// Generated with:
// keytool -genkeypair -alias mykey -storepass s3cr3t -keypass s3cr3t -keyalg
// RSA -keystore keystore.jks
InputStream ins = RsaExample.class.getResourceAsStream("/keystore.jks");
KeyStore keyStore = KeyStore.getInstance("JCEKS");
keyStore.load(ins, "s3cr3t".toCharArray()); // Keystore password
KeyStore.PasswordProtection keyPassword = // Key password
new KeyStore.PasswordProtection("s3cr3t".toCharArray());
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry("mykey", keyPassword);
java.security.cert.Certificate cert = keyStore.getCertificate("mykey");
PublicKey publicKey = cert.getPublicKey();
PrivateKey privateKey = privateKeyEntry.getPrivateKey();
return new KeyPair(publicKey, privateKey);
}
public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherText = encryptCipher.doFinal(plainText.getBytes(UTF_8));
return bytesToHexString(cipherText);
}
public static String decrypt(String cipherText, PrivateKey privateKey) throws Exception {
byte[] bytes = hexStringToBytes(cipherText);
Cipher decriptCipher = Cipher.getInstance("RSA");
decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(decriptCipher.doFinal(bytes), UTF_8);
}
public static String sign(String plainText, PrivateKey privateKey) throws Exception {
Signature privateSignature = Signature.getInstance("SHA1withRSA");
privateSignature.initSign(privateKey);
privateSignature.update(plainText.getBytes(UTF_8));
byte[] signature = privateSignature.sign();
return bytesToHexString(signature);
}
public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
Signature publicSignature = Signature.getInstance("SHA1withRSA");
publicSignature.initVerify(publicKey);
publicSignature.update(plainText.getBytes(UTF_8));
byte[] signatureBytes = hexStringToBytes(signature);
return publicSignature.verify(signatureBytes);
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
public static String publicKeyToString(PublicKey pubKey) {
return Base64.getEncoder().encodeToString(pubKey.getEncoded());
}
public static PublicKey stringToPublicKey(String key) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
Base64.Decoder dec = Base64.getDecoder();
byte[] encodedKey = dec.decode(key);
return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
}
public static void main(String... argv) throws Exception {
// First generate a public/private key pair
KeyPair pair = generateKeyPair();
// KeyPair pair = getKeyPairFromKeyStore();
// Our secret message
String message = "the answer to life the universe and everything";
// Encrypt the message
String cipherText = encrypt(message, pair.getPublic());
// Now decrypt it
String decipheredMessage = decrypt(cipherText, pair.getPrivate());
System.out.println(decipheredMessage);
// Let's sign our message
String signature = sign("foobar", pair.getPrivate());
// Let's check the signature
boolean isCorrect = verify("foobar", signature, pair.getPublic());
System.out.println("Signature correct: " + isCorrect);
String publicKey = publicKeyToString(pair.getPublic());
PublicKey pubKey = stringToPublicKey(publicKey);
boolean isCorrects = verify("foobar", signature, pubKey);
System.out.println("publicKey:" + publicKey);
System.out.println("signature:" + signature);
System.out.println("content:" + "foobar");
System.out.println("Signature correct: " + isCorrects);
}
}
// Usage:
// javac RsaExample.java
// java RsaExample
@d2btecnologia
Copy link

Hello. To use the getKeyPairFromKeyStore method, how should I do to sign with a private key?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment