Skip to content

Commit

Permalink
feat: derive public key
Browse files Browse the repository at this point in the history
  • Loading branch information
whilefoo committed Oct 23, 2023
1 parent 037830a commit 23eefbc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion static/keygen.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ <h1 class="title">Key Generator</h1>
<input type="text" class="form-control" id="privKey" />
</div>
<div class="mb-3">
<label for="pubKey" class="form-label">x25519_PUBLIC_KEY</label>
<label for="pubKey" class="form-label">x25519_PUBLIC_KEY (Optional if private key is supplied)</label>
<input type="text" class="form-control" id="pubKey" />
</div>
<div class="mb-3">
Expand Down
23 changes: 23 additions & 0 deletions static/scripts/key-generator/keygen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,24 @@ const sodiumKeyBox = async () => {

const sodiumEncryptedSeal = async () => {
const pubKey = document.querySelector("#pubKey") as HTMLInputElement;
const privKey = document.querySelector("#privKey") as HTMLInputElement;
const plainKey = document.querySelector("#plainKey") as HTMLInputElement;
const cipherKey = document.querySelector("#cipherKey") as HTMLInputElement;
try {
await _sodium.ready;
const sodium = _sodium;

if (!privKey.value && !pubKey.value) {
statusToggle("error", `Error: You need to enter either public or private key.`);
return;
}
if (!pubKey.value && privKey.value) {
// derive public key from private key
const binPriv = sodium.from_base64(privKey.value, sodium.base64_variants.URLSAFE_NO_PADDING);
const binPub = sodium.crypto_scalarmult_base(binPriv);
const output = sodium.to_base64(binPub, sodium.base64_variants.URLSAFE_NO_PADDING);
pubKey.value = output;
}
const binkey = sodium.from_base64(pubKey.value, sodium.base64_variants.URLSAFE_NO_PADDING);
const binsec = sodium.from_string(plainKey.value);
const encBytes = sodium.crypto_box_seal(binsec, binkey);
Expand All @@ -60,6 +72,17 @@ const sodiumOpenSeal = async () => {
await _sodium.ready;
const sodium = _sodium;

if (!privKey.value) {
statusToggle("error", `Error: You need to enter private key.`);
return;
}
if (!pubKey.value && privKey.value) {
// derive public key from private key
const binPriv = sodium.from_base64(privKey.value, sodium.base64_variants.URLSAFE_NO_PADDING);
const binPub = sodium.crypto_scalarmult_base(binPriv);
const output = sodium.to_base64(binPub, sodium.base64_variants.URLSAFE_NO_PADDING);
pubKey.value = output;
}
const binPub = sodium.from_base64(pubKey.value, sodium.base64_variants.URLSAFE_NO_PADDING);
const binPriv = sodium.from_base64(privKey.value, sodium.base64_variants.URLSAFE_NO_PADDING);
const binCipher = sodium.from_base64(cipherKey.value, sodium.base64_variants.URLSAFE_NO_PADDING);
Expand Down

0 comments on commit 23eefbc

Please sign in to comment.