# Juce RSA implementation

**URL:** <https://forum.juce.com/t/juce-rsa-implementation/10341>\
**Category:** General JUCE discussion\
**Created:** [April 23, 2013, 1:19pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341 "2013-04-23T13:19:43Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![gbevin](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/gbevin/32/258_2.png) [@gbevin](https://forum.juce.com/u/gbevin)\
**Post date:** [April 23, 2013, 1:19pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/1 "2013-04-23T13:19:43Z")

</div>

Hi,

I’m looking at using Juce’s RSA implementation for implementing a key-based license system. I however want to integrate it with a web backend that hands out license key files based on email address and key-code. Since my whole server-side infrastructure is built with Java, I’d like to use that to implement the backend. I can’t however find anything that seems compatible with Juce’s RSA implementation. Has anyone done something like this? What is the RSA/Cipher you’ve used?

Thanks,

Geert

---

<div class="post-metadata">

**Author:** ![jules](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@jules](https://forum.juce.com/u/jules)\
**Post date:** [April 23, 2013, 1:21pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/2 "2013-04-23T13:21:48Z")

</div>

I did the same thing with a simple juce command-line exe that the server runs to generate the key.

---

<div class="post-metadata">

**Author:** ![gbevin](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/gbevin/32/258_2.png) [@gbevin](https://forum.juce.com/u/gbevin)\
**Post date:** [April 23, 2013, 1:36pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/3 "2013-04-23T13:36:12Z")

</div>

Thanks for the info Jules, I saw that in an earlier thread indeed. Ideally though I would like to keep it in Java instead of having to compile something to binary. Currently I can very easily migrate servers or bring other ones up since it’s all platform agnostic. As soon as a native executable enters the picture, this becomes much less trivial. Do you remember by any chance what you based your RSA implementation on? Maybe BouncyCastle has something compatible. Worst comes to happens, maybe I can just port your logic, it doesn’t seem very involving.

---

<div class="post-metadata">

**Author:** ![ckk](https://avatars.discourse-cdn.com/v4/letter/c/d26b3c/32.png) [@ckk](https://forum.juce.com/u/ckk)\
**Post date:** [April 23, 2013, 1:37pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/4 "2013-04-23T13:37:41Z")

</div>

Java also has a BigInteger class. It isn’t that hard to rewrite the RSAKey class for Java but of course you need to change some parts (mainly string parsing for the keys).

---

<div class="post-metadata">

**Author:** ![gbevin](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/gbevin/32/258_2.png) [@gbevin](https://forum.juce.com/u/gbevin)\
**Post date:** [April 23, 2013, 1:41pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/5 "2013-04-23T13:41:26Z")

</div>

Yes, the string parsing I already have done to get the correct bytes to the javax.crypto classes. Looks like I’ll just go all the way then 🙂

---

<div class="post-metadata">

**Author:** ![ckk](https://avatars.discourse-cdn.com/v4/letter/c/d26b3c/32.png) [@ckk](https://forum.juce.com/u/ckk)\
**Post date:** [April 23, 2013, 2:01pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/6 "2013-04-23T14:01:50Z")

</div>

The java.cryptox RSA algorithm is most probably different than the JUCE one (regarding key/data representation).  
For de/encryption you only need the constructor from a String, creating a BigInteger from a string the same way JUCE does and applyToValue().

Chris

---

<div class="post-metadata">

**Author:** ![gbevin](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/gbevin/32/258_2.png) [@gbevin](https://forum.juce.com/u/gbevin)\
**Post date:** [April 23, 2013, 10:18pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/7 "2013-04-23T22:18:39Z")

</div>

Great, this only took 10 minutes of time to port. For the future people that might be interested, here’s the Java class:

```auto
public class RSAKey {
  private BigInteger part1, part2;

  public RSAKey(String key) {
    if (key.contains(",")) {
      String[] split = key.split(",");
      part1 = new BigInteger(split[0], 16);
      part2 = new BigInteger(split[1], 16);
    }
    else {
      throw new IllegalArgumentException("The string needs to be two hex numbers, comma-separated");
    }
  }

  public BigInteger applyToValue(BigInteger value) {
    if (part1.equals(BigInteger.ZERO) || part2.equals(BigInteger.ZERO) || value.compareTo(BigInteger.ZERO) <= 0) {
      return null;
    }

    BigInteger result = BigInteger.ZERO;

    while (!value.equals(BigInteger.ZERO)) {
      result = result.multiply(part2);

      BigInteger[] div = value.divideAndRemainder(part2);
      value = div[0];
      BigInteger remainder = div[1];

      remainder = remainder.modPow(part1, part2);

      result = result.add(remainder);
    }

    return result;
  }
}
```

Use like this:

```auto
    RSAKey rsa = new RSAKey("JUCEhexRSAkey");
    BigInteger result = rsa.applyToValue(new BigInteger("JUCEencryptedHEXstring", 16));
    System.out.println(new String(result.toByteArray(), "UTF-8"));
```

---

<div class="post-metadata">

**Author:** ![FabienTDR](https://avatars.discourse-cdn.com/v4/letter/f/cdc98d/32.png) [@FabienTDR](https://forum.juce.com/u/FabienTDR)\
**Post date:** [May 26, 2014, 3:52pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/8 "2014-05-26T15:52:08Z")

</div>

I ran into a similar problem, but this time it's about "synchronizing" the RSA implemenation of PHP's&nbsp; phpseclib with JUCE's approach.

Before I try to re-invent the wheel by adapting the original phpseclib code to JUCE's implementation (both are incompatible), has anybody worked on this issue before? I thought I might ask first ;)

---

<div class="post-metadata">

**Author:** ![FabienTDR](https://avatars.discourse-cdn.com/v4/letter/f/cdc98d/32.png) [@FabienTDR](https://forum.juce.com/u/FabienTDR)\
**Post date:** [May 27, 2014, 9:19pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/9 "2014-05-27T21:19:00Z")

</div>

For the record, we finally managed to reproduce's JUCE's RSA algorithm with a standard PHP environment. Find our solution below.  
&nbsp;

Keep in mind that JUCE's RSA implenentation is not super-safe (time attacks, etc). I strongly recommend to not use JUCE's RSA for critical network business. In our case, JUCE's RSA implemenation was sufficient, since we only use RSA for certain parts of our key based, "garden fence" copy protection.

First of all, download phpseclib from http://phpseclib.sourceforge.net/ it's an open source (MIT) and dependency free alternative to openSSL. We use its Math/BigInteger.php class to represent the (really) big ints needed for RSA.

Here's the PHP side encryption/decryption code:

```
<?php

// from http://phpseclib.sourceforge.net/
include('Math/BigInteger.php');

function applyToValue($x, $key_part1, $key_part2)
{
    $part1 = new Math_BigInteger($key_part1, 16);
    $part2 = new Math_BigInteger($key_part2, 16);

    $zero = new Math_BigInteger();
    $value = new Math_BigInteger(strrev($x), 256);

    $result = new Math_BigInteger();

    while (!$value->equals($zero)) {
        $result = $result->multiply($part2);

        list($value, $remainder) = $value->divide($part2);

        $result = $result->add($remainder->modPow($part1, $part2));
    }

    return strrev($result->toBytes());
}

// generated by RSAKey::createKeyPair()
$PUBLIC_KEY_PART_1 = "5";
$PUBLIC_KEY_PART_2 = "60c838206a7e278ea3af103ce3b602d9de733a99f6d37df6580271996c9fba13";

$PRIVATE_KEY_PART_1 = "3a11bb46a64bb155956909be223a01b52c8bee2841d0caee997204997d4c360d";
$PRIVATE_KEY_PART_2 = "60c838206a7e278ea3af103ce3b602d9de733a99f6d37df6580271996c9fba13";

// secret message
$initial = "There's a rabbit in my hat!";

// encrypt by public key
$encrypted = applyToValue($initial, $PUBLIC_KEY_PART_1, $PUBLIC_KEY_PART_2);

// decrypt by private key
$decrypted = applyToValue($encrypted, $PRIVATE_KEY_PART_1, $PRIVATE_KEY_PART_2);

echo $decrypted."\n";

?>
```

And just for clarity, here's the JUCE side encryption/decryption:  
&nbsp;

```
RSAKey public_key("5,60c838206a7e278ea3af103ce3b602d9de733a99f6d37df6580271996c9fba13");
RSAKey private_key("3a11bb46a64bb155956909be223a01b52c8bee2841d0caee997204997d4c360d,60c838206a7e278ea3af103ce3b602d9de733a99f6d37df6580271996c9fba13");
 
String initial = "There's a rabbit in my hat!";
 
BigInteger bi;
bi.loadFromMemoryBlock(MemoryBlock(initial.getCharPointer(), initial.length()));
 
// encrypt
public_key.applyToValue(bi);

 
// decrypt
private_key.applyToValue(bi);
 
String decrypted = bi.toMemoryBlock().toString();
```

---

<div class="post-metadata">

**Author:** ![FabienTDR](https://avatars.discourse-cdn.com/v4/letter/f/cdc98d/32.png) [@FabienTDR](https://forum.juce.com/u/FabienTDR)\
**Post date:** [May 27, 2014, 9:22pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/10 "2014-05-27T21:22:53Z")

</div>

@Jules: Maybe we can add gbevin's JAVA and our PHP example to JUCE's documentation?

---

<div class="post-metadata">

**Author:** ![jules](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@jules](https://forum.juce.com/u/jules)\
**Post date:** [May 28, 2014, 11:55am UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/11 "2014-05-28T11:55:49Z")

</div>

Sure, thanks guys, I'll add some notes about that.

> Keep in mind that JUCE's RSA implenebtation is not super-safe (time attacks, etc)

I'd take issue with that!&nbsp;Assuming&nbsp;there's no flaw in the actual RSA algorithm itself, then the&nbsp;only weakness could be in the random number that you use to generate the key-pair?

Since the RSA::createKeyPair() method provides a parameter where you can provide your own extra randomness bits, then even if you don't trust the default implementation, you could still&nbsp;use it.. And its default RNG is pretty damned convoluted, involving&nbsp;many samples of&nbsp;tick-resolution counters from different timebases, and a lot of complicated system-dependent interactions between them. Even if someone had the skill and patience&nbsp;to reverse-engineer it, I doubt whether they could&nbsp;reduce the search space enough to make an attack feasible. (And it would&nbsp;be a very determined&nbsp;attacker who'd go to all that trouble&nbsp;when you may not even have&nbsp;used the default RNG!)

Personally, when I've used it to generate keys, I've seeded it with some a couple of extra things like a randomly-typed&nbsp;constant, the number of bytes free on my hard disk, etc, so there must be at least a couple of hundred bits of entropy, even if an attacker knew the time when the key was generated to within a few seconds.

&nbsp;

---

<div class="post-metadata">

**Author:** ![FabienTDR](https://avatars.discourse-cdn.com/v4/letter/f/cdc98d/32.png) [@FabienTDR](https://forum.juce.com/u/FabienTDR)\
**Post date:** [May 28, 2014, 1:13pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/12 "2014-05-28T13:13:57Z")

</div>

Fair enough. Maybe I should have worded the warning differently. ;)

I don't expect the typical cracker to get his hands dirty with encryption anyway. But I doubt that any sort of "bedroom" tested implemenation will be rejected by typical security audits (those you face when working for big IT corps or public authority). These ppl usually have no idea about the technical side, they just fill a long, burocratic check-list. Following PCKS guidelines or other established standards helps alot in this case (not to mention interoperability with other technologies).  
  
  
But don't get me wrong. I am really happy with JUCE's implementation! It's was perfect for our case and will probabaly be just right for most other scenarios as well.

&nbsp;

Interesting read: http://happybearsoftware.com/you-are-dangerously-bad-at-cryptography.html :)

---

<div class="post-metadata">

**Author:** ![jules](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@jules](https://forum.juce.com/u/jules)\
**Post date:** [May 28, 2014, 1:21pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/13 "2014-05-28T13:21:47Z")

</div>

Oh yes, I know it'd never pass a corporate paranoia test! Just saying that for normal use by non-corporate folk, there's nothing to be nervous about!

---

<div class="post-metadata">

**Author:** ![CrushedPixel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/crushedpixel/32/8654_2.png) [@CrushedPixel](https://forum.juce.com/u/CrushedPixel)\
**Post date:** [December 23, 2019, 3:42pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/14 "2019-12-23T15:42:16Z")

</div>

Here’s my implementation of the JUCE RSA algorithm in Go:

```auto
import (
	"math/big"
	"strings"
)

func applyJuceRSAKey(message []byte, key string) []byte {
	keyParts := strings.Split(key, ",")

	var keyPart1, keyPart2 big.Int
	keyPart1.SetString(keyParts[0], 16)
	keyPart2.SetString(keyParts[1], 16)

	// JUCE BigIntegers are in little-endian format,
	// while big.Int is in big-endian format.
	// reverse the input bytes to convert them from
	// little-endian to big-endian.
	reverse(message)

	msg := new(big.Int)
	msg.SetBytes(message)

	result := new(big.Int)
	zero := new(big.Int)

	for msg.Cmp(zero) != 0 {
		result.Mul(result, &keyPart2)

		remainder := new(big.Int)
		msg.DivMod(msg, &keyPart2, remainder)

		result.Add(result, remainder.Exp(remainder, &keyPart1, &keyPart2))
	}

	// convert the big-endian bytes into
	// little-endian bytes again
	resultBytes := result.Bytes()
	reverse(resultBytes)

	return resultBytes
}

func reverse(s []byte) {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
}

```

@jules you’re welcome to use this snippet in the `RSAKey` documentation 🙂

---

<div class="post-metadata">

**Author:** ![spirux](https://avatars.discourse-cdn.com/v4/letter/s/2bfe46/32.png) [@spirux](https://forum.juce.com/u/spirux)\
**Post date:** [June 17, 2020, 4:16pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/15 "2020-06-17T16:16:13Z")

</div>

I’ve created a Python 3 package that exposes the JUCE RSA implementation to python.

Check it out [on PyPI](https://pypi.org/project/juce-rsa/). Feel free to file issues or contribute in the corresponding [GitHub page](https://github.com/sevangelatos/juce_rsa) and/or to include it in the `RSAKey` docs.

---

<div class="post-metadata">

**Author:** ![hexmarkrecords](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/hexmarkrecords/32/11115_2.png) [@hexmarkrecords](https://forum.juce.com/u/hexmarkrecords)\
**Post date:** [September 8, 2021, 11:43pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/16 "2021-09-08T23:43:58Z")

</div>

And for those after a node.js implementation (Requires the big-integer package):

```auto
npm install big-integer

```

JS Implementation inspired from JUCE:

rsa-key.js:

```auto
const bigInt = require('big-integer')

class RSAKey {
	constructor (key) {
		if (key.indexOf(',') > 0) {
			const p = key.split(',');

			this.part1 = this.fromHex(p[0]);
			this.part2 = this.fromHex(p[1]);
		} else {
			throw new Error('The string needs to be two hex numbers, comma-separated');
		}
	}

	fromHex (val) {
		return bigInt(val, 16);
	}

	applyToValue (value) {
		if (!this.part1.compareTo(bigInt.zero)
			|| !this.part2.compareTo(bigInt.zero)
			|| value.compareTo(bigInt.zero) <= 0) {
			return null;
		}

		let result = bigInt.zero;

		while (bigInt.zero.compareTo(value)) {
			result = this.part2.multiply(result);

			let { quotient, remainder } = value.divmod(this.part2);
			value = quotient;
			remainder = remainder.modPow(this.part1, this.part2);

			result = result.add(remainder);
		}

		return result;
	}
}

module.exports = RSAKey;

```

(for testing) index.js:

```auto
const RSAKey = require('./rsa-key');

const rsa = new RSAKey('5,60c838206a7e278ea3af103ce3b602d9de733a99f6d37df6580271996c9fba13');

const result = rsa.applyToValue(rsa.fromHex('abc123'));
console.log(result.toString(16));

process.exit(0);

```

---

<div class="post-metadata">

**Author:** ![wimvandenborre](https://avatars.discourse-cdn.com/v4/letter/w/da6949/32.png) [@wimvandenborre](https://forum.juce.com/u/wimvandenborre)\
**Post date:** [May 13, 2022, 9:15am UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/17 "2022-05-13T09:15:43Z")

</div>

Hey hey, Thank you for the code! If someone at the Juce team reads this, this could go straight to: [JUCE: RSAKey Class Reference](https://docs.juce.com/master/classRSAKey.html)

---

<div class="post-metadata">

**Author:** ![adamwilson](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/adamwilson/32/1387_2.png) [@adamwilson](https://forum.juce.com/u/adamwilson)\
**Post date:** [October 27, 2022, 9:17am UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/18 "2022-10-27T09:17:30Z")

</div>

@hexmarkrecords we are trying to get your NodeJS example working. Following your example, the encoded string does not decode properly using the JUCE methods. It seems that `applyToValue` in your example accepts and returns a string when it should be a byte array.

@eyalamir did you get anywhere with this?

---

<div class="post-metadata">

**Author:** ![hexmarkrecords](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/hexmarkrecords/32/11115_2.png) [@hexmarkrecords](https://forum.juce.com/u/hexmarkrecords)\
**Post date:** [October 27, 2022, 5:44pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/19 "2022-10-27T17:44:02Z")

</div>

Hi @adamwilson,

I completely abandoned the pure js solution unfortunately.

I ran into problems with JS big integer vs the C++ implentation and ended up experimenting with a C++ implementation of the product unlock, built as a linux shared library wrapped by NAPI with the intention to integrated into a microservice. Node, under the hood was written in C++ thus provides easy integration with native C++ libraries enabling solutions like this.

This strategy ensured that i used exactly the same implementation of big integer througout the solution alleviating the problem.

Your probably chuckling right now at this elaborate solution, as its quite a workaround, but it worked for my PoC.

If you get anywhere with a pure js solution could you let me know as that would greatly intrest me.

---

<div class="post-metadata">

**Author:** ![eyalamir](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.juce.com/eyalamir/32/2978_2.png) [@eyalamir](https://forum.juce.com/u/eyalamir)\
**Post date:** [October 27, 2022, 6:04pm UTC](https://forum.juce.com/t/juce-rsa-implementation/10341/20 "2022-10-27T18:04:21Z")

</div>

I went with a similar solution.

Most cloud services (Google, Amazon, Azure, etc) allow you now to just run a docker container written in any language that just answers an http request.

So I just deployed the JUCE RSA implementation using something like this:

> **[JuceDocker/Apps/Encryptor at master · eyalamirmusic/JuceDocker](https://github.com/eyalamirmusic/JuceDocker/tree/master/Apps/Encryptor)**
>
> master/Apps/Encryptor

Once you put it behind a ‘clean’ http request, you can call it from the plugin, from a NodeJS app, from a Python App, etc.

[Next page](https://forum.juce.com/t/juce-rsa-implementation/10341.md?page=2)
