Restore RSA private key by modulus, public and private exponents using Java Security

Restore RSA private key by modulus, public and private exponents using Java Security

By : Romemeek
Date : November 20 2020, 03:01 PM
will help you I provided some code in this answer which I will reproduce here:
code :
 * Find a factor of n by following the algorithm outlined in Handbook of Applied Cryptography, section
 * 8.2.2(i). See http://cacr.uwaterloo.ca/hac/about/chap8.pdf.

private static BigInteger findFactor(BigInteger e, BigInteger d, BigInteger n) {
    BigInteger edMinus1 = e.multiply(d).subtract(BigInteger.ONE);
    int s = edMinus1.getLowestSetBit();
    BigInteger t = edMinus1.shiftRight(s);

    for (int aInt = 2; true; aInt++) {
        BigInteger aPow = BigInteger.valueOf(aInt).modPow(t, n);
        for (int i = 1; i <= s; i++) {
            if (aPow.equals(BigInteger.ONE)) {
            if (aPow.equals(n.subtract(BigInteger.ONE))) {
            BigInteger aPowSquared = aPow.multiply(aPow).mod(n);
            if (aPowSquared.equals(BigInteger.ONE)) {
                return aPow.subtract(BigInteger.ONE).gcd(n);
            aPow = aPowSquared;


public static RSAPrivateCrtKey createCrtKey(RSAPublicKey rsaPub, RSAPrivateKey rsaPriv) throws NoSuchAlgorithmException, InvalidKeySpecException {

    BigInteger e = rsaPub.getPublicExponent();
    BigInteger d = rsaPriv.getPrivateExponent();
    BigInteger n = rsaPub.getModulus();
    BigInteger p = findFactor(e, d, n);
    BigInteger q = n.divide(p);
    if (p.compareTo(q) > 1) {
        BigInteger t = p;
        p = q;
        q = t;
    BigInteger exp1 = d.mod(p.subtract(BigInteger.ONE));
    BigInteger exp2 = d.mod(q.subtract(BigInteger.ONE));
    BigInteger coeff = q.modInverse(p);
    RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, exp1, exp2, coeff);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return (RSAPrivateCrtKey) kf.generatePrivate(keySpec);


Share : facebook icon twitter icon
How to factor RSA modulus given the public and private exponent?

How to factor RSA modulus given the public and private exponent?

By : user2986118
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Yes -- once you know the modulus N, and public/private exponents d and e, it is not too difficult to obtain p and q such that N=pq.
This paper by Dan Boneh describes an algorithm for doing so. It relies on the fact that, by definition,
RSA Key Values and Modulus in Public/Private Keys

RSA Key Values and Modulus in Public/Private Keys

By : QoL
Date : March 29 2020, 07:55 AM
it helps some times The RSAKeyValue, Modulus, and Exponent tags are in there because you used the method ToXmlString().
An RSA public key is made up of the modulus and the public exponent. There is no security issue with distributing these 2 items. HOWEVER, you do NOT want to distribute any of the other items in the Private Key. The private key has these fields:
code :
Java Security - RSA Public Key & Private Key Code Issue

Java Security - RSA Public Key & Private Key Code Issue

By : EOpp
Date : March 29 2020, 07:55 AM
will be helpful for those in need Here is my error
code :
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;

class RSA{

public static void main(String[] args) throws Exception {
    rsaEncrypt("plaintext.txt", "encrypted.txt");
    rsaDecrypt("encrypted.txt", "decrypted.txt");

public static void generateKeys() throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();
    PublicKey publicKey = kp.getPublic();
    PrivateKey privateKey = kp.getPrivate();

    System.out.println("keys created");

    KeyFactory fact = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pub = fact.getKeySpec(publicKey,
    RSAPrivateKeySpec priv = fact.getKeySpec(privateKey,

    saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
    saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent());

    System.out.println("keys saved");

public static void saveToFile(String fileName, BigInteger mod,
        BigInteger exp) throws IOException {
    ObjectOutputStream fileOut = new ObjectOutputStream(
            new BufferedOutputStream(new FileOutputStream(fileName)));
    try {
    } catch (Exception e) {
        throw new IOException("Unexpected error");
    } finally {
        System.out.println("Closed writing file.");

// Return the saved key
static Key readKeyFromFile(String keyFileName) throws IOException {
    InputStream in = new FileInputStream(keyFileName);
    ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
    try {
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        KeyFactory fact = KeyFactory.getInstance("RSA");
        if (keyFileName.startsWith("public"))
            return fact.generatePublic(new RSAPublicKeySpec(m, e));
            return fact.generatePrivate(new RSAPrivateKeySpec(m, e));
    } catch (Exception e) {
        throw new RuntimeException("Spurious serialisation error", e);
    } finally {
        System.out.println("Closed reading file.");

// Use this PublicKey object to initialize a Cipher and encrypt some data
public static void rsaEncrypt(String file_loc, String file_des)
        throws Exception {
    FileReader file = new FileReader("C://myprograms//plaintext.txt");
    BufferedReader reader = new BufferedReader(file);
    String text = "";
    String line = reader.readLine();
    while(line!= null)
        text += line;
    line = reader.readLine();
    byte[] data = new byte[32];
    int i;

    System.out.println("start encyption");
    Key pubKey = readKeyFromFile("public.key");
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);

    FileInputStream fileIn = new FileInputStream(file_loc);
    FileOutputStream fileOut = new FileOutputStream(file_des);
    CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher);

    // Read in the data from the file and encrypt it
    while ((i = fileIn.read(data)) != -1) {
        cipherOut.write(data, 0, i);

    // Close the encrypted file

    System.out.println("encrypted file created");

// Use this PublicKey object to initialize a Cipher and decrypt some data
public static void rsaDecrypt(String file_loc, String file_des)
        throws Exception {
    byte[] data = new byte[32];
    int i;

    System.out.println("start decyption");

    Key priKey = readKeyFromFile("private.key");
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, priKey);

    FileInputStream fileIn = new FileInputStream(file_loc);
    CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher);
    FileOutputStream fileOut = new FileOutputStream(file_des);

    // Write data to new file
    while ((i = cipherIn.read()) != -1) {

    // Close the file

    System.out.println("decrypted file created");

Generated RSA Public and Private key modulus are the same in Java/Android

Generated RSA Public and Private key modulus are the same in Java/Android

By : Pallavi
Date : November 05 2020, 03:01 PM
like below fixes the issue What you generate is a key pair for Java. The public and private keys of the key pair always share the same modulus: the calculations are performed within that domain.
What is kept secure is not the modulus but the private exponent and - generally also available - the parameters required to perform the fast exponentiation using the Chinese Remainder Theorem (CRT). These are basically the parameters such as prime P and Q used to calculate the private key and indeed the modulus.
Regenerating Public and Private Key based on modulus and public exponent

Regenerating Public and Private Key based on modulus and public exponent

By : Emily Chan
Date : March 29 2020, 07:55 AM
help you fix your problem In RSA the public key is (n, e), which you already have. Deriving the private key from the modulus is the exact thing RSA wants to be difficult. This is known as the factoring problem. If this was a tractable problem computationally then RSA would not be a useful cryptosystem. In fact, as computers have gotten faster and algorithms for factoring have improved (see: GNFS) the recommended bit length of an RSA key has gotten longer to combat this. Where 1024 was once considered acceptable today 2048 is a minimum recommendation.
You can't sign without the private key, as the idea is that a signature demonstrates possession of the private key and you use the public key (which you distribute in some fashion to the parties who need to validate the signature) to confirm that the signature is genuine. Frequently this is combined with X.509 to provide some identity binding, but it isn't required.
Related Posts Related Posts :
  • Integration Testing with Kitchen CI
  • Can't seem to get the from <asp:Literal </asp:Literal> property in Web forms
  • Can't access faraday params on views
  • RQM testNG integration
  • How can I enable unit templates?
  • Displaying multiple colors on a single data bar
  • Loading aggregates on reacting to domain events
  • Integrating Azure Cognitive services with Robotic Process Automation
  • Autodesk Forge Design Automation quota
  • Why can i not login to the wso2 api store using the email address of a secondary user store account
  • order not working with sortWhitelist
  • config.site for vendor libs on Fedora x86_64
  • Getting a limit response from Loopback, when no authentication is provided
  • What is the effect of FeedOptions.EnableLowPrecisionOrderBy Property
  • Recordset Null Value not being detected in null check
  • How to connect to an arbitary database using FaaS?
  • SourceTree not working after Windows 10 Fall Creators Update
  • How to get all registered user from Openfire through http
  • Error "invalid parameter" when launching a converted app
  • Using react-sortable-hoc with react-virtualized Grid
  • Xamarin.Forms: How to set values in Style only on specific platform
  • ZSH avoid adding empty commands to history?
  • Grep regular expression - Pattern issue
  • Unable to connect via Java to a DSE graph
  • Check if attachment is up to date with current document revision in couchdb
  • Can I bind an argument value ahead of time when using redux-actions?
  • How to change a member field with Kotlin reflection?
  • Replaying merged streams individually
  • DevExpress GridColumn strange proportional sizing
  • Drools Decision table error : Error while creating KieBase
  • Kafka-Flink-Stream processing: Is there a way to reload input files into the variables being used in a streaming process
  • How to export and import nifi flow from one HDP to another HDP
  • map pointWidth to a single Datapoint in Column Chart
  • Pygame animating image by transforming it
  • Why is my Gdk/cairo class causing a segfault?
  • How to organize queues in Masstransit/RabbitMQ?
  • How to remove a collection element without EntityManager#remove(...) in Doctrine 2?
  • how to change the format of the return value of 'mnist.load_data()' to 'mnist_train.csv' in Keras?
  • CodeFights Interview Practice- Dynamic Programing : Basic : fillingBlocks
  • Accessing the built request details in Karate
  • How to draw a polyline with initial point in Leaflet
  • docusign transform pdf field with text tab as required
  • How to avoid "unused variable in a for loop" error
  • Clipping a polygon to only draw within a circle in Love2D
  • Can't import library in Python
  • Silverstripe - Turn modules on or off in config
  • How does shared memory work behind the scene in Linux?
  • Vue - how to bind table column to a data object?
  • OrientDB deep traversal until specific class
  • Static code analysis of Dockerfiles?
  • Is Batmobile Defy Mini a fake device?
  • Reverse a list to a range
  • Add multiple y-axis to SAPUI5 VizFrame Column Charts
  • Nightmare with rabbitmq.client versions
  • How to change timeout for a request in okhttp
  • How to support relative date parameters in Web Intelligence Report
  • cfEngine3 - class if package is installed
  • Count number of sentences in a string in SAS
  • Visit Last Loaded URL
  • What are the use cases to substitute cookbook array attribute in chef?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org