Rsa Algorithm Key Generation Example Java

  1. Key Generator
Example of RSA generation, sign, verify, encryption, decryption and keystores in Java

How can I generate RSA key pair in Java using the format supported by OpenSSL? Is there a way to generate them straight away like how we do in php? The output should be like: -BEGIN PU. Aug 30, 2016 شرح كامل للتشفير و فك التشفير وعمل المفتاح عن طريق شيفرة rsa بطريقة مبسطة مع حل مثال. /. Compilation: javac RSA.java. Execution: java RSA N. Generate an N-bit public and private RSA key and use to encrypt. and decrypt a random message.% java RSA 50. public = 65537. private = 26609. modulus = 90631. message = 4950. encrpyted = 60104. decrypted = 4950. RSA the Key Generation Example 1. Randomly choose two prime numbers pand q. We choose p= 11 and q= 13. Compute n= pq. We compute n= pq= 1113 = 143.

RsaExample.java
importjavax.crypto.Cipher;
importjava.io.InputStream;
importjava.security.*;
importjava.util.Base64;
import staticjava.nio.charset.StandardCharsets.UTF_8;
publicclassRsaExample {
publicstaticKeyPairgenerateKeyPair() throwsException {
KeyPairGenerator generator =KeyPairGenerator.getInstance('RSA');
generator.initialize(2048, newSecureRandom());
KeyPair pair = generator.generateKeyPair();
return pair;
}
publicstaticKeyPairgetKeyPairFromKeyStore() throwsException {
//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
newKeyStore.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();
returnnewKeyPair(publicKey, privateKey);
}
publicstaticStringencrypt(StringplainText, PublicKeypublicKey) throwsException {
Cipher encryptCipher =Cipher.getInstance('RSA');
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherText = encryptCipher.doFinal(plainText.getBytes(UTF_8));
returnBase64.getEncoder().encodeToString(cipherText);
}
publicstaticStringdecrypt(StringcipherText, PrivateKeyprivateKey) throwsException {
byte[] bytes =Base64.getDecoder().decode(cipherText);
Cipher decriptCipher =Cipher.getInstance('RSA');
decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);
returnnewString(decriptCipher.doFinal(bytes), UTF_8);
}
publicstaticStringsign(StringplainText, PrivateKeyprivateKey) throwsException {
Signature privateSignature =Signature.getInstance('SHA256withRSA');
privateSignature.initSign(privateKey);
privateSignature.update(plainText.getBytes(UTF_8));
byte[] signature = privateSignature.sign();
returnBase64.getEncoder().encodeToString(signature);
}
publicstaticbooleanverify(StringplainText, Stringsignature, PublicKeypublicKey) throwsException {
Signature publicSignature =Signature.getInstance('SHA256withRSA');
publicSignature.initVerify(publicKey);
publicSignature.update(plainText.getBytes(UTF_8));
byte[] signatureBytes =Base64.getDecoder().decode(signature);
return publicSignature.verify(signatureBytes);
}
publicstaticvoidmain(String... argv) throwsException {
//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);
}
}

commented Oct 17, 2019

It's good thank you so much , How can i create base64 like jwt (header,body,sign) ?

commented Nov 26, 2019

Thanks for the code. One issue - using openjdk version '11.0.5-ea' 2019-10-15 requires the KeyStore.getInstance('JCEKS') code to be KeyStore.getInstance('PKCS12').

commented Dec 29, 2019

@stdunbar: It depends on your keyStore creation.

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

Java Program on RSA Algorithm

RSA algorithm is an asymmetric cryptography algorithm. Asymmetric means that it works on two different keys i.e. Public Key and Private Key. As the name suggests that the Public Key is given to everyone and Private Key is kept private.

Algorithm

Key

Step 1 : Choose two prime numbers p and q.

Step 2 : Calculate n = p*q

Step 3 : Calculate ϕ(n) = (p – 1) * (q – 1)

Step 4 : Choose e such that gcd(e , ϕ(n) ) = 1

Step 5 : Calculate d such that e*d mod ϕ(n) = 1

Step 6 : Public Key {e,n} Private Key {d,n}

Key Generator

Step 7 : Cipher text C = Pe mod n where P = plaintext

Step 8 : For Decryption D = Dd mod n where D will give back the plaintext.

If you need a dry run of the program or any other query, then kindly leave a comment in the comment box or mail me, I would be more than happy to help you.


Program

java program on RSA Algorithm
Rsa algorithm key generation example java pdf
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
importjava.math.*;
classRSA
publicstaticvoidmain(Stringargs[])
Scanner sc=newScanner(System.in);
System.out.println('Enter the number to be encrypted and decrypted');
doublec;
System.out.println('Enter 1st prime number p');
System.out.println('Enter 2nd prime number q');
z=(p-1)*(q-1);
{
{
}
System.out.println('the value of e = '+e);
{
if(x%e0)//d is for private key exponent
d=x/e;
}
System.out.println('the value of d = '+d);
System.out.println('Encrypted message is : -');
//converting int value of n to BigInteger
//converting float value of c to BigInteger
msgback=(C.pow(d)).mod(N);
System.out.println(msgback);
}
staticintgcd(inte,intz)
if(e0)
else
}

Output

You may also Like