Skip to content

Instantly share code, notes, and snippets.

@jsgao0
Last active July 15, 2024 08:45
Show Gist options
  • Save jsgao0/52ca6f835a00cccb3cef164f2b9035c1 to your computer and use it in GitHub Desktop.
Save jsgao0/52ca6f835a00cccb3cef164f2b9035c1 to your computer and use it in GitHub Desktop.
Encryption with RSA using Java in Spring Framework.
package com.jsgao.bean;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
@Component
public class CipherUtility {
private static KeyPairGenerator keyPairGenerator = null;
private final SecureRandom random = new SecureRandom();
public KeyPair getKeyPair() {
return keyPairGenerator.genKeyPair();
}
public String encrypt(String content, Key pubKey) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] contentBytes = content.getBytes();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherContent = cipher.doFinal(contentBytes);
String encoded = Base64.getEncoder().encodeToString(cipherContent);
return encoded;
}
public String decrypt(String cipherContent, Key privKey) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] cipherContentBytes = Base64.getDecoder().decode(cipherContent.getBytes());
byte[] decryptedContent = cipher.doFinal(cipherContentBytes);
String decoded = new String(decryptedContent);
return decoded;
}
public String encodeKey(Key key) {
byte[] keyBytes = key.getEncoded();
String encodedKeyStr = Base64.getEncoder().encodeToString(keyBytes);
return encodedKeyStr;
}
public PublicKey decodePublicKey(String keyStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] keyBytes = Base64.getDecoder().decode(keyStr);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(spec);
return key;
}
public PrivateKey decodePrivateKey(String keyStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] keyBytes = Base64.getDecoder().decode(keyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey key = keyFactory.generatePrivate(keySpec);
return key;
}
@PostConstruct
private void init() {
try {
if(keyPairGenerator == null) keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024, random);
} catch(Exception e) {
e.printStackTrace();
}
}
}
package com.jsgao.bean;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.jsgao.Application;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class CipherUtilityTest {
@Autowired
private CipherUtility cipherUtility;
@Test
public void cipherTest() {
String plain = "Happy day!";
// Initialization of key pair for encryption and decryption.
KeyPair keyPair = cipherUtility.getKeyPair();
try {
// Get public key from the key pair.
PublicKey pubKey = keyPair.getPublic();
// Get private key from the key pair.
PrivateKey privKey = keyPair.getPrivate();
// Try to encode public key as a string.
String pubKeyStr = cipherUtility.encodeKey(pubKey);
// Assertion of 'pubKey' and the public key decoded by 'pubKeyStr'.
Assert.assertEquals(pubKey, cipherUtility.decodePublicKey(pubKeyStr));
// Try to encode private key as a string.
String privKeyStr = cipherUtility.encodeKey(privKey);
// Assertion of 'privKey' and the private key decoded by 'privKeyStr'.
Assert.assertEquals(privKey, cipherUtility.decodePrivateKey(privKeyStr));
// Encrypt plain as a cipher.
String cipherContent = cipherUtility.encrypt(plain, pubKey);
// Decrypt cipher to original plain.
String decryptResult = cipherUtility.decrypt(cipherContent, privKey);
// Assertion of 'plain' and 'decryptResult'.
Assert.assertEquals(plain, decryptResult);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment