Skip to content

Commit 06cb8a3

Browse files
authored
Add Math.multiplyHigh, unsignedMultiplyHigh and P-256 Montgomery multiply intrinsics (#28)
1 parent 80b94d8 commit 06cb8a3

3 files changed

Lines changed: 106 additions & 6 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ Node, which is how the tests run.
4949
- `src/natives/` JS implementations of JDK native methods, by package;
5050
`java2d*.ts` port libawt's Java2D loops and must match HotSpot's pixels;
5151
`font*.ts` are the font natives (scaler, fontconfig, layout) over one TrueType font;
52-
`crypto.ts` the SHA, AES and BigInteger methods HotSpot replaces with intrinsics
52+
`crypto.ts` the SHA, AES, BigInteger and P-256 field methods HotSpot replaces with intrinsics
5353
- `src/sockets.ts` sockets (`Sock`, POSIX readiness) and the in-VM loopback backend;
5454
`src/net-node.ts` host sockets, DNS and interfaces for Node
5555
- `src/node.ts` Node entry, over `build/jdk` or, built as `dist/node.js`, the

‎src/natives/crypto.ts‎

Lines changed: 68 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
// The methods HotSpot replaces with intrinsics for SHA digests, AES blocks
2-
// and BigInteger arithmetic. As bytecode they run on Java longs, which are JS
3-
// BigInts here, so a 64-bit step allocates; these do the same work on
4-
// numbers, or on one BigInt for a whole multiplication.
1+
// The methods HotSpot replaces with intrinsics for SHA digests, AES blocks,
2+
// BigInteger and elliptic-curve field arithmetic. As bytecode they run on Java
3+
// longs, which are JS BigInts here, so a 64-bit step allocates; these do the
4+
// same work on numbers, or in far fewer BigInt steps.
55

66
import type { JArray, JObject } from "../runtime.ts";
77
import type { JThread } from "../thread.ts";
@@ -13,6 +13,7 @@ const SHA2 = "sun/security/provider/SHA2";
1313
const SHA5 = "sun/security/provider/SHA5";
1414
const BI = "java/math/BigInteger";
1515
const AES = "com/sun/crypto/provider/AESCrypt";
16+
const P256 = "sun/security/util/math/intpoly/MontgomeryIntegerPolynomialP256";
1617

1718
// the `state` field's slot in each digest class
1819
const stateSlots = new WeakMap<JVM, Map<string, number>>();
@@ -260,7 +261,70 @@ function aesEncrypt(t: JThread, self: JObject, inp: Int8Array, i: number, out: I
260261
aesLast(out, o + 12, S, t3, t0, t1, t2, K[k + 3]);
261262
}
262263

264+
// MontgomeryIntegerPolynomialP256.mult: r = a * b * 2^-260 mod p over five
265+
// 52-bit limbs, step for step as the Java code, whose limbs are below 2^52
266+
// (HotSpot's x64 intrinsic reads only those bits too). Every value stays
267+
// below 2^63 until the final subtraction, so exact BigInt steps give its
268+
// 64-bit results without wrapping.
269+
const LIMB = 0xfffffffffffffn;
270+
const P256_MOD = [0xfffffffffffffn, 0xfffffffffffn, 0n, 0x1000000000n, 0xffffffff0000n];
271+
const d = [0n, 0n, 0n, 0n, 0n], dd = [0n, 0n, 0n, 0n, 0n], c = Array<bigint>(9).fill(0n);
272+
273+
function p256Mult(av: BigInt64Array, bv: BigInt64Array, r: BigInt64Array) {
274+
const a0 = av[0] & LIMB, a1 = av[1] & LIMB, a2 = av[2] & LIMB, a3 = av[3] & LIMB, a4 = av[4] & LIMB;
275+
const b = [bv[0] & LIMB, bv[1] & LIMB, bv[2] & LIMB, bv[3] & LIMB, bv[4] & LIMB];
276+
const a = [a0, a1, a2, a3, a4];
277+
for (let i = 0; i < 5; i++) {
278+
for (let j = 0; j < 5; j++) {
279+
const p = a[i] * b[j];
280+
d[j] = p & LIMB;
281+
dd[j] = p >> 52n;
282+
}
283+
// row i reduces out column i: add it, then the multiple of p that clears it
284+
if (i > 0) d[0] += c[i];
285+
const n = d[0] & LIMB;
286+
for (let j = 0; j < 5; j++) {
287+
const q = n * P256_MOD[j];
288+
dd[j] += q >> 52n;
289+
d[j] += q & LIMB;
290+
}
291+
if (i < 4) {
292+
c[i + 1] = (i === 0 ? 0n : c[i + 1]) + d[1] + dd[0] + (d[0] >> 52n);
293+
for (let j = 2; j < 5; j++) c[i + j] = (i === 0 ? 0n : c[i + j]) + d[j] + dd[j - 1];
294+
c[i + 5] = dd[4];
295+
}
296+
}
297+
// the last row carries through
298+
let c5 = c[5] + d[1] + dd[0] + (d[0] >> 52n);
299+
let c6 = c[6] + d[2] + dd[1] + (c5 >> 52n);
300+
let c7 = c[7] + d[3] + dd[2] + (c6 >> 52n);
301+
let c8 = c[8] + d[4] + dd[3] + (c7 >> 52n);
302+
const c9 = dd[4] + (c8 >> 52n);
303+
c5 &= LIMB; c6 &= LIMB; c7 &= LIMB; c8 &= LIMB;
304+
// subtract p once; keep the difference unless it went negative
305+
let c0 = c5 - P256_MOD[0];
306+
let c1 = c6 - P256_MOD[1] + (c0 >> 52n);
307+
c0 &= LIMB;
308+
let c2 = c7 - P256_MOD[2] + (c1 >> 52n);
309+
c1 &= LIMB;
310+
let c3 = c8 - P256_MOD[3] + (c2 >> 52n);
311+
c2 &= LIMB;
312+
const c4 = c9 - P256_MOD[4] + (c3 >> 52n);
313+
c3 &= LIMB;
314+
if (c4 < 0n) {
315+
r[0] = c5; r[1] = c6; r[2] = c7; r[3] = c8; r[4] = c9;
316+
} else {
317+
r[0] = c0; r[1] = c1; r[2] = c2; r[3] = c3; r[4] = c4;
318+
}
319+
}
320+
263321
export const intrinsics: Natives = {
322+
"java/lang/Math.multiplyHigh(JJ)J": (_t, [x, y]) => ((x as bigint) * (y as bigint)) >> 64n,
323+
"java/lang/Math.unsignedMultiplyHigh(JJ)J": (_t, [x, y]) =>
324+
BigInt.asIntN(64, (BigInt.asUintN(64, x as bigint) * BigInt.asUintN(64, y as bigint)) >> 64n),
325+
[`${P256}.mult([J[J[J)V`]: (_t, [, a, b, r]) =>
326+
p256Mult((a as JArray).a as BigInt64Array, (b as JArray).a as BigInt64Array, (r as JArray).a as BigInt64Array),
327+
264328
[`${AES}.implEncryptBlock([BI[BI)V`]: (t, [self, inp, i, out, o]) =>
265329
aesEncrypt(t, self, (inp as JArray).a as Int8Array, i, (out as JArray).a as Int8Array, o),
266330

‎test/java/CryptoMath.java‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
import java.math.BigInteger;
2+
import java.security.KeyPair;
23
import java.security.KeyPairGenerator;
4+
import java.security.Signature;
35
import java.security.MessageDigest;
46
import java.security.SecureRandom;
57
import java.security.interfaces.RSAPrivateCrtKey;
68
import java.util.HexFormat;
79
import java.util.Arrays;
810
import javax.crypto.Cipher;
11+
import javax.crypto.KeyAgreement;
912
import javax.crypto.Mac;
1013
import javax.crypto.spec.IvParameterSpec;
1114
import javax.crypto.spec.SecretKeySpec;
1215

13-
// SHA digests, AES and BigInteger arithmetic, at sizes that reach their intrinsics.
16+
// SHA digests, AES, BigInteger and P-256 arithmetic, at sizes that reach their intrinsics.
1417
public class CryptoMath {
1518
static final HexFormat HEX = HexFormat.of();
1619

@@ -66,6 +69,39 @@ public static void main(String[] args) throws Exception {
6669
RSAPrivateCrtKey k = (RSAPrivateCrtKey) kpg.generateKeyPair().getPrivate();
6770
System.out.println("rsa " + hash(k.getModulus()) + " " + hash(k.getPrivateExponent()));
6871
System.out.println("prime " + BigInteger.probablePrime(512, rnd).bitLength() + " " + new BigInteger("1000000007").isProbablePrime(50));
72+
73+
long[] edges = {0, 1, -1, 2, Long.MIN_VALUE, Long.MAX_VALUE, 0xffffffffL, 1L << 32, -(1L << 32), 0x123456789abcdefL};
74+
long hi = 0, uhi = 0;
75+
for (long x : edges) for (long y : edges) {
76+
hi = hi * 31 + Math.multiplyHigh(x, y);
77+
uhi = uhi * 31 + Math.unsignedMultiplyHigh(x, y);
78+
}
79+
System.out.println("multiplyHigh " + hi + " " + uhi);
80+
81+
// P-256 key pairs, agreement and signatures, all from seeded randomness
82+
KeyPairGenerator ec = KeyPairGenerator.getInstance("EC");
83+
SecureRandom ecRnd = SecureRandom.getInstance("SHA1PRNG");
84+
ecRnd.setSeed(11);
85+
ec.initialize(256, ecRnd);
86+
KeyPair alice = ec.generateKeyPair(), bob = ec.generateKeyPair();
87+
KeyAgreement ka = KeyAgreement.getInstance("ECDH");
88+
ka.init(alice.getPrivate());
89+
ka.doPhase(bob.getPublic(), true);
90+
byte[] shared = ka.generateSecret();
91+
ka.init(bob.getPrivate());
92+
ka.doPhase(alice.getPublic(), true);
93+
System.out.println("ecdh " + HEX.formatHex(shared, 0, 8) + " " + Arrays.equals(shared, ka.generateSecret()));
94+
Signature sign = Signature.getInstance("SHA256withECDSA");
95+
sign.initSign(alice.getPrivate(), ecRnd);
96+
sign.update(data);
97+
byte[] sig = sign.sign();
98+
Signature verify = Signature.getInstance("SHA256withECDSA");
99+
verify.initVerify(alice.getPublic());
100+
verify.update(data);
101+
boolean good = verify.verify(sig);
102+
verify.initVerify(bob.getPublic());
103+
verify.update(data);
104+
System.out.println("ecdsa " + hash(new BigInteger(1, sig)) + " " + good + " " + verify.verify(sig));
69105
}
70106

71107
static String hash(BigInteger x) throws Exception {

0 commit comments

Comments
 (0)