def set_conf(profile, username, password, hesperides_endpoint, response_format):
basic_auth = base64.b64encode(str.encode('%s:%s' % (username, password))).decode('UTF-8')
config = {'endpoint': hesperides_endpoint, 'format': response_format}
credentials = {'username': username, 'auth': basic_auth}
config_writer = ConfigFileWriter()
config_writer.update_config(profile, config, False)
credentials_writer = ConfigFileWriter()
credentials_writer.update_credentials(profile, credentials, False)
profile_writer = ConfigFileWriter()
config_writer.update_config('config', {}, False)
python类b64encode()的实例源码
def encrypt(raw, aes_key=secret):
iv = Random.new().read( AES.block_size )
cipher = AES.new(aes_key, AES.MODE_CFB, iv )
return (base64.b64encode( iv + cipher.encrypt( raw ) ) )
def login(cpf, password):
result = session.post('https://www.meualelo.com.br/meualelo.services/rest/login/authenticate', json={
'cpf': cpf,
'pwd': base64.b64encode(password),
'captchaResponse': '',
})
if result.status_code != 200:
raise WebApiFailure()
def headers(self):
"""Get the headers for the service requests."""
encoding = 'utf8'
headers = super().headers
token = b64encode(bytes('{}:{}'.format(
self.username,
self.password
), encoding))
headers['Authorization'] = 'Basic {}'.format(str(token, encoding))
return headers
def submit_sample(self, filepath, filename, tags=['JAMIE_Import', 'TheHive_Import']):
"""
Uploads a new sample to VMRay api. Filename gets sent base64 encoded.
:param filepath: path to sample
:type filepath: str
:param filename: filename of the original file
:type filename: str
:param tags: List of tags to apply to the sample
:type tags: list(str)
:returns: Dictionary of results
:rtype: dict
"""
apiurl = '/rest/sample/submit?sample_file'
params = {'sample_filename_b64enc': base64.b64encode(filename.encode('utf-8')),
'reanalyze': self.reanalyze}
if tags:
params['tags'] = ','.join(tags)
if os.path.isfile(filepath):
res = self.session.post(url=self.url + apiurl,
files=[('sample_file', open(filepath, mode='rb'))],
params=params)
if res.status_code == 200:
return json.loads(res.text)
else:
raise BadResponseError('Response from VMRay was not HTTP 200.'
' Responsecode: {}; Text: {}'.format(res.status_code, res.text))
else:
raise SampleFileNotFoundError('Given sample file was not found.')
def encrypt(pubkey, password):
"""Encrypt password using given RSA public key and encode it with base64.
The encrypted password can only be decrypted by someone with the
private key (in this case, only Travis).
"""
key = load_key(pubkey)
encrypted_password = key.encrypt(password, PKCS1v15())
return base64.b64encode(encrypted_password)
def encode_private_key(self):
"""
Based on spotnab, this is the gzipped version of the key
with base64 applied to it. We encode it as such and
return it.
"""
fileobj = StringIO()
with GzipFile(fileobj=fileobj, mode="wb") as f:
try:
f.write(self.private_pem())
except TypeError:
# It wasn't initialized yet
return None
return b64encode(fileobj.getvalue())
def encrypt(raw):
raw = pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(KEY, AES.MODE_CBC, iv)
return base64.b64encode( iv + cipher.encrypt(raw) )
def encrypt(raw):
raw = pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(KEY, AES.MODE_CBC, iv)
return base64.b64encode( iv + cipher.encrypt(raw) )
def encrypt(plaintext):
return base64.b64encode(kms.encrypt(
KeyId=KMS_KEY_ID, Plaintext=plaintext)['CiphertextBlob'])
def _b64_encode_bytes(b):
return base64.b64encode(b).decode("ascii")
def encrypt(text):
"""text (string)"""
aes = AES.new(settings.CRYPT_KEY, AES.MODE_CFB, settings.CRYPT_IV)
return base64.b64encode(aes.encrypt(text.encode())).decode()
def encrypt(pubkey, password):
"""Encrypt password using given RSA public key and encode it with base64.
The encrypted password can only be decrypted by someone with the
private key (in this case, only Travis).
"""
key = load_key(pubkey)
encrypted_password = key.encrypt(password, PKCS1v15())
return base64.b64encode(encrypted_password)
json_format.py 文件源码
项目:ios-xr-grpc-python
作者: cisco-grpc-connection-libs
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def _FieldToJsonObject(self, field, value):
"""Converts field value according to Proto3 JSON Specification."""
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
return self._MessageToJsonObject(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
enum_value = field.enum_type.values_by_number.get(value, None)
if enum_value is not None:
return enum_value.name
else:
raise SerializeToJsonError('Enum field contains an integer value '
'which can not mapped to an enum value.')
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
# Use base64 Data encoding for bytes
return base64.b64encode(value).decode('utf-8')
else:
return value
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return bool(value)
elif field.cpp_type in _INT64_TYPES:
return str(value)
elif field.cpp_type in _FLOAT_TYPES:
if math.isinf(value):
if value < 0.0:
return _NEG_INFINITY
else:
return _INFINITY
if math.isnan(value):
return _NAN
return value
def generate_cookie(name, securekey):
#print (">> generate cookie for %s" % name)
content = { 'name':name, 'login-time': time.asctime() }
text = json.dumps(content)
part1 = base64.b64encode(text.encode('ascii'))
part2 = hashlib.md5( (text+securekey).encode('ascii') ).hexdigest()
# part1 is binary(ascii) and part2 is str(utf-8)
cookie = str(part1, encoding='utf-8') +"."+ part2
#print ("cookie : %s" % cookie)
return cookie
def generate_auth_token(self, expiration = 3600):
s = Serializer(app.config['SECRET_KEY'], expires_in = expiration)
str = s.dumps({'id': self.id})
return b64encode(str).decode('utf-8')
pytest_selenium_pdiff.py 文件源码
项目:pytest-selenium-pdiff
作者: rentlytics
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def get_image_as_base64(filename):
with open(filename, 'rb') as fp:
content = fp.read()
return base64.b64encode(content).decode('ascii')
def _temporary_keychain():
"""
This function creates a temporary Mac keychain that we can use to work with
credentials. This keychain uses a one-time password and a temporary file to
store the data. We expect to have one keychain per socket. The returned
SecKeychainRef must be freed by the caller, including calling
SecKeychainDelete.
Returns a tuple of the SecKeychainRef and the path to the temporary
directory that contains it.
"""
# Unfortunately, SecKeychainCreate requires a path to a keychain. This
# means we cannot use mkstemp to use a generic temporary file. Instead,
# we're going to create a temporary directory and a filename to use there.
# This filename will be 8 random bytes expanded into base64. We also need
# some random bytes to password-protect the keychain we're creating, so we
# ask for 40 random bytes.
random_bytes = os.urandom(40)
filename = base64.b64encode(random_bytes[:8]).decode('utf-8')
password = base64.b64encode(random_bytes[8:]) # Must be valid UTF-8
tempdirectory = tempfile.mkdtemp()
keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')
# We now want to create the keychain itself.
keychain = Security.SecKeychainRef()
status = Security.SecKeychainCreate(
keychain_path,
len(password),
password,
False,
None,
ctypes.byref(keychain)
)
_assert_no_error(status)
# Having created the keychain, we want to pass it off to the caller.
return keychain, tempdirectory
def _b64_encode_bytes(b):
return base64.b64encode(b).decode("ascii")
def read_file(filename):
filename_path = os.path.join('/etc/ceph', filename)
if not os.path.exists(filename_path):
json_exit("file not found: {}".format(filename_path), failed=True)
if not os.access(filename_path, os.R_OK):
json_exit("file not readable: {}".format(filename_path), failed=True)
with open(filename_path, 'rb') as f:
raw_data = f.read()
return {'content': base64.b64encode(zlib.compress(raw_data)),
'sha1': hashlib.sha1(raw_data).hexdigest(),
'filename': filename}