Skip to content

Commit a7a7254

Browse files
committed
NTRU: Optimize S3ToBytes
1 parent 7acd73b commit a7a7254

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

core/src/main/java/org/bouncycastle/pqc/math/ntru/Polynomial.java

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -147,28 +147,33 @@ public byte[] s3ToBytes(int messageSize)
147147

148148
public void s3ToBytes(byte[] msg, int msgOff)
149149
{
150-
byte c;
150+
int degree = params.packDegree(), limit = degree - 5;
151151

152-
for (int i = 0; i < params.packDegree() / 5; i++)
152+
int i = 0;
153+
while (i <= limit)
153154
{
154-
c = (byte)(this.coeffs[5 * i + 4] & 255);
155-
c = (byte)(3 * c + this.coeffs[5 * i + 3] & 255);
156-
c = (byte)(3 * c + this.coeffs[5 * i + 2] & 255);
157-
c = (byte)(3 * c + this.coeffs[5 * i + 1] & 255);
158-
c = (byte)(3 * c + this.coeffs[5 * i + 0] & 255);
159-
msg[i + msgOff] = c;
155+
int c0 = (coeffs[i + 0] & 0xFF);
156+
int c1 = (coeffs[i + 1] & 0xFF) * 3;
157+
int c2 = (coeffs[i + 2] & 0xFF) * 9;
158+
int c3 = (coeffs[i + 3] & 0xFF) * 27;
159+
int c4 = (coeffs[i + 4] & 0xFF) * 81;
160+
161+
msg[msgOff++] = (byte)(c0 + c1 + c2 + c3 + c4);
162+
i += 5;
160163
}
161164

162-
// if 5 does not divide NTRU_N-1
163-
if (params.packDegree() > (params.packDegree() / 5) * 5)
165+
if (i < degree)
164166
{
165-
int i = params.packDegree() / 5;
166-
c = 0;
167-
for (int j = params.packDegree() - (5 * i) - 1; j >= 0; j--)
167+
int j = degree - 1;
168+
int c = coeffs[j] & 0xFF;
169+
170+
while (--j >= i)
168171
{
169-
c = (byte)(3 * c + this.coeffs[5 * i + j] & 255);
172+
c *= 3;
173+
c += coeffs[j] & 0xFF;
170174
}
171-
msg[i + msgOff] = c;
175+
176+
msg[msgOff++] = (byte)c;
172177
}
173178
}
174179

0 commit comments

Comments
 (0)