Skip to content

Instantly share code, notes, and snippets.

@bryandh
Created November 12, 2018 09:51
Show Gist options
  • Save bryandh/21edc8dbf0d170278a26a75d5969213a to your computer and use it in GitHub Desktop.
Save bryandh/21edc8dbf0d170278a26a75d5969213a to your computer and use it in GitHub Desktop.
Decryption using JSEncrypt
import { JSEncrypt } from 'jsencrypt';
export class CryptographyUtils {
private private_key = '-----BEGIN RSA PRIVATE KEY-----' +
'MIICXQIBAAKBgQDg2FPu8j317CkARCRDBXDp8Ury7W+VPjqrRhwTaqKGGLXeT2u/' +
'Ne13R9lNIhdWP/qbS8yI5RfPElzZ8PnXI8ihv4ij8bd9cdy/mDVeI+venwIDAQAB' +
'AoGBAKjYCn9/DaRlCY0XnptttJMZDY1LW+WY63m+lkrGYvGMENa2kVTdXp3tMI1d' +
'nGT+PTZAXYl52BAA7wYt3208q9PwTd7Cb7WwEu24QtsDFbkcm8RD7jntSgECQGN3' +
'sEYqeb+sPrSwuHx0/WcCQQCQ0o3W+tX4wTnZCp+ReqPHzzE7uSkcTzg7AEVSsjlI' +
'kgmaAt3txI7oABf8nDdi29s1o8KDV8UzQn+Jh9LXYdxs' +
'-----END RSA PRIVATE KEY-----'; // Set your own key here, this key is not real
/**
* Decrypts the encoded string with the private key.
* @param cipher URL-escaped, base64'ed encoded string ('cipher').
*/
public decrypt(cipher: string): string {
const decrypter = new JSEncrypt();
decrypter.setPrivateKey(this.private_key);
const response = decrypter.decrypt(cipher);
return response;
}
public decipher(cipher: string): ICipherAccessScope {
let decrypted = this.decrypt(cipher);
// If the cipher cannot be decrypted, return null as we do not allow an accessible scope
if (!decrypted) return null;
const decryptedSplit = decrypted.split('|');
const scope: ICipherAccessScope = {
companyId: decryptedSplit[0],
username: decryptedSplit[1],
installationId: decryptedSplit[2]
};
return scope;
}
}
export interface ICipherAccessScope {
companyId: string;
username: string;
installationId: string;
}
export interface ICipherAccess {
access_token: string;
expires_at: number;
cipher: string;
}
export interface ICipherAuth {
token: string;
expiresAt: number;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment