Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ Example module that shows integrating JNA GMP with Bouncy Castle.

Available on Maven central as `com.squareup.jnagmp:bouncycastle-rsa`.

### [sc-rsa](sc-rsa/README.md)

Example module that shows integrating JNA GMP with Spongy Castle.

Available on Maven central as `com.squareup.jnagmp:spongycastle-rsa`

## Contributors

- Scott Blum <dragonsinth@gmail.com>
Expand Down
9 changes: 9 additions & 0 deletions sc-rsa/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Spongy Castle RSA

Example module that shows integrating JNA GMP with Spongy Castle.

## Features

### NativeRSAEngine

A replacement for `org.spongycastle.crypto.engines.RSAEngine` that uses GMP modPow.
47 changes: 47 additions & 0 deletions sc-rsa/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.squareup.jnagmp</groupId>
<artifactId>jnagmp-parent</artifactId>
<version>2.0.1-SNAPSHOT</version>
</parent>

<artifactId>spongycastle-rsa</artifactId>
<name>Spongy Castle RSA</name>
<description>Example using JNA modPow with Spongy Castle</description>

<dependencies>
<dependency>
<groupId>com.squareup.jnagmp</groupId>
<artifactId>jnagmp</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.madgag.spongycastle</groupId>
<artifactId>prov</artifactId>
<version>1.50</version>
</dependency>

<!-- TEST DEPENDENCIES -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<excludes>com/squareup/crypto/rsa/NativeRSA*Engine.java</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
246 changes: 246 additions & 0 deletions sc-rsa/src/main/java/com/squareup/crypto/rsa/NativeRSACoreEngine.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
// Copy of org.bouncycastle.crypto.engines.RSACoreEngine
package com.squareup.crypto.rsa;

import com.squareup.jnagmp.GmpInteger;
import java.math.BigInteger;
import org.spongycastle.crypto.CipherParameters;
import org.spongycastle.crypto.DataLengthException;
import org.spongycastle.crypto.params.ParametersWithRandom;
import org.spongycastle.crypto.params.RSAKeyParameters;
import org.spongycastle.crypto.params.RSAPrivateCrtKeyParameters;

import static com.squareup.jnagmp.Gmp.modPowInsecure;
import static com.squareup.jnagmp.Gmp.modPowSecure;

/**
* this does your basic RSA algorithm.
*
* SQUARE: replacement for {@code RSACoreEngine}; this is <i>much</i> faster using jna-gmp.
*/
final class NativeRSACoreEngine
{
private RSAKeyParameters key;
private boolean forEncryption;
private boolean isPrivate;
private boolean isSmallExponent;

// cached components for private CRT key
private GmpInteger p;
private GmpInteger q;
private GmpInteger dP;
private GmpInteger dQ;
private BigInteger qInv;

// cached components for public key
private GmpInteger exponent;
private GmpInteger modulus;

/**
* initialise the RSA engine.
*
* @param forEncryption true if we are encrypting, false otherwise.
* @param param the necessary RSA key parameters.
*/
public void init(
boolean forEncryption,
CipherParameters param)
{
if (param instanceof ParametersWithRandom)
{
ParametersWithRandom rParam = (ParametersWithRandom)param;

key = (RSAKeyParameters)rParam.getParameters();
}
else
{
key = (RSAKeyParameters)param;
}

this.forEncryption = forEncryption;

if (key instanceof RSAPrivateCrtKeyParameters)
{
isPrivate = true;
//
// we have the extra factors, use the Chinese Remainder Theorem - the author
// wishes to express his thanks to Dirk Bonekaemper at rtsffm.com for
// advice regarding the expression of this.
//
RSAPrivateCrtKeyParameters crtKey = (RSAPrivateCrtKeyParameters)key;

p = new GmpInteger(crtKey.getP());
q = new GmpInteger(crtKey.getQ());
dP = new GmpInteger(crtKey.getDP());
dQ = new GmpInteger(crtKey.getDQ());
qInv = crtKey.getQInv();

exponent = modulus = null;
}
else
{
isPrivate = false;
exponent = new GmpInteger(key.getExponent());
modulus = new GmpInteger(key.getModulus());
isSmallExponent = exponent.bitLength() < 64;

p = q = dP = dQ = null;
qInv = null;
}
}

/**
* Return the maximum size for an input block to this engine.
* For RSA this is always one byte less than the key size on
* encryption, and the same length as the key size on decryption.
*
* @return maximum size for an input block.
*/
public int getInputBlockSize()
{
int bitSize = key.getModulus().bitLength();

if (forEncryption)
{
return (bitSize + 7) / 8 - 1;
}
else
{
return (bitSize + 7) / 8;
}
}

/**
* Return the maximum size for an output block to this engine.
* For RSA this is always one byte less than the key size on
* decryption, and the same length as the key size on encryption.
*
* @return maximum size for an output block.
*/
public int getOutputBlockSize()
{
int bitSize = key.getModulus().bitLength();

if (forEncryption)
{
return (bitSize + 7) / 8;
}
else
{
return (bitSize + 7) / 8 - 1;
}
}

public BigInteger convertInput(
byte[] in,
int inOff,
int inLen)
{
if (inLen > (getInputBlockSize() + 1))
{
throw new DataLengthException("input too large for RSA cipher.");
}
else if (inLen == (getInputBlockSize() + 1) && !forEncryption)
{
throw new DataLengthException("input too large for RSA cipher.");
}

byte[] block;

if (inOff != 0 || inLen != in.length)
{
block = new byte[inLen];

System.arraycopy(in, inOff, block, 0, inLen);
}
else
{
block = in;
}

BigInteger res = new BigInteger(1, block);
if (res.compareTo(key.getModulus()) >= 0)
{
throw new DataLengthException("input too large for RSA cipher.");
}

return res;
}

public byte[] convertOutput(
BigInteger result)
{
byte[] output = result.toByteArray();

if (forEncryption)
{
if (output[0] == 0 && output.length > getOutputBlockSize()) // have ended up with an extra zero byte, copy down.
{
byte[] tmp = new byte[output.length - 1];

System.arraycopy(output, 1, tmp, 0, tmp.length);

return tmp;
}

if (output.length < getOutputBlockSize()) // have ended up with less bytes than normal, lengthen
{
byte[] tmp = new byte[getOutputBlockSize()];

System.arraycopy(output, 0, tmp, tmp.length - output.length, output.length);

return tmp;
}
}
else
{
if (output[0] == 0) // have ended up with an extra zero byte, copy down.
{
byte[] tmp = new byte[output.length - 1];

System.arraycopy(output, 1, tmp, 0, tmp.length);

return tmp;
}
}

return output;
}

public BigInteger processBlock(BigInteger input)
{
if (isPrivate)
{
BigInteger mP, mQ, h, m;

// mP = ((input mod p) ^ dP)) mod p
mP = modPowSecure(input.remainder(p), dP, p);

// mQ = ((input mod q) ^ dQ)) mod q
mQ = modPowSecure(input.remainder(q), dQ, q);

// h = qInv * (mP - mQ) mod p
h = mP.subtract(mQ);
h = h.multiply(qInv);
h = h.mod(p); // mod (in Java) returns the positive residual

// m = h * q + mQ
m = h.multiply(q);
m = m.add(mQ);

return m;
}
else
{
if (isSmallExponent)
{
// Public key with reasonable (small) exponent, no need for secure.
return modPowInsecure(input, exponent, modulus);
}
else
{
// Client mistakenly configured private key as public? Better be safe than sorry.
return modPowSecure(input, exponent, modulus);
}
}
}
}
Loading