Skip to content

Commit 784df7d

Browse files
committed
LMS: LMSContext takes over what consumes its digest - outputQ writes Q in place (getQ removed), collectQ sizes it for the checksum, and calculateKc/generateSignature replace the LM_OTS and LMSEngine statics that reached into it; LM_OTS gains appendCksm and calculateKc is split from lm_ots_validate_signature_calculate; LMSEngine.verifySignature is rewritten around the node parity with the path guard ahead of each step
1 parent bf9d99c commit 784df7d

4 files changed

Lines changed: 143 additions & 84 deletions

File tree

‎core/src/main/java/org/bouncycastle/crypto/signers/lms/LMSContext.java‎

Lines changed: 60 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package org.bouncycastle.crypto.signers.lms;
22

33
import org.bouncycastle.crypto.Digest;
4+
import org.bouncycastle.crypto.OutputLengthException;
5+
import org.bouncycastle.crypto.params.LMOtsParameters;
46
import org.bouncycastle.crypto.params.LMSigParameters;
57

68
/**
@@ -51,15 +53,67 @@ byte[] getC()
5153
return C;
5254
}
5355

54-
byte[] getQ()
56+
/**
57+
* Write Q, the message hash, to the given buffer. The context cannot be used afterwards.
58+
* <p>
59+
* A caller that goes on to append the LM-OTS checksum needs two bytes beyond the value written here.
60+
* </p>
61+
*
62+
* @param output the byte array Q is to be copied into.
63+
* @param outOff the offset into the byte array Q is to start at.
64+
* @return the number of bytes written.
65+
*/
66+
public int outputQ(byte[] output, int outOff)
67+
{
68+
Digest digest = this.digest;
69+
int qLen = digest.getDigestSize();
70+
if (outOff > output.length - qLen)
71+
{
72+
throw new OutputLengthException("output buffer too short");
73+
}
74+
75+
digest.doFinal(output, outOff);
76+
this.digest = null;
77+
return qLen;
78+
}
79+
80+
/**
81+
* Take Q, the message hash, in the buffer shape the LM-OTS chaining expects: the N bytes of Q,
82+
* followed by room for the two bytes of {@link LM_OTS#cksm(byte[], int, LMOtsParameters)} that the
83+
* caller appends (RFC 8554 sec. 4.5). The context cannot be used afterwards.
84+
*/
85+
byte[] collectQ(LMOtsParameters otsParameters)
86+
{
87+
byte[] Q = new byte[otsParameters.getN() + 2];
88+
outputQ(Q, 0);
89+
return Q;
90+
}
91+
92+
/**
93+
* Kc, the LM-OTS public key the signature this context carries computes for itself over the
94+
* message absorbed into it. The context cannot be used afterwards.
95+
*/
96+
byte[] calculateKc()
97+
{
98+
// Either an LMS signature, whose LM-OTS part this verifies, or a bare LM-OTS one
99+
LMOtsSignature otsSignature = (signature instanceof LMSSignature)
100+
? ((LMSSignature)signature).getOtsSignature()
101+
: (LMOtsSignature)signature;
102+
103+
return LM_OTS.calculateKc(publicKey, otsSignature, collectQ(publicKey.getParameter()));
104+
}
105+
106+
/**
107+
* Complete the LMS signature of the one-time key this context was opened on, over the message
108+
* absorbed into it (RFC 8554 sec. 5.4.1). The context cannot be used afterwards.
109+
*/
110+
LMSSignature generateSignature()
55111
{
56-
byte[] Q = new byte[LM_OTS.MAX_HASH + 2];
112+
byte[] Q = collectQ(key.getParameter());
57113

58-
digest.doFinal(Q, 0);
59-
60-
digest = null;
114+
LMOtsSignature otsSignature = LM_OTS.lm_ots_generate_signature(key, Q, C);
61115

62-
return Q;
116+
return new LMSSignature(key.getQ(), otsSignature, sigParams, path);
63117
}
64118

65119
byte[][] getPath()

‎core/src/main/java/org/bouncycastle/crypto/signers/lms/LMSEngine.java‎

Lines changed: 60 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -124,10 +124,7 @@ public static LMSContext withSignedPublicKeys(LMSContext context, LMSSignature[]
124124
*/
125125
public static LMSSignature generateSign(LMSContext context)
126126
{
127-
// Step 1.
128-
LMOtsSignature ots_signature = LM_OTS.lm_ots_generate_signature(context.getPrivateKey(), context.getQ(), context.getC());
129-
130-
return new LMSSignature(context.getPrivateKey().getQ(), ots_signature, context.getSigParams(), context.getPath());
127+
return context.generateSignature();
131128
}
132129

133130
/**
@@ -181,30 +178,32 @@ public static LMSContext generateVerifyContext(LMSPublicKeyParameters publicKey,
181178
* and the final comparison saw to that - but both are work the specification says to refuse up
182179
* front.
183180
*/
184-
static LMSContext generateVerifyContext(LMSPublicKeyParameters publicKey, LMSSignature S)
181+
static LMSContext generateVerifyContext(LMSPublicKeyParameters publicKey, LMSSignature signature)
185182
{
186183
LMSigParameters sigParameters = publicKey.getSigParameters();
187-
if (S.getParameter().getType() != sigParameters.getType())
184+
if (signature.getParameter().getType() != sigParameters.getType())
188185
{
189186
throw new IllegalArgumentException("lms type from lms signature does not match lms type" +
190187
" from public key");
191188
}
192189

193-
int q = S.getQ();
190+
int q = signature.getQ();
194191
if (q < 0 || q >= (1 << sigParameters.getH()))
195192
{
196193
throw new IllegalArgumentException("lms leaf number q from lms signature is outside the" +
197194
" public key's tree");
198195
}
199196

200197
int ots_typecode = publicKey.getOtsParameters().getType();
201-
if (S.getOtsSignature().getType().getType() != ots_typecode)
198+
if (signature.getOtsSignature().getType().getType() != ots_typecode)
202199
{
203200
throw new IllegalArgumentException("ots type from lsm signature does not match ots" +
204201
" signature type from embedded ots signature");
205202
}
206203

207-
return new LMOtsPublicKey(LMOtsParameters.getParametersForType(ots_typecode), publicKey.getI(), S.getQ(), null).createOtsContext(S);
204+
LMOtsParameters otsParameters = LMOtsParameters.getParametersForType(ots_typecode);
205+
LMOtsPublicKey otsPublicKey = new LMOtsPublicKey(otsParameters, publicKey.getI(), q, null);
206+
return otsPublicKey.createOtsContext(signature);
208207
}
209208

210209
/**
@@ -213,65 +212,72 @@ static LMSContext generateVerifyContext(LMSPublicKeyParameters publicKey, LMSSig
213212
*/
214213
public static boolean verifySignature(LMSPublicKeyParameters publicKey, LMSContext context)
215214
{
216-
LMSSignature S = (LMSSignature)context.getSignature();
217-
LMSigParameters sigParameters = S.getParameter();
218-
int h = sigParameters.getH();
219-
byte[][] path = S.getY();
220-
byte[] Kc = LM_OTS.lm_ots_validate_signature_calculate(context);
221-
// Step 4
222-
// node_num = 2^h + q
223-
int node_num = (1 << h) + S.getQ();
224-
225-
// tmp = H(I || u32str(node_num) || u16str(D_LEAF) || Kc)
215+
Object contextSignature = context.getSignature();
216+
217+
// Guaranteed by every route the library has to a verification context, all of which reach
218+
// LMOtsPublicKey.createOtsContext with a decoded LMS signature. No public path to mis-construction.
219+
if (!(contextSignature instanceof LMSSignature))
220+
{
221+
throw new IllegalStateException("context was not created from an LMS signature");
222+
}
223+
224+
LMSSignature signature = (LMSSignature)contextSignature;
225+
LMSigParameters sigParameters = signature.getParameter();
226+
byte[][] path = signature.getY();
227+
228+
// Kc, the LM-OTS public key the signature computes for itself
229+
byte[] Kc = context.calculateKc();
230+
226231
byte[] I = publicKey.getI();
227-
Digest H = DigestUtil.getDigest(sigParameters);
228-
byte[] tmp = new byte[H.getDigestSize()];
232+
Digest digest = DigestUtil.getDigest(sigParameters);
229233

230-
H.update(I, 0, I.length);
231-
LmsUtils.u32str(node_num, H);
232-
LmsUtils.u16str(D_LEAF, H);
233-
H.update(Kc, 0, Kc.length);
234-
H.doFinal(tmp, 0);
234+
// The node the walk is at, and the hash it has computed for it: the leaf of the one-time key that
235+
// signed, then each parent in turn, leaving the root the signature claims.
236+
// RFC 8554 sec. 5.4.2 step 4: node_num = 2^h + q, tmp = H(I || u32str(node_num) || u16str(D_LEAF) || Kc)
237+
int node_num = (1 << sigParameters.getH()) + signature.getQ();
238+
byte[] nodeHash = new byte[digest.getDigestSize()];
239+
240+
digest.update(I, 0, I.length);
241+
LmsUtils.u32str(node_num, digest);
242+
LmsUtils.u16str(D_LEAF, digest);
243+
digest.update(Kc, 0, Kc.length);
244+
digest.doFinal(nodeHash, 0);
235245

236246
int i = 0;
237247

238248
while (node_num > 1)
239249
{
240-
if ((node_num & 1) == 1)
241-
{
242-
// is odd
243-
H.update(I, 0, I.length);
244-
LmsUtils.u32str(node_num / 2, H);
245-
LmsUtils.u16str(D_INTR, H);
246-
H.update(path[i], 0, path[i].length);
247-
H.update(tmp, 0, tmp.length);
248-
H.doFinal(tmp, 0);
249-
}
250-
else
251-
{
252-
H.update(I, 0, I.length);
253-
LmsUtils.u32str(node_num / 2, H);
254-
LmsUtils.u16str(D_INTR, H);
255-
H.update(tmp, 0, tmp.length);
256-
H.update(path[i], 0, path[i].length);
257-
H.doFinal(tmp, 0);
258-
}
259-
node_num = node_num / 2;
260-
i++;
261-
// these two can get out of sync with an invalid signature, we'll
262-
// try and fail gracefully
263-
if (i == path.length && node_num > 1)
250+
// The path and the node count can get out of sync with an invalid signature, so fail gracefully
251+
// rather than index past the path the signature carries.
252+
if (i >= path.length)
264253
{
265254
return false;
266255
}
256+
257+
byte[] siblingHash = path[i++];
258+
259+
// The node's parity decides which side its sibling from the path goes on - left for an odd node,
260+
// right for an even one - while the hash itself is over the parent (RFC 8554 sec. 5.4.2 step 4).
261+
boolean isOdd = (node_num & 1) == 1;
262+
node_num >>= 1;
263+
264+
byte[] left = isOdd ? siblingHash : nodeHash;
265+
byte[] right = isOdd ? nodeHash : siblingHash;
266+
267+
digest.update(I, 0, I.length);
268+
LmsUtils.u32str(node_num, digest);
269+
LmsUtils.u16str(D_INTR, digest);
270+
digest.update(left, 0, left.length);
271+
digest.update(right, 0, right.length);
272+
digest.doFinal(nodeHash, 0);
267273
}
268-
byte[] Tc = tmp;
269-
return Arrays.constantTimeAreEqual(publicKey.getT1(), Tc);
274+
275+
return Arrays.constantTimeAreEqual(publicKey.getT1(), nodeHash);
270276
}
271277

272-
static boolean verifySignature(LMSPublicKeyParameters publicKey, LMSSignature S, byte[] message)
278+
static boolean verifySignature(LMSPublicKeyParameters publicKey, LMSSignature signature, byte[] message)
273279
{
274-
LMSContext context = generateVerifyContext(publicKey, S);
280+
LMSContext context = generateVerifyContext(publicKey, signature);
275281

276282
LmsUtils.byteArray(message, context);
277283

‎core/src/main/java/org/bouncycastle/crypto/signers/lms/LM_OTS.java‎

Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ class LM_OTS
1313
private static final int ITER_PREV = 23;
1414
private static final int ITER_J = 22;
1515
static final int SEED_RANDOMISER_INDEX = ~2;
16-
static final int MAX_HASH = 32;
1716

1817
static final short D_MESG = (short)0x8181;
1918

@@ -46,6 +45,16 @@ static int cksm(byte[] S, int sLen, LMOtsParameters parameters)
4645
return sum << parameters.getLs();
4746
}
4847

48+
/**
49+
* Append the checksum of the first n bytes of Q to them, as the two bytes the chains after the
50+
* message digest carry (RFC 8554 sec. 4.5).
51+
*/
52+
private static void appendCksm(byte[] Q, int n, LMOtsParameters parameters)
53+
{
54+
int cs = cksm(Q, n, parameters);
55+
Pack.shortToBigEndian((short)cs, Q, n);
56+
}
57+
4958

5059
public static byte[] lms_ots_generatePublicKey(LMOtsParameters parameter, byte[] I, int q, byte[] masterSecret)
5160
{
@@ -112,7 +121,7 @@ public static LMOtsSignature lm_ots_generate_signature(LMSigParameters sigParams
112121

113122
LmsUtils.byteArray(message, 0, message.length, qCtx);
114123

115-
return lm_ots_generate_signature(privateKey, qCtx.getQ(), qCtx.getC());
124+
return lm_ots_generate_signature(privateKey, qCtx.collectQ(privateKey.getParameter()), qCtx.getC());
116125
}
117126

118127
public static LMOtsSignature lm_ots_generate_signature(LMOtsPrivateKey privateKey, byte[] Q, byte[] C)
@@ -129,9 +138,7 @@ public static LMOtsSignature lm_ots_generate_signature(LMOtsPrivateKey privateKe
129138

130139
SeedDerive derive = privateKey.getDerivationFunction();
131140

132-
int cs = cksm(Q, n, parameter);
133-
Q[n] = (byte)((cs >>> 8) & 0xFF);
134-
Q[n + 1] = (byte)cs;
141+
appendCksm(Q, n, parameter);
135142

136143
byte[] tmp = Composer.compose().bytes(privateKey.getI()).u32str(privateKey.getQ()).padUntil(0, ITER_PREV + n).build();
137144

@@ -176,32 +183,18 @@ public static byte[] lm_ots_validate_signature_calculate(LMOtsPublicKey publicKe
176183

177184
LmsUtils.byteArray(message, ctx);
178185

179-
return lm_ots_validate_signature_calculate(ctx);
186+
return ctx.calculateKc();
180187
}
181188

182-
public static byte[] lm_ots_validate_signature_calculate(LMSContext context)
189+
static byte[] calculateKc(LMOtsPublicKey publicKey, LMOtsSignature signature, byte[] Q)
183190
{
184-
LMOtsPublicKey publicKey = context.getPublicKey();
185191
LMOtsParameters parameter = publicKey.getParameter();
186-
Object sig = context.getSignature();
187-
LMOtsSignature signature;
188-
if (sig instanceof LMSSignature)
189-
{
190-
signature = ((LMSSignature)sig).getOtsSignature();
191-
}
192-
else
193-
{
194-
signature = (LMOtsSignature)sig;
195-
}
196192

197193
int n = parameter.getN();
198194
int w = parameter.getW();
199195
int p = parameter.getP();
200-
byte[] Q = context.getQ();
201196

202-
int cs = cksm(Q, n, parameter);
203-
Q[n] = (byte)((cs >>> 8) & 0xFF);
204-
Q[n + 1] = (byte)cs;
197+
appendCksm(Q, n, parameter);
205198

206199
byte[] I = publicKey.getI();
207200
int q = publicKey.getQ();

‎core/src/test/java/org/bouncycastle/crypto/signers/lms/LMOtsTests.java‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,10 @@ public void testPrivateKeyRound()
4343

4444
ctx.update(ms, 0, ms.length);
4545

46-
LMOtsSignature sig = LM_OTS.lm_ots_generate_signature(privateKey, ctx.getQ(), ctx.getC());
46+
byte[] Q = new byte[parameter.getN() + 2];
47+
ctx.outputQ(Q, 0);
48+
49+
LMOtsSignature sig = LM_OTS.lm_ots_generate_signature(privateKey, Q, ctx.getC());
4750
assertTrue(LM_OTS.lm_ots_validate_signature(publicKey, sig, ms, false));
4851

4952
// Recreate signature
@@ -112,7 +115,10 @@ public void testContextSingleUse()
112115

113116
ctx.update(ms, 0, ms.length);
114117

115-
LMOtsSignature sig = LM_OTS.lm_ots_generate_signature(privateKey, ctx.getQ(), ctx.getC());
118+
byte[] Q = new byte[parameter.getN() + 2];
119+
ctx.outputQ(Q, 0);
120+
121+
LMOtsSignature sig = LM_OTS.lm_ots_generate_signature(privateKey, Q, ctx.getC());
116122
assertTrue(LM_OTS.lm_ots_validate_signature(publicKey, sig, ms, false));
117123

118124
try

0 commit comments

Comments
 (0)