Skip to content

Commit 568113e

Browse files
authored
Create CipherDecrypt.java
1 parent 1ea21e6 commit 568113e

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

CipherDecrypt.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.security.KeyPair;
2+
import java.security.KeyPairGenerator;
3+
import java.security.Signature;
4+
5+
import javax.crypto.Cipher;
6+
7+
public class CipherDecrypt {
8+
public static void main(String args[]) throws Exception{
9+
//Creating a Signature object
10+
Signature sign = Signature.getInstance("SHA256withRSA");
11+
12+
//Creating KeyPair generator object
13+
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
14+
15+
//Initializing the key pair generator
16+
keyPairGen.initialize(2048);
17+
18+
//Generate the pair of keys
19+
KeyPair pair = keyPairGen.generateKeyPair();
20+
21+
//Getting the public key from the key pair
22+
PublicKey publicKey = pair.getPublic();
23+
24+
//Creating a Cipher object
25+
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
26+
27+
//Initializing a Cipher object
28+
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
29+
30+
//Add data to the cipher
31+
byte[] input = "Welcome to Tutorialspoint".getBytes();
32+
cipher.update(input);
33+
34+
//encrypting the data
35+
byte[] cipherText = cipher.doFinal();
36+
System.out.println( new String(cipherText, "UTF8"));
37+
38+
//Initializing the same cipher for decryption
39+
cipher.init(Cipher.DECRYPT_MODE, pair.getPrivate());
40+
41+
//Decrypting the text
42+
byte[] decipheredText = cipher.doFinal(cipherText);
43+
System.out.println(new String(decipheredText));
44+
}
45+
}

0 commit comments

Comments
 (0)