Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def generate_all_keys(custodia_conf):
parser = configparser.ConfigParser(
interpolation=configparser.ExtendedInterpolation()
)
with open(custodia_conf) as f:
parser.read_file(f)
filename = parser.get('store:encgen', 'master_key')
key = jwk.JWK(generate='oct', size=256)
with open(filename, 'w+') as keyfile:
keyfile.write(key.export())
store = SqliteStore(parser, 'store:simple')
srv_kid = "srvkid"
cli_kid = "clikid"
ss_key = jwk.JWK(generate='RSA', kid=srv_kid, use="sig")
se_key = jwk.JWK(generate='RSA', kid=srv_kid, use="enc")
store.set('kemkeys/sig/%s' % srv_kid, ss_key.export())
store.set('kemkeys/enc/%s' % srv_kid, se_key.export())
cs_key = jwk.JWK(generate='RSA', kid=cli_kid, use="sig")
ce_key = jwk.JWK(generate='RSA', kid=cli_kid, use="enc")
store.set('kemkeys/sig/%s' % cli_kid, cs_key.export_public())
store.set('kemkeys/enc/%s' % cli_kid, ce_key.export_public())
801xAoGADQB84MJe/X8xSUZQzpn2KP/yZ7C517qDJjComGe3mjVxTIT5XAaa1tLy\n\
T4mvpSeYDJkBD8Hxr3fB1YNDWNbgwrNPGZnUTBNhxIsNLPnV8WySiW57LqVXlggH\n\
vjFmyDdU5Hh6ma4q+BeAqbXZSJz0cfkBcBLCSe2gIJ/QJ3YJVQI= \n\
-----END RSA PRIVATE KEY-----"
pub_pem = "-----BEGIN PUBLIC KEY----- \n\
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4qiw8PWs7PpnnC2BUEoD\n\
RcwXF8pq8XT1/3Hc3cuUJwX/otNefr/Bomr3dtM0ERLN3DrepCXvuzEU5FcJVDUB\n\
3sI+pFtjjLBXD/zJmuL3Afg91J9p79+Dm+43cR6wuKywVJx5DJIdswF6oQDDzhwu\n\
89d2V5x02aXB9LqdXkPwiO0eR5s/xHXgASl+hqDdVL9hLod3iGa9nV7cElCbcl8U\n\
VXNPJnQAfaiKazF+hCdl/syrIh0KCZ5opggsTJibo8qFXBmG4PkT5YbhHE11wYKI\n\
LwZFSvZ9iddRPQK3CtgFiBnXbVwU5t67tn9pMizHgypgsfBoeoyBrpTuc4egSCpj\n\
sQIDAQAB \n\
-----END PUBLIC KEY-----"
priv_key = JWK.from_pem(to_bytes_2and3(priv_pem))
pub_key = JWK.from_pem(to_bytes_2and3(pub_pem))
priv_keys = {
'HS256': {'default': JWK(kty='oct', k=base64url_encode('some random key'))},
'HS384': {'default': JWK(kty='oct', k=base64url_encode('another one'))},
'HS512': {'default': JWK(kty='oct', k=base64url_encode('keys keys keys!'))},
'RS256': {'python-jwt': priv_key},
'RS384': {'python-jwt': priv_key},
'RS512': {'python-jwt': priv_key},
'PS256': {'python-jwt': priv_key},
'PS384': {'python-jwt': priv_key},
'PS512': {'python-jwt': priv_key}
}
pub_keys = {
'HS256': {'default': priv_keys['HS256']['default']},
def spawn(cmd, parse_json):
""" run node command """
#pylint: disable=E1101
with lock:
p = Popen(["node", "-e", "fixtures=require('./test/fixtures');" + cmd],
stdout=PIPE, stderr=PIPE)
(stdout, stderr) = p.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
if p.returncode == 0:
return json_decode(stdout) if parse_json else stdout
raise Exception(stderr if stderr else ('exited with {}'.format(p.returncode)))
#pylint: enable=E1101
def _save_session(self, session_id, user_id, data, legacy=False):
raw_data = json.dumps(vars(data))
protected_header = {
'alg': 'dir',
'enc': 'A256GCM',
'kid': '1,1',
}
if legacy:
plaintext = base64url_encode(raw_data)
else:
plaintext = raw_data
jwe_token = jwe.JWE(
plaintext=plaintext,
protected=protected_header,
recipient=self.key
)
session_model = EQSession(
session_id,
user_id,
jwe_token.serialize(compact=True)
)
data_access.put(session_model)
def encrypt_data(self, data):
if isinstance(data, dict):
data = json.dumps(data)
protected_header = {
'alg': 'dir',
'enc': 'A256GCM',
'kid': '1,1',
}
data = snappy.compress(data)
jwe_token = jwe.JWE(
plaintext=data,
protected=protected_header,
recipient=self.key,
)
return jwe_token.serialize(compact=True)
def _save_legacy_state_data(self, user_id, data):
protected_header = {
'alg': 'dir',
'enc': 'A256GCM',
'kid': '1,1',
}
jwe_token = jwe.JWE(
plaintext=base64url_encode(data),
protected=protected_header,
recipient=self.storage.encrypter.key
)
legacy_state_data = json.dumps({'data': jwe_token.serialize(compact=True)})
questionnaire_state = QuestionnaireState(
user_id,
legacy_state_data,
self.LEGACY_DATA_STORE_VERSION
)
data_access.put(questionnaire_state)
def _store_keys(keystore, usage, keys):
name = os.path.join('kemkeys',
kem.KEY_USAGE_MAP[usage],
keys[usage]['kid'])
keystore.set(name, json_encode(keys[usage]), True)
def f(claims, alg, lifetime=None, expires=None, not_before=None):
""" generate token using node-jsjws """
now = datetime.utcnow()
return spawn(
"fixtures.generate({now}, {header}, {claims}, {expires}, {not_before}, {key})".format(
now=timegm(now.utctimetuple()),
header=json_encode({'alg': alg}),
claims=json_encode(claims),
expires=timegm(((now + lifetime) if lifetime else expires).utctimetuple()),
not_before=timegm((not_before or now).utctimetuple()),
key=json_encode(base64url_decode(json_decode(key.export())['k']) if key.is_symmetric else key.export_to_pem(True, None))),
False)
return f
def f(sjwt, iat_skew=timedelta()):
""" verify token using node-jsjws """
r = spawn(
"fixtures.verify({now}, {sjwt}, {iat_skew}, {key}, {alg})".format(
now=timegm(datetime.utcnow().utctimetuple()),
sjwt=json_encode(sjwt),
iat_skew=iat_skew.total_seconds(),
key=json_encode(base64url_decode(json_decode(key.export())['k']) if key.is_symmetric else key.export_to_pem()),
alg=json_encode(alg)),
True)
return tuple(r)
return f
def f(sjwt, iat_skew=timedelta()):
""" verify token using node-jsjws """
r = spawn(
"fixtures.verify({now}, {sjwt}, {iat_skew}, {key}, {alg})".format(
now=timegm(datetime.utcnow().utctimetuple()),
sjwt=json_encode(sjwt),
iat_skew=iat_skew.total_seconds(),
key=json_encode(base64url_decode(json_decode(key.export())['k']) if key.is_symmetric else key.export_to_pem()),
alg=json_encode(alg)),
True)
return tuple(r)
return f