Skip to content

Commit

Permalink
Fix regression in x25519 (legacy) key generation: store clamped secre…
Browse files Browse the repository at this point in the history
…t scalar

Fixes regression from changes in openpgpjs#1782, as the spec mandates that
legacy x25519 store the secret scalar already clamped.
Keys generated using v6.0.0-beta.3 are still expected to be functional,
since the scalar is to be clamped before computing the ECDH shared secret.
  • Loading branch information
larabr committed Sep 9, 2024
1 parent a3839f6 commit 8d80333
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/crypto/public_key/elliptic/oid_curves.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,11 @@ class CurveWithOID {
case 'node':
return nodeGenKeyPair(this.name);
case 'curve25519Legacy': {
// the private key must be stored in big endian and already clamped: https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-13.html#section-5.5.5.6.1.1-3
const { k, A } = await ecdhXGenerate(enums.publicKey.x25519);
const privateKey = k.slice().reverse();
privateKey[0] = (privateKey[0] & 127) | 64;
privateKey[31] &= 248;
const publicKey = util.concatUint8Array([new Uint8Array([this.wireFormatLeadingByte]), A]);
return { publicKey, privateKey };
}
Expand Down
11 changes: 11 additions & 0 deletions test/crypto/ecdh.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import x25519 from '@openpgp/tweetnacl';
import sinon from 'sinon';
import { use as chaiUse, expect } from 'chai';
import chaiAsPromised from 'chai-as-promised'; // eslint-disable-line import/newline-after-import
Expand Down Expand Up @@ -67,6 +68,16 @@ export default () => describe('ECDH key exchange @lightweight', function () {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
]);

it('Generated legacy x25519 secret scalar is stored clamped', async function () {
const curve = new elliptic_curves.CurveWithOID(openpgp.enums.curve.curve25519Legacy);
const { privateKey, publicKey } = await curve.genKeyPair();
const clampedKey = privateKey.slice();
clampedKey[0] = (clampedKey[0] & 127) | 64;
clampedKey[31] &= 248;
expect(privateKey).to.deep.equal(clampedKey);
const { publicKey: expectedPublicKey } = x25519.box.keyPair.fromSecretKey(privateKey.slice().reverse());
expect(publicKey.subarray(1)).to.deep.equal(expectedPublicKey);
});
it('Invalid curve oid', function (done) {
expect(decrypt_message(
'', 2, 7, [], [], [], [], []
Expand Down

0 comments on commit 8d80333

Please sign in to comment.