Skip to content

Instantly share code, notes, and snippets.

@afiqiqmal
Last active October 23, 2020 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afiqiqmal/d30f1327f5832ed790d1fdf688fbd357 to your computer and use it in GitHub Desktop.
Save afiqiqmal/d30f1327f5832ed790d1fdf688fbd357 to your computer and use it in GitHub Desktop.
Generate KeyPair RSA In Java
package com.example.rsagenerator;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import com.example.rsagenerator.databinding.ActivityMainBinding;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
}
public void generate(View view) {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
PublicKey publicKey = kp.getPublic();
PrivateKey privateKey = kp.getPrivate();
String pubKey = Base64.encodeToString(publicKey.getEncoded(), Base64.DEFAULT);
String priKey = Base64.encodeToString(privateKey.getEncoded(), Base64.DEFAULT);
binding.setRsa1(pubKey);
binding.setRsa2(priKey);
Log.d("publicKey", pubKey);
Log.d("privateKey", priKey);
String stringToSign = "Testing1|Testing2|Testing3";
String signByte = signData(stringToSign.getBytes(), privateKey);
Log.d("signByte", signByte);
signVerify(stringToSign.getBytes(), publicKey, signByte);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static String signData (byte[] data, PrivateKey javaPrivateKey) {
try {
Signature s = Signature.getInstance("SHA256withRSA");
s.initSign(javaPrivateKey);
s.update(data);
byte[] signature = s.sign();
return Base64.encodeToString(signature , Base64.NO_WRAP);
} catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
public static void signVerify (byte[] data, PublicKey javaPublicKey, String signature) {
try {
Signature s = Signature.getInstance("SHA256withRSA");
s.initVerify(javaPublicKey);
s.update(data);
boolean success = s.verify(Base64.decode(signature, Base64.NO_WRAP));
if(success) {
Log.e("signVerify", "OK");
} else {
Log.e("signVerify", "FAILED");
}
} catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment