1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
|
#!/usr/bin/env python
import os
import sys
from ctypes import (
POINTER,
c_char_p,
c_double,
c_int,
c_size_t,
c_uint32,
c_uint64,
cdll,
create_string_buffer,
pointer,
)
if sys.version_info >= (3, 8) and sys.platform == "win32":
lib_path = os.path.join(os.path.normpath(sys.prefix), "Library", "bin")
build_dir = os.path.join(os.path.dirname(__file__), "../")
if os.path.exists(lib_path):
os.add_dll_directory(lib_path)
if os.path.exists(build_dir):
os.add_dll_directory(build_dir)
import importlib
import importlib.util
import os.path
# Fix for finding the _scrypt module
_scrypt_spec = importlib.util.find_spec("_scrypt")
if _scrypt_spec and hasattr(_scrypt_spec, "origin"):
_scrypt = cdll.LoadLibrary(_scrypt_spec.origin)
else:
# Fallback for Windows
import os.path
import sys
if sys.platform == "win32":
# Look for the DLL in common locations
_scrypt_dll = "_scrypt.pyd"
_path = os.path.abspath(os.path.dirname(__file__))
_scrypt = cdll.LoadLibrary(os.path.join(_path, _scrypt_dll))
__version__ = "0.9.4"
# Declare C functions from libscrypt
_scryptenc_buf = _scrypt.exp_scryptenc_buf
_scryptenc_buf.argtypes = [
c_char_p, # const uint_t *inbuf
c_size_t, # size_t inbuflen
c_char_p, # uint8_t *outbuf
c_char_p, # const uint8_t *passwd
c_size_t, # size_t passwdlen
c_size_t, # size_t maxmem
c_double, # double maxmemfrac
c_double, # double maxtime
c_int, # int logN
c_uint32, # uint32_t r
c_uint32, # uint32_t p
c_int, # int verbose
c_int, # int force
]
_scryptenc_buf.restype = c_int
_scryptdec_buf = _scrypt.exp_scryptdec_buf
_scryptdec_buf.argtypes = [
c_char_p, # const uint8_t *inbuf
c_size_t, # size_t inbuflen
c_char_p, # uint8_t *outbuf
POINTER(c_size_t), # size_t *outlen
c_char_p, # const uint8_t *passwd
c_size_t, # size_t passwdlen
c_size_t, # size_t maxmem
c_double, # double maxmemfrac
c_double, # double maxtime
c_int, # int logN
c_uint32, # uint32_t r
c_uint32, # uint32_t p
c_int, # int verbose
c_int, # int force
]
_scryptdec_buf.restype = c_int
_crypto_scrypt = _scrypt.exp_crypto_scrypt
_crypto_scrypt.argtypes = [
c_char_p, # const uint8_t *passwd
c_size_t, # size_t passwdlen
c_char_p, # const uint8_t *salt
c_size_t, # size_t saltlen
c_uint64, # uint64_t N
c_uint32, # uint32_t r
c_uint32, # uint32_t p
c_char_p, # uint8_t *buf
c_size_t, # size_t buflen
]
_crypto_scrypt.restype = c_int
# Define the pickparams C function interface
_pickparams = _scrypt.exp_pickparams
_pickparams.argtypes = [
c_size_t, # size_t maxmem
c_double, # double maxmemfrac
c_double, # double maxtime
POINTER(c_int), # int *logN
POINTER(c_uint32), # uint32_t *r
POINTER(c_uint32), # uint32_t *p
c_int, # int verbose
]
_pickparams.restype = c_int
# Define the checkparams C function interface
_checkparams = _scrypt.exp_checkparams
_checkparams.argtypes = [
c_size_t, # size_t maxmem
c_double, # double maxmemfrac
c_double, # double maxtime
c_int, # int logN
c_uint32, # uint32_t r
c_uint32, # uint32_t p
c_int, # int verbose
c_int, # int force
]
_checkparams.restype = c_int
ERROR_MESSAGES = [
"success",
"getrlimit or sysctl(hw.usermem) failed",
"clock_getres or clock_gettime failed",
"error computing derived key",
"could not obtain cryptographically secure random bytes",
"error in OpenSSL",
"malloc failed",
"data is not a valid scrypt-encrypted block",
"unrecognized scrypt format",
"decrypting file would take too much memory",
"decrypting file would take too long",
"password is incorrect",
"error writing output file",
"error reading input file",
"error in explicit parameters",
"error in explicit parameters (both SCRYPT_ETOOBIG and SCRYPT_ETOOSLOW)",
]
MAXMEM_DEFAULT = 0
MAXMEMFRAC_DEFAULT = 0.5
MAXTIME_DEFAULT = 300.0
MAXTIME_DEFAULT_ENC = 5.0
class error(Exception):
def __init__(self, scrypt_code):
if isinstance(scrypt_code, int):
self._scrypt_code = scrypt_code
super().__init__(ERROR_MESSAGES[scrypt_code])
else:
self._scrypt_code = -1
super().__init__(scrypt_code)
def _ensure_bytes(data):
"""Convert data to bytes if it's a string, otherwise return as is.
Args:
data: String or bytes to convert
Returns:
bytes: The input converted to bytes if needed
"""
if isinstance(data, str):
return data.encode("utf-8")
elif not isinstance(data, bytes):
raise TypeError(f"Expected str or bytes, got {type(data).__name__}")
return data
def encrypt(
input,
password,
maxtime=MAXTIME_DEFAULT_ENC,
maxmem=MAXMEM_DEFAULT,
maxmemfrac=MAXMEMFRAC_DEFAULT,
logN=0,
r=0,
p=0,
force=False,
verbose=False,
):
"""Encrypt data using a password.
The resulting data will have len = len(input) + 128.
- `input` and `password` can be both str and bytes. If they are str
instances, they will be encoded with utf-8
- The result will be a bytes instance
- If logN, r, and p are all zero, optimal parameters will be chosen automatically
- If logN, r, and p are provided,
they must all be non-zero and will be used explicitly
Args:
input: Data to encrypt (bytes or str)
password: Password for encryption (bytes or str)
maxtime: Maximum time to spend in seconds
maxmem: Maximum memory to use in bytes (0 for unlimited)
maxmemfrac: Maximum fraction of available memory to use (0.0 to 1.0)
logN: Log2 of the work factor (0 for automatic selection)
r: Block size parameter (0 for automatic selection)
p: Parallelization parameter (0 for automatic selection)
force: If True, do not check whether encryption will exceed the estimated
available memory or time
verbose: If True, display parameter information
Returns:
bytes: Encrypted data
Exceptions raised:
- TypeError on invalid input
- scrypt.error if encryption failed or parameters are invalid
For more information on the `maxtime`, `maxmem`, and `maxmemfrac`
parameters, see the scrypt documentation.
"""
input = _ensure_bytes(input)
password = _ensure_bytes(password)
# All parameters must be 0 or all must be non-zero
if not ((logN == 0 and r == 0 and p == 0) or (logN != 0 and r != 0 and p != 0)):
raise error(
"If providing explicit parameters, all of logN, r, and p must be non-zero"
)
# If parameters aren't provided, pick them automatically
if logN == 0 and r == 0 and p == 0:
logN, r, p = pickparams(maxmem, maxmemfrac, maxtime)
outbuf = create_string_buffer(len(input) + 128)
# verbose is set to zero
result = _scryptenc_buf(
input,
len(input),
outbuf,
password,
len(password),
maxmem,
maxmemfrac,
maxtime,
logN,
r,
p,
1 if verbose else 0, # verbose parameter
1 if force else 0, # force parameter
)
if result:
raise error(result)
return outbuf.raw
def decrypt(
input,
password,
maxtime=MAXTIME_DEFAULT,
maxmem=MAXMEM_DEFAULT,
maxmemfrac=MAXMEMFRAC_DEFAULT,
encoding="utf-8",
verbose=False,
force=False,
):
"""Decrypt data using a password.
- `input` and `password` can be both str and bytes. If they are str
instances, they will be encoded with utf-8. `input` *should*
really be a bytes instance, since that's what `encrypt` returns.
- The result will be a str instance decoded with `encoding`.
If encoding=None, the result will be a bytes instance.
Args:
input: Encrypted data (bytes or str)
password: Password for decryption (bytes or str)
maxtime: Maximum time to spend in seconds
maxmem: Maximum memory to use in bytes (0 for unlimited)
maxmemfrac: Maximum fraction of available memory to use
encoding: Encoding to use for output string (None for raw bytes)
verbose: If True, display parameter information
force: If True, do not check whether decryption will exceed the estimated
available memory or time
Returns:
Decrypted data as str (if encoding is provided) or bytes (if encoding is None)
Exceptions raised:
- TypeError on invalid input
- scrypt.error if decryption failed or if decoding with the specified
encoding fails
For more information on the `maxtime`, `maxmem`, and `maxmemfrac`
parameters, see the scrypt documentation.
"""
outbuf = create_string_buffer(len(input))
outbuflen = pointer(c_size_t(0))
input = _ensure_bytes(input)
password = _ensure_bytes(password)
# verbose and force are set to zero
result = _scryptdec_buf(
input,
len(input),
outbuf,
outbuflen,
password,
len(password),
maxmem,
maxmemfrac,
maxtime,
0,
0,
0,
1 if verbose else 0, # verbose parameter
1 if force else 0, # force parameter
)
if result:
raise error(result)
out_bytes = outbuf.raw[: outbuflen.contents.value]
if encoding is None:
return out_bytes
try:
# More robust error handling for decoding
return out_bytes.decode(encoding)
except UnicodeDecodeError as e:
raise error(f"Failed to decode using {encoding} encoding: {str(e)}") from e
def hash(password, salt, N=1 << 14, r=8, p=1, buflen=64):
"""Compute scrypt(password, salt, N, r, p, buflen).
The parameters r, p, and buflen must satisfy r * p < 2^30 and
buflen <= (2^32 - 1) * 32. The parameter N must be a power of 2
greater than 1. N, r and p must all be positive.
- `password` and `salt` can be both str and bytes. If they are str
instances, they wil be encoded with utf-8.
- The result will be a bytes instance
Exceptions raised:
- TypeError on invalid input
- scrypt.error if scrypt failed
"""
outbuf = create_string_buffer(buflen)
password = _ensure_bytes(password)
salt = _ensure_bytes(salt)
if r * p >= (1 << 30) or N <= 1 or (N & (N - 1)) != 0 or p < 1 or r < 1:
raise error(
"hash parameters are wrong (r*p should be < 2**30, "
"and N should be a power of two > 1)"
)
result = _crypto_scrypt(
password, len(password), salt, len(salt), N, r, p, outbuf, buflen, 0
)
if result:
raise error("could not compute hash")
return outbuf.raw
def pickparams(
maxmem=MAXMEM_DEFAULT,
maxmemfrac=MAXMEMFRAC_DEFAULT,
maxtime=MAXTIME_DEFAULT_ENC,
verbose=0,
):
"""
Pick the optimal scrypt parameters (logN, r, p) based on memory and CPU constraints.
This function automatically determines the best parameters for scrypt encryption
based on the available system resources. It balances security and performance
by selecting parameters that will use as much memory and CPU time as allowed
without exceeding the specified constraints.
Args:
maxmem: Maximum memory to use in bytes (0 for unlimited)
maxmemfrac: Maximum fraction of available memory to use (0.0 to 1.0)
maxtime: Maximum time to spend in seconds
verbose: Whether to display parameter information (0 or 1)
Returns:
tuple: (logN, r, p) parameters for scrypt encryption
- logN: The log2 of the work factor (N = 2^logN)
- r: Block size parameter, fixed at 8 for compatibility
- p: Parallelization parameter, adjusted based on CPU and memory
Example:
>>> from scrypt import pickparams
>>> logN, r, p = pickparams(maxtime=2.0)
>>> print(f"Optimal parameters: N=2^{logN} ({2**logN}), r={r}, p={p}")
"""
# Create output parameters for the C function
logN = c_int(0)
r = c_uint32(0)
p = c_uint32(0)
# Call the C function
result = _pickparams(
maxmem, maxmemfrac, maxtime, pointer(logN), pointer(r), pointer(p), verbose
)
# Check for errors
if result:
raise error(result)
return logN.value, r.value, p.value
def checkparams(
logN,
r,
p,
maxmem=MAXMEM_DEFAULT,
maxmemfrac=MAXMEMFRAC_DEFAULT,
maxtime=MAXTIME_DEFAULT_ENC,
verbose=0,
force=0,
):
"""
Check if the provided scrypt parameters are valid and within resource limits.
This function verifies that the scrypt parameters (logN, r, p) are valid and
can be computed within the specified memory and CPU time constraints.
Args:
logN: Log2 of the work factor (N = 2^logN)
r: Block size parameter
p: Parallelization parameter
maxmem: Maximum memory to use in bytes (0 for unlimited)
maxmemfrac: Maximum fraction of available memory to use (0.0 to 1.0)
maxtime: Maximum time to spend in seconds
verbose: Whether to display parameter information (0 or 1)
force: If 1, ignore resource limits
Returns:
0 on success, otherwise an error code
Exceptions raised:
- scrypt.error if parameters are invalid or would exceed resource limits
"""
# Call the C function
result = _checkparams(maxmem, maxmemfrac, maxtime, logN, r, p, verbose, force)
# Check for errors
if result:
raise error(result)
return 0
__all__ = ["error", "encrypt", "decrypt", "hash", "pickparams", "checkparams"]
|