Skip to content

Commit eb8fbb7

Browse files
committed
add RSAUtils.java
1 parent 7dbd6aa commit eb8fbb7

File tree

3 files changed

+210
-0
lines changed

3 files changed

+210
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
package com.codingapi.springboot.framework.crypto;
2+
3+
import lombok.Getter;
4+
import org.bouncycastle.util.encoders.Base64;
5+
6+
import javax.crypto.Cipher;
7+
import java.nio.charset.StandardCharsets;
8+
import java.security.*;
9+
10+
public class RSA {
11+
12+
@Getter
13+
private final PrivateKey privateKey;
14+
15+
@Getter
16+
private final PublicKey publicKey;
17+
18+
public RSA() throws NoSuchAlgorithmException {
19+
KeyPair keyPair = RSAUtils.generateKey();
20+
this.privateKey = keyPair.getPrivate();
21+
this.publicKey = keyPair.getPublic();
22+
}
23+
24+
public RSA(PrivateKey privateKey, PublicKey publicKey){
25+
this.privateKey = privateKey;
26+
this.publicKey =publicKey;
27+
}
28+
29+
public RSA(String privateKey, String publicKey) throws Exception {
30+
this.privateKey = RSAUtils.getPrivateKeyFromString(privateKey);
31+
this.publicKey = RSAUtils.getPublicKeyFromString(publicKey);
32+
}
33+
34+
35+
/**
36+
* Encrypt a text using public key.
37+
*
38+
* @param text The original unencrypted text
39+
* @return Encrypted text
40+
* @throws Exception
41+
*/
42+
public byte[] encrypt(byte[] text) throws Exception {
43+
byte[] cipherText = null;
44+
// get an RSA cipher object and print the provider
45+
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
46+
47+
// encrypt the plaintext using the public key
48+
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
49+
cipherText = cipher.doFinal(text);
50+
return cipherText;
51+
}
52+
53+
/**
54+
* Encrypt a text using public key. The result is enctypted BASE64 encoded text
55+
*
56+
* @param text The original unencrypted text
57+
* @return Encrypted text encoded as BASE64
58+
* @throws Exception
59+
*/
60+
public String encrypt(String text) throws Exception {
61+
String encryptedText;
62+
byte[] cipherText = encrypt(text.getBytes(StandardCharsets.UTF_8));
63+
encryptedText = Base64.toBase64String(cipherText);
64+
return encryptedText;
65+
}
66+
67+
68+
/**
69+
* Decrypt text using private key
70+
*
71+
* @param text The encrypted text
72+
* @return The unencrypted text
73+
* @throws Exception
74+
*/
75+
public byte[] decrypt(byte[] text) throws Exception {
76+
byte[] dectyptedText = null;
77+
// decrypt the text using the private key
78+
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
79+
cipher.init(Cipher.DECRYPT_MODE, privateKey);
80+
dectyptedText = cipher.doFinal(text);
81+
return dectyptedText;
82+
83+
}
84+
85+
/**
86+
* Decrypt BASE64 encoded text using private key
87+
*
88+
* @param text The encrypted text, encoded as BASE64
89+
* @return The unencrypted text encoded as UTF8
90+
* @throws Exception
91+
*/
92+
public String decrypt(String text) throws Exception {
93+
String result;
94+
// decrypt the text using the private key
95+
byte[] dectyptedText = decrypt(Base64.decode(text));
96+
result = new String(dectyptedText, StandardCharsets.UTF_8);
97+
return result;
98+
}
99+
100+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package com.codingapi.springboot.framework.crypto;
2+
3+
import org.bouncycastle.jce.provider.BouncyCastleProvider;
4+
import org.bouncycastle.util.encoders.Base64;
5+
6+
import java.security.*;
7+
import java.security.spec.EncodedKeySpec;
8+
import java.security.spec.InvalidKeySpecException;
9+
import java.security.spec.PKCS8EncodedKeySpec;
10+
import java.security.spec.X509EncodedKeySpec;
11+
12+
13+
public class RSAUtils {
14+
protected static final String ALGORITHM = "RSA";
15+
16+
private RSAUtils() {
17+
18+
}
19+
20+
static {
21+
// Init java security to add BouncyCastle as an RSA provider
22+
Security.addProvider(new BouncyCastleProvider());
23+
}
24+
25+
26+
/**
27+
* Generate key which contains a pair of privae and public key using 1024 bytes
28+
*
29+
* @return key pair
30+
* @throws NoSuchAlgorithmException
31+
*/
32+
public static KeyPair generateKey() throws NoSuchAlgorithmException {
33+
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
34+
keyGen.initialize(2048);
35+
return keyGen.generateKeyPair();
36+
}
37+
38+
39+
40+
/**
41+
* Generates Private Key from BASE64 encoded string
42+
*
43+
* @param key BASE64 encoded string which represents the key
44+
* @return The PrivateKey
45+
* @throws Exception
46+
*/
47+
public static PrivateKey getPrivateKeyFromString(String key) throws Exception {
48+
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
49+
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decode(key));
50+
return keyFactory.generatePrivate(privateKeySpec);
51+
}
52+
53+
/**
54+
* Generates Public Key from BASE64 encoded string
55+
*
56+
* @param key BASE64 encoded string which represents the key
57+
* @return The PublicKey
58+
* @throws NoSuchAlgorithmException,InvalidKeySpecException
59+
*/
60+
public static PublicKey getPublicKeyFromString(String key) throws Exception {
61+
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
62+
EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.decode(key));
63+
return keyFactory.generatePublic(publicKeySpec);
64+
}
65+
66+
/**
67+
* Convert a Key to string encoded as BASE64
68+
*
69+
* @param key The key (private or public)
70+
* @return A string representation of the key
71+
*/
72+
public static String getKeyAsString(Key key) {
73+
// Get the bytes of the key
74+
byte[] keyBytes = key.getEncoded();
75+
return Base64.toBase64String(keyBytes);
76+
}
77+
78+
79+
80+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.codingapi.springboot.framework.crypto;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
7+
class RSATest {
8+
9+
@Test
10+
void test() throws Exception {
11+
RSA rsa = new RSA();
12+
String content = "123456";
13+
String encrypt = rsa.encrypt(content);
14+
System.out.println(encrypt);
15+
String decrypt =rsa.decrypt(encrypt);
16+
System.out.println(decrypt);
17+
assertEquals(decrypt,content);
18+
}
19+
20+
@Test
21+
void pwd() throws Exception {
22+
String privateKey ="MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggS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YbibTPGcb+Zaje9vO1J7Bpuydm9UxSvp+mj1J6rZpOMdGB5p6uFOwI0k492eT+nexyycACkzgmjy+74pv1G1lVsueWiWxaHEill3pXnrxZNGEmsDqMevDgKuwN8VMgGOaXWH3kS42KzQKBgQCKMoQ7Xj8KTHUTqva3mVETgP12XHw4qv5dsa74kSEC+/1+iG9q4cnVCS85LdeUPtIzxZ/hbzXOsA6E7tgz4gRjA700/GlVhScc2r08rykyfoJk3vTPcrCTvo0v4gq24Q4RstOZ2Vf4BmcfgJ742vah/fSNxRGSB4XzRMXkRKVQyQKBgHrV9e+fZQMxvwrGIJyttNHJek5ehGhOBgaz1YKOr4zzRgviIAL3p0oXeNQuAL9EaNwXX4aWjR6TbfP5CvU3+UsY+QREYdRWPi9xss09Ms8czQ8hH799tmToag66qd9cJFkVNMVChVLQQ8iRd4aJehirzupg5g55jrBzCEJClCvc";
23+
String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApk1TsAa2s6H+47SPE3ktIr+KxMYEGXecX3VW7Bt7ujgIwXz0i7lmxZr4mESKtpW6BPFEZ3DYt06dk7qm3IlDl+ODxsk2TzhDmKRM5C9g/ZUYVIdgDnGYX0kUjzuhT76FUbX3SKfTgO9TkMY586mcVo5bPlyqQNvhNan9HXEl30kWDLmRcZxBl0CqCzFJsrAdEGSB2gXfk6jY2NdjWLZCwaJK4QoGBLFtLVx2mcQZLrfOqxVzIWllph0pEp2XZZchTDvDyjdQ1aRTU/VBZixitlEu5u9vKOKSnUA4Z+9gYjf3dwbIl1qH3QR9yIcewzJP1riPZeAKPoS+N9SDiFBQBwIDAQAB";
24+
RSA rsa = new RSA(privateKey,publicKey);
25+
26+
String content = "mqCHaVZg2G0iNFaIFRM6zhQGnXma1v2mFP8LcuTtljsou/UNwDdPcQzkhe4pQaifEY2A4pVrJk+wL1dNxylFhJsgR3SojfLZXeBWcpkiwn/KHhRuzzw3fST0K3gPO9tLnOPsxembssNFG+J2nBAZNFdpQ6qi0W2gje9PttFBQZplBeypx5WdS1fDHEmNOIYJz0FwR6UuaSOVVDoXUboxLGkyt3VVt4qyvtOvHH9vqzbV4/77rfZktvHaQ9z5te/NPtLTsd1Uc3MXNxoXlKN9/tUPLLPqKNBfmrOtjPU3kvYsF7gEVXcxosFtI+kvy/4SGkcX3sHNEKuJqj5HWr+PLw==";
27+
String decrypt =rsa.decrypt(content);
28+
assertEquals(decrypt,"123456");
29+
}
30+
}

0 commit comments

Comments
 (0)