本文整理汇总了Python中crypt.crypt方法的典型用法代码示例。如果您正苦于以下问题:Python crypt.crypt方法的具体用法?Python crypt.crypt怎么用?Python crypt.crypt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类crypt
的用法示例。
在下文中一共展示了crypt.crypt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def setUp(self):
self.admin = credentials.UsernamePassword('admin', 'asdf')
self.alice = credentials.UsernamePassword('alice', 'foo')
self.badPass = credentials.UsernamePassword('alice', 'foobar')
self.badUser = credentials.UsernamePassword('x', 'yz')
self.checker = strcred.makeChecker('unix')
# Hack around the pwd and spwd modules, since we can't really
# go about reading your /etc/passwd or /etc/shadow files
if pwd:
database = UserDatabase()
for username, password in self.users.items():
database.addUser(
username, crypt.crypt(password, 'F/'),
1000, 1000, username, '/home/' + username, '/bin/sh')
self.patch(pwd, 'getpwnam', database.getpwnam)
if spwd:
self._spwd_getspnam = spwd.getspnam
spwd.getspnam = self._spwd
示例2: kullaniciOlustur
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def kullaniciOlustur(isim,kullisim,kullsifre):
#encPass = crypt.crypt(kullsifre,"22")
#os.system("useradd -p "+encPass+ " -s "+ "/bin/bash "+ "-d "+ "/home/" + kullisim+ " -m "+ " -c \""+ name+"\" " + kullisim)
os.system("kopar milislinux-"+isim+" "+kullisim)
os.system('echo -e "'+kullsifre+'\n'+kullsifre+'" | passwd '+kullisim)
#masaustu ve diğer ayarların aktarılması
ayar_komut="cp -r /root/.config /home/"+kullisim+"/"
os.system(ayar_komut)
ayar_komut2="cp -r /root/.xinitrc /home/"+kullisim+"/"
os.system(ayar_komut2)
ayar_komut3="chown "+kullisim+":"+kullisim+" -R /home/"+kullisim
os.system(ayar_komut3)
saat_komut="saat_ayarla_tr"
os.system(saat_komut)
d.infobox(text=kullisim+" kullanıcısı başarıyla oluşturuldu.")
time.sleep(1)
示例3: validate_authentication
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def validate_authentication(self, username, password, handler):
"""Authenticates against shadow password db; raises
AuthenticationFailed in case of failed authentication.
"""
if username == "anonymous":
if self.anonymous_user is None:
raise AuthenticationFailed(self.msg_anon_not_allowed)
else:
try:
pw1 = spwd.getspnam(username).sp_pwd
pw2 = crypt.crypt(password, pw1)
except KeyError: # no such username
raise AuthenticationFailed(self.msg_no_such_user)
else:
if pw1 != pw2:
raise AuthenticationFailed(self.msg_wrong_password)
示例4: get_hexdigest
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def get_hexdigest(algorithm, salt, raw_password):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or 'crypt').
"""
raw_password, salt = smart_str(raw_password), smart_str(salt)
if algorithm == 'crypt':
try:
import crypt
except ImportError:
raise ValueError('"crypt" password algorithm not supported in this environment')
return crypt.crypt(raw_password, salt)
if algorithm == 'md5':
return hashlib.md5(salt + raw_password).hexdigest()
elif algorithm == 'sha1':
return hashlib.sha1(salt + raw_password).hexdigest()
elif algorithm == 'sha256':
return hashlib.sha256(salt + raw_password).hexdigest()
raise ValueError("Got unknown password algorithm type in password.")
示例5: setUp
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def setUp(self):
self.admin = credentials.UsernamePassword('admin', 'asdf')
self.alice = credentials.UsernamePassword('alice', 'foo')
self.badPass = credentials.UsernamePassword('alice', 'foobar')
self.badUser = credentials.UsernamePassword('x', 'yz')
self.checker = strcred.makeChecker('unix')
self.adminBytes = credentials.UsernamePassword(b'admin', b'asdf')
self.aliceBytes = credentials.UsernamePassword(b'alice', b'foo')
self.badPassBytes = credentials.UsernamePassword(b'alice', b'foobar')
self.badUserBytes = credentials.UsernamePassword(b'x', b'yz')
self.checkerBytes = strcred.makeChecker('unix')
# Hack around the pwd and spwd modules, since we can't really
# go about reading your /etc/passwd or /etc/shadow files
if pwd:
database = UserDatabase()
for username, password in self.users.items():
database.addUser(
username, crypt.crypt(password, 'F/'),
1000, 1000, username, '/home/' + username, '/bin/sh')
self.patch(pwd, 'getpwnam', database.getpwnam)
if spwd:
self.patch(spwd, 'getspnam', self._spwd_getspnam)
示例6: verifyCryptedPassword
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def verifyCryptedPassword(crypted, pw):
"""
Use L{crypt.crypt} to Verify that an unencrypted
password matches the encrypted password.
@param crypted: The encrypted password, obtained from
the Unix password database or Unix shadow
password database.
@param pw: The unencrypted password.
@return: L{True} if there is successful match, else L{False}.
@rtype: L{bool}
"""
try:
import crypt
except ImportError:
crypt = None
if crypt is None:
raise NotImplementedError("cred_unix not supported on this platform")
if not isinstance(pw, StringType):
pw = pw.decode('utf-8')
if not isinstance(crypted, StringType):
crypted = crypted.decode('utf-8')
return crypt.crypt(pw, crypted) == crypted
示例7: safe_crypt
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def safe_crypt(secret, hash):
if isinstance(secret, bytes):
# Python 3's crypt() only accepts unicode, which is then
# encoding using utf-8 before passing to the C-level crypt().
# so we have to decode the secret.
orig = secret
try:
secret = secret.decode("utf-8")
except UnicodeDecodeError:
return None
assert secret.encode("utf-8") == orig, \
"utf-8 spec says this can't happen!"
if _NULL in secret:
raise ValueError("null character in secret")
if isinstance(hash, bytes):
hash = hash.decode("ascii")
result = _crypt(secret, hash)
if not result or result[0] in _invalid_prefixes:
return None
return result
示例8: test_interleaving
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def test_interleaving(container):
# make sure we can interleave calls of different API objects
password = crypt("foobar", "salt")
root = container.vanilla_api(connection='paramiko')
root.host_key_checking = False
root.command('useradd --non-unique --uid 0 foo -p ' + password)
root.command('useradd --non-unique --uid 0 bar -p ' + password)
foo = container.vanilla_api(
connection='paramiko', remote_user='foo', remote_pass='foobar')
bar = container.vanilla_api(
connection='paramiko', remote_user='bar', remote_pass='foobar')
foo.host_key_checking = False
bar.host_key_checking = False
assert foo.command('id -g').stdout() == '1000'
assert bar.command('id -g').stdout() == '1001'
assert foo.command('id -g').stdout() == '1000'
assert bar.command('id -g').stdout() == '1001'
示例9: crypt_salt_is_valid
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def crypt_salt_is_valid(salt):
"""
Validate a salt as crypt salt
:param str salt: a password salt
:return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise
:rtype: bool
"""
if len(salt) < 2:
return False
else:
if salt[0] == '$':
if salt[1] == '$':
return False
else:
if '$' not in salt[1:]:
return False
else:
hashed = crypt.crypt("", salt)
if not hashed or '$' not in hashed[1:]:
return False
else:
return True
else:
return True
示例10: _generate_salt
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def _generate_salt(self):
# The salt can be generated with crypt.mksalt() on Python 3
CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
salt = ''.join(random.choice(CHARACTERS) for i in range(16))
# Use SHA512
return '$6$' + salt
示例11: _retrieve_salt
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def _retrieve_salt(self, password_hash):
# Example hashed password
# python -c 'import crypt; print crypt.crypt("", "$6$cMLi2vqIIJtq1Shm")'
# $6$cMLi2vqIIJtq1Shm$41Ko1W2aTapn.p12G2dWRrRdStI2CrkC1JsftC/bPmwVgiy0vAQIXuuZEbVenyqsM6vZOsuzFrKrQC9NGd6/p.
elements = password_hash.split('$')
if len(elements) != 4:
return None
else:
# Use SHA512
return '$6$' + elements[2]
示例12: _hash_password
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def _hash_password(self, password):
salt = self._generate_salt()
return crypt.crypt(password, salt)
示例13: verify_password
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def verify_password(self, user_name, password):
found_records = filter(lambda x: x['user_name'] == user_name, self.records)
count = len(found_records)
if count == 0:
return False
elif count == 1:
password_hash = found_records[0]['password_hash']
return crypt.crypt(password, self._retrieve_salt(password_hash)) == password_hash
elif count > 1:
# Should not be here
raise Exception('Faint! Is there something wrong?')
# We need to verify the user with the old password first
示例14: test_hash_type_is_used
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def test_hash_type_is_used(request, master, python):
user = WHEEL_CONFIG['user']
password_salt = '00'
password = crypt.crypt(WHEEL_CONFIG['password'], password_salt)
request.addfinalizer(
partial(master['container'].run, "userdel {0}".format(user)))
master['container'].run("useradd {0} -p '{1}'".format(user, password))
raw_output = master['container'].run(
"{0} tests/scripts/wheel_config_values.py".format(python))
output = json.loads(str(raw_output.decode()))
assert output['data']['return']['hash_type'] == "sha384"
示例15: gen_htpasswd
# 需要导入模块: import crypt [as 别名]
# 或者: from crypt import crypt [as 别名]
def gen_htpasswd(users_passwords, file_name_suffix=""):
with open("nginx/.htpasswd" + file_name_suffix, "w") as fh:
for user, password in users_passwords.items():
if not password:
fh.write("\n")
else:
fh.write(
"%s:%s\n"
% (
user,
crypt.crypt(
password, crypt.mksalt(crypt.METHOD_SHA512)
),
)
)