Skip to content

Instantly share code, notes, and snippets.

@4skl
Created September 21, 2024 10:39
Show Gist options
  • Save 4skl/3e2beed0c7c2f75af073997fcd2039eb to your computer and use it in GitHub Desktop.
Save 4skl/3e2beed0c7c2f75af073997fcd2039eb to your computer and use it in GitHub Desktop.
Small openpgp wrapper / polyfill to make ecc work in expo react native
import * as openpgp from './openpgp.mjs';
import * as Crypto from 'expo-crypto';
if (typeof global.crypto === 'undefined') {
global.crypto = {
getRandomValues: (array) => {
const randomBytes = Crypto.getRandomBytes(array.length);
array.set(randomBytes);
},
};
}
const TextEncodingPolyfill = require('text-encoding');
Object.assign(global, {
TextEncoder: TextEncodingPolyfill.TextEncoder,
TextDecoder: TextEncodingPolyfill.TextDecoder,
});
export const generateKeypair = async () => {
try {
const { privateKey, publicKey } = await openpgp.generateKey({
type: 'ecc',
curve: 'p256',
userIDs: [{ name: 'User', email: '[email protected]' }],
});
return { privateKey, publicKey };
} catch (error) {
console.error('Error generating keypair:', error);
return null;
}
};
export const encryptMessage = async (publicKey, message) => {
try {
const encrypted = await openpgp.encrypt({
message: await openpgp.createMessage({ text: message }),
encryptionKeys: (await openpgp.readKey({ armoredKey: publicKey })),
});
return encrypted;
} catch (error) {
console.error('Error encrypting message:', error);
return null;
}
};
export const encryptAndSignMessage = async (publicKey, privateKey, message) => {
try {
const encrypted = await openpgp.encrypt({
message: await openpgp.createMessage({ text: message }),
encryptionKeys: (await openpgp.readKey({ armoredKey: publicKey })),
signingKeys: (await openpgp.readKey({ armoredKey: privateKey })),
});
return encrypted;
} catch (error) {
console.error('Error encrypting message:', error);
return null;
}
};
export const decryptMessage = async (privateKey, encrypted) => {
try {
const decrypted = await openpgp.decrypt({
message: await openpgp.readMessage({ armoredMessage: encrypted }),
decryptionKeys: (await openpgp.readKey({ armoredKey: privateKey })),
});
return decrypted;
} catch (error) {
console.error('Error decrypting message:', error);
return null;
}
};
export const decryptAndVerifyMessage = async (privateKey, publicKey, encrypted) => {
try {
const decrypted = await openpgp.decrypt({
message: await openpgp.readMessage({ armoredMessage: encrypted }),
verificationKeys: (await openpgp.readKey({ armoredKey: publicKey })),
decryptionKeys: (await openpgp.readKey({ armoredKey: privateKey })),
});
return decrypted;
} catch (error) {
console.error('Error decrypting message:', error);
return null;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment