Skip to content

Commit 3e8673a

Browse files
committed
Added RSA
1 parent 09378e6 commit 3e8673a

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
2+
package com.example.rsaservice;
3+
4+
import org.springframework.boot.SpringApplication;
5+
import org.springframework.boot.autoconfigure.SpringBootApplication;
6+
7+
@SpringBootApplication
8+
public class RsaBackendServiceApplication {
9+
public static void main(String[] args) {
10+
SpringApplication.run(RsaBackendServiceApplication.class, args);
11+
}
12+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
2+
package com.example.rsaservice.util;
3+
4+
import javax.crypto.Cipher;
5+
import java.security.*;
6+
import java.util.Base64;
7+
8+
public class RSAUtil {
9+
private static final String ALGORITHM = "RSA";
10+
private static final String TRANSFORMATION = "RSA/ECB/OAEPWithSHA-1AndMGF1Padding";
11+
private static KeyPair keyPair;
12+
13+
static {
14+
try {
15+
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
16+
keyPairGenerator.initialize(2048);
17+
keyPair = keyPairGenerator.generateKeyPair();
18+
} catch (Exception e) {
19+
throw new RuntimeException("Error initializing RSA KeyPair", e);
20+
}
21+
}
22+
23+
public static String encrypt(String plaintext) throws Exception {
24+
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
25+
cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
26+
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
27+
return Base64.getEncoder().encodeToString(encryptedBytes);
28+
}
29+
30+
public static String decrypt(String encryptedText) throws Exception {
31+
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
32+
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
33+
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
34+
return new String(decryptedBytes);
35+
}
36+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
2+
server.port=8080

0 commit comments

Comments
 (0)