Many integers will produce an odd number of hex bytes. For a smaller example, consider generating numbers in range(256)
. If you randomly generate 16-255 (0x10
to 0xff
) you’ll trim it to two digits, corresponding to one real byte of data. But if you generate 15, hex
will return '0xf'
, and 'f'
that can’t decode unambiguously to a single byte (did you want b'x0f'
or b'xf0'
?).
Really, if you want to generate the bytes of a private key, the easy solution is to just generate the bytes directly, and use a secure means of generating the bytes (Python’s PRNG is not suitable for cryptographically secure random numbers):
import os
private_key_bytes = os.urandom(32) # Directly pulls 32 bytes/256 bits of cryptographically secure
# random bytes from OS source
private_key = int.from_bytes(private_key_bytes, 'big') # If needed
Or equivalently using the random
module as a wrapper for os.urandom
:
import random
private_key_bytes = random.SystemRandom().randbytes(32) # SystemRandom directly wraps os.urandom
# Conversion to int unchanged
The secrets
module provides similar wrapper functionality with cryptographically secure random number generation and while it was only introduced in 3.6, you should be able to rely on that in most contexts, making for a third option:
import secrets
private_key_bytes = secrets.token_bytes(32)
Содержание
- Bug Report: Unhandled exception «binascii.Error: Odd-length string» #761
- Comments
- Traceback (most recent call last): File «commix.py», line 35, in main() File «commix.py», line 30, in main import src.core.main File «main.py», line 835, in main(filename, url) File «main.py», line 487, in main controller.do_check(url, http_request_method, filename) File «controller.py», line 842, in do_check perform_checks(url, http_request_method, filename) File «controller.py», line 770, in perform_checks get_request(url, http_request_method, filename, timesec) File «controller.py», line 650, in get_request injection_proccess(url, check_parameter, http_request_method, filename, timesec) File «controller.py», line 375, in injection_proccess decoded_value, decoded_with = checks.recognise_payload(payload=settings.TESTABLE_VALUE) File «checks.py», line 1259, in recognise_payload decoded_payload = hexdecode(check_value) File «convert.py», line 24, in hexdecode value = codecs.decode(».join(value.split()), «hex») binascii.Error: decoding with ‘hex’ codec failed (Error: Odd-length string)
- TypeError: Odd-length string #27
- Comments
- binascii.Error: Odd-length string #4
- Comments
- Footer
- Ошибки Ansible-vault с » строкой нечетной длины»
- 4 ответов
- AnsibleVaultFormatError does not point to the source of the error #72276
- Comments
Bug Report: Unhandled exception «binascii.Error: Odd-length string» #761
[info] Testing connection to the target URL.
[info] Performing identification checks to the target URL.
[info] Setting the unix-like based payloads.
[critical] Unable to connect to the target URL (HTTP Error 400: Bad Request).
[info] Setting the GET parameter ‘backstep’ for tests.
[critical] Unhandled exception occurred in ‘3.5-dev#47’. It is recommended to retry your run with the latest (dev) version from official GitHub repository at ‘https://github.com/commixproject/commix.git’. If the exception persists, please open a new issue at ‘https://github.com/commixproject/commix/issues/new’ with the following text and any other information required to reproduce the bug. The developers will try to reproduce the bug, fix it accordingly and get back to you.
Commix version: 3.5-dev#47
Python version: 3.9.12
Operating system: posix
Command line: commix.py —url=********************************************* —batch —level=3
Traceback (most recent call last):
File «hex_codec.py», line 19, in hex_decode
return (binascii.a2b_hex(input), len(input))
binascii.Error: Odd-length string
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File «commix.py», line 35, in
main()
File «commix.py», line 30, in main
import src.core.main
File «main.py», line 835, in
main(filename, url)
File «main.py», line 487, in main
controller.do_check(url, http_request_method, filename)
File «controller.py», line 842, in do_check
perform_checks(url, http_request_method, filename)
File «controller.py», line 770, in perform_checks
get_request(url, http_request_method, filename, timesec)
File «controller.py», line 650, in get_request
injection_proccess(url, check_parameter, http_request_method, filename, timesec)
File «controller.py», line 375, in injection_proccess
decoded_value, decoded_with = checks.recognise_payload(payload=settings.TESTABLE_VALUE)
File «checks.py», line 1259, in recognise_payload
decoded_payload = hexdecode(check_value)
File «convert.py», line 24, in hexdecode
value = codecs.decode(».join(value.split()), «hex»)
binascii.Error: decoding with ‘hex’ codec failed (Error: Odd-length string)
Could this be a duplicate my commix is updated to the latest version and this error popped up again could this be another kali linux issue or commix issue ?
The text was updated successfully, but these errors were encountered:
Источник
TypeError: Odd-length string #27
I am running Fedora 30.
I tried to update the list, but it just gives me «TypeError: Odd-length string».
Full traceback is here:
Traceback (most recent call last):
File «psi_client.py», line 440, in
update()
File «psi_client.py», line 311, in update
js = i[loc:].decode(‘hex’)
File «/usr/lib64/python2.7/encodings/hex_codec.py», line 42, in hex_decode
output = binascii.a2b_hex(input)
TypeError: Odd-length string
Any fix, or having a same issue?
The text was updated successfully, but these errors were encountered:
same here, i’m fedora 30 and run the docker:latest. during update got same error:
root@fefbd46bc6a8:
/psiphon# psiphon -u 100% [. ] 1409925 / 1409925Traceback (most recent call last): File «psi_client.py», line 440, in update() File «psi_client.py», line 311, in update js = i[loc:].decode(‘hex’) File «/usr/lib/python2.7/encodings/hex_codec.py», line 42, in hex_decode output = binascii.a2b_hex(input) TypeError: Odd-length string root@fefbd46bc6a8:
it seems «servers.dat» file did not generate in the normal way so serverlist did not get updated and timeout issue occurs, i used windows based server_list.dat and had no luck (format is different) i’m going to use android version and check whether that file is ok with linux or not!
Edit:
it seems this part of code has issue :
so i’ve edited this part with this code and the output file is structural the same with the original file but cannot be read (i’m so noob in python)
Источник
binascii.Error: Odd-length string #4
I think that no padding necessary isn’t always the case. An example is when trying to run examples/spend_p2sh_csv_p2pkh.py with:
By adding .zfill(64) to keys.py#L315, it seems to work fine. Please let me know if you need more information or if I’m doing something wrong.
The text was updated successfully, but these errors were encountered:
Thank you for reporting.
You get the error when you send the transaction to a node?
What error do you get exactly? The error that you mention comes up frequently when using a txid and/or vout that do not correspond to a valid UTXO.
Ideally a UTXO in testnet so that I can replicate the error would be great!
The error occurs when trying to use the script above, to just create the raw signed transaction. Should it matter if it’s from a valid UTXO? (even though in my local regtest it is)
The full error when running the above is:
I assumed the error was when you were sending it to a node. which is not uncommon given an invalid UTXO.
You are correct, if it happens during creation of the raw tx, the UTXO itself is irrelevant as long as the txid is proper hex (which it is). The padding does not matter while one works with numbers (e.g. line above) but it should matter with hex strings . not sure how the comment ended up there!
The hex need to be even so you are right. Good catch!
I will change and test tomorrow (run the existing tests, etc.).
Great stuff. It fixes it as expected! Maybe you would like to make a pull request? (otherwise, I will commit the change tomorrow)
© 2023 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Ошибки Ansible-vault с » строкой нечетной длины»
Я Ansible 1.8.2 . У меня есть сводчатый файл, созданный в другой системе. На этой системе он работает без каких-либо проблем. Однако, когда я запускаю его в своей локальной системе, я получаю следующую ошибку:
Я пытался вручную ввести пароль или скопировать его, но ошибка все равно происходит.
что здесь происходит и как исправить эту ошибку?
4 ответов
оказывается, эта ошибка из-за того, что с Ansible 1.8.2 она требует очень специфической кодировки конца строки для сводчатых файлов.
когда у меня был этот тип файла, он потерпел бы неудачу:
однако, как только я изменил его на это, он начал работать:
вся эта проблема возникла из-за того, что мой клиент git менял символы ввода строк. См. эту статью для деталей: https://help.github.com/articles/dealing-with-line-endings/
даже со всеми этими решениями редактирование файлов Ansible vault не работало для меня, пока я не установил переменную среды редактора (по какой-либо причине она не была установлена в моем дистрибутиве Linux):
один из способов выяснить, относится ли это к вам, — попытаться view хранилище файлов (с ) и если view работает нормально, но edit нет, тогда вам нужно установить редактор переменная env для вашего любимого редактора.
некоторые разработчики, использующие Windows, столкнулись с той же проблемой. т. е. возникновение ERROR: Odd-length string при работе ansible . Оказалось, что файлы, содержащие переменные ASCII text, with CRLF line terminators :
после sed -i ‘s/r//’ *_vars/*/* на crlf было изъято:
и запуск ansible удался.
Как уже было связано выше @Mxx (Thx!) Я разбавил необходимые изменения для того, чтобы иметь на LF-линии окончания на машине Windows:
(при условии, что у вас нет незафиксированных изменений и нет .gitattributes файл пока)
Это сделало работу для меня. Я смог получить доступ к хранилищу без необходимости запускать sed каждый раз.
Источник
AnsibleVaultFormatError does not point to the source of the error #72276
SUMMARY
When an invalid hex string is provided as encrypted secret, the following error is returned to the user :
This error is not directly actionable, since it does not point to the source of the error. Ideally, the error would contain the filename and the line where the error was found, and the value that failed to be decoded.
ISSUE TYPE
COMPONENT NAME
ANSIBLE VERSION
STEPS TO REPRODUCE
Create a playbook that contains, for instance:
EXPECTED RESULTS
ACTUAL RESULTS
The text was updated successfully, but these errors were encountered:
Files identified in the description:
If these files are incorrect, please update the component name section of the description or use the !component bot command.
You are correct in this not being actionable. I’m not sure how we could ever make it actionable.
We take the vault data, we remove newlines (which is required, the newlines are just there to keep YAML lines short), and then feed it to binascii.unhexlify . The error we get is simply binascii.Error(‘Odd-length string’) .
This indicates that the vault data is invalid, but due to the fact that it is odd-length.
We don’t know any more about this error, or where the source of the error is. Someone could have inserted some errant character into the middle of a vault data at any point. This is not a recoverable error.
The only recommended way to recover from this is to recreate the vault.
I’m unsure if we could indicate the source of where that vault string shows up.
It looks like all the functions that raise an AnsibleVaultFormatError take some encrypted text as input. Just including this text in the error would already make it much easier to find where the error comes from (the user would just rg the_invalid_string ). Adding a file name to the error should just be a matter to catch the error higher up, add the file name, and rethrow.
Источник
У меня есть pandas.Series
с несколькими значениями str
в шестнадцатеричном виде, например:
74 ,68 ,69 ,73 ,20 ,69 ,73 ,20 ,6d ,79 ,20 ,74 ,65 ,78 ,74 ,20 ,74 ,6f ,20 ,68 ,65 ,78
00, ff, aa, dd, 11, 22, 33, 44, 55, 00, ff, aa, dd, 11, 22, 33, 44, 55
74 ,68 ,69 ,73 ,20 ,69 ,73 ,20 ,6d ,79 ,20 ,74 ,65 ,78 ,74 ,20 ,74 ,6f ,20 ,68 ,65 ,78
74 ,68 ,69 ,73 ,20 ,69 ,73 ,20 ,6d ,79 ,20 ,74 ,65 ,78 ,74 ,20 ,74 ,6f ,20 ,68 ,65 ,78
00, ff, aa, dd, 11, 22, 33, 44, 55, 00, ff, aa, dd, 11, 22, 33, 44, 55
Я пытаюсь преобразовать hex в ascii, например:
df['value'] = df['value'].apply(lambda x: codec.decode(x, 'hex')
Я получаю такие ошибки, как:
binascii.Error: decoding with 'hex' codec failed (Error: Odd-length string)
Я ожидаю эти ошибки в некоторых строках, но нужно изменить значения, которые можно преобразовать в преобразованное состояние. Как я могу при ошибке ничего не делать со значением серии?
Ожидаемый результат:
this is my text to hex
00, ff, aa, dd, 11, 22, 33, 44, 55, 00, ff, aa, dd, 11, 22, 33, 44, 55
this is my text to hex
this is my text to hex
00, ff, aa, dd, 11, 22, 33, 44, 55, 00, ff, aa, dd, 11, 22, 33, 44, 55
output = binascii.a2b_hex(input)
TypeError: Odd-length string
2016-08-07 05:15:37,739 [ pgoapi] [ INFO] pgoapi v1.1.7 - Copyright (c) 2016 tjado <https://github.com/tejado>
2016-08-07 05:15:38,059 [ utilities] [ INFO] Location for 'Nimbin' found: Nimbin NSW 2480, Australia
2016-08-07 05:15:38,059 [ utilities] [ INFO] Coordinates (lat/long/alt) for location: -28.595833 153.223056 0.0
2016-08-07 05:15:38,061 [ auth_ptc] [ INFO] PTC User Login for: kDPDjkFzVKGg
2016-08-07 05:15:39,967 [ auth_ptc] [ INFO] PTC User Login successful.
2016-08-07 05:15:39,967 [ auth_ptc] [ INFO] Request PTC Access Token...
2016-08-07 05:15:40,429 [ auth_ptc] [ INFO] PTC Access Token successfully retrieved.
2016-08-07 05:15:40,445 [ pgoapi] [ INFO] Creating a new direct request...
2016-08-07 05:15:40,445 [ pgoapi] [ INFO] Adding 'GET_MAP_OBJECTS' to RPC request including arguments
2016-08-07 05:15:40,447 [ pgoapi] [ INFO] Execution of RPC
2016-08-07 05:15:41,052 [ pgoapi] [ INFO] API Endpoint redirect... re-execution of call
Traceback (most recent call last):
File "pokecli.py", line 133, in <module>
main()
File "pokecli.py", line 128, in main
response_dict = api.get_map_objects(latitude =position[0], longitude = position[1], since_timestamp_ms = timestamps, cell_id = cell_ids
)
File "/root/pgoapi/pgoapi/pgoapi.py", line 121, in function
return request.call()
File "/root/pgoapi/pgoapi/pgoapi.py", line 219, in call
response = request.request(self._api_endpoint, self._req_method_list, self.get_position())
File "/root/pgoapi/pgoapi/rpc_api.py", line 125, in request
request_proto = self._build_main_request(subrequests, player_position)
File "/root/pgoapi/pgoapi/rpc_api.py", line 196, in _build_main_request
sig.location_hash1 = generateLocation1(ticket_serialized, request.latitude, request.longitude, request.altitude)
File "/root/pgoapi/pgoapi/utilities.py", line 165, in generateLocation1
locationBytes = d2h(lat) + d2h(lng) + d2h(alt)
File "/root/pgoapi/pgoapi/utilities.py", line 183, in d2h
return hex(struct.unpack('<Q', struct.pack('<d', f))[0])[2:-1].decode("hex")
File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
output = binascii.a2b_hex(input)
TypeError: Odd-length string
https://gist.github.com/vivosmith/f0e692d9aedbc39ec8d3eb4651bc107c
I was trying to implement this video in Python 3
But the issue is that, it was implemented in Python 2
So I tried to implement this with binascii instead of encode/decode. However I keep getting a binascii.Error: Odd-length string at line 22.
How to I correct this? Or if this is completely broken, then is there any other libraries that work better for python 3?
remedcu
1,0831 gold badge9 silver badges26 bronze badges
asked Sep 25, 2017 at 20:20
This is working for me:
import os
import ecdsa
import binascii
import hashlib
private_key = os.urandom(32)
PK_EN = binascii.hexlify(private_key)
print("Your Key" + " " + str(PK_EN))
PK_CON = binascii.unhexlify(PK_EN)
sk = ecdsa.SigningKey.from_string(PK_CON, curve=ecdsa.SECP256k1)
vk = sk.verifying_key
msg = binascii.hexlify(b'Hello')
sign_msg = sk.sign(msg)
assert vk.verify(sign_msg, msg)
public_key = b'04' + binascii.hexlify(vk.to_string())
print(public_key)
ripemd160 = hashlib.new('ripemd160')
ripemd160.update(hashlib.sha256(binascii.unhexlify(public_key)).digest())
I’ve changed the way you concatenated the public key with the prefix, and the call to the ripmd160.update
, since it was expecting a string, not a Hash object.
answered Sep 28, 2017 at 14:46
sr_gisr_gi
2,8521 gold badge11 silver badges36 bronze badges
Я Ansible 1.8.2
.
У меня есть сводчатый файл, созданный в другой системе. На этой системе он работает без каких-либо проблем.
Однако, когда я запускаю его в своей локальной системе, я получаю следующую ошибку:
$» ansible-vault --debug view vars/vaulted_vars.yml
Vault password:
Traceback (most recent call last):
File "/usr/bin/ansible-vault", line 225, in main
fn(args, options, parser)
File "/usr/bin/ansible-vault", line 172, in execute_view
this_editor.view_file()
File "/usr/lib/python2.7/site-packages/ansible/utils/vault.py", line 280, in view_file
dec_data = this_vault.decrypt(tmpdata)
File "/usr/lib/python2.7/site-packages/ansible/utils/vault.py", line 136, in decrypt
data = this_cipher.decrypt(data, self.password)
File "/usr/lib/python2.7/site-packages/ansible/utils/vault.py", line 545, in decrypt
data = unhexlify(data)
TypeError: Odd-length string
ERROR: Odd-length string
Я пытался вручную ввести пароль или скопировать его, но ошибка все равно происходит.
что здесь происходит и как исправить эту ошибку?
4 ответов
оказывается, эта ошибка из-за того, что с Ansible 1.8.2 она требует очень специфической кодировки конца строки для сводчатых файлов.
когда у меня был этот тип файла, он потерпел бы неудачу:
$» file vaulted_vars.yml
vaulted_vars.yml: ASCII text, with CRLF line terminators
однако, как только я изменил его на это, он начал работать:
$» file vaulted_vars.yml
vaulted_vars.yml: ASCII text
вся эта проблема возникла из-за того, что мой клиент git менял символы ввода строк. См. эту статью для деталей: https://help.github.com/articles/dealing-with-line-endings/
даже со всеми этими решениями редактирование файлов Ansible vault не работало для меня, пока я не установил переменную среды редактора (по какой-либо причине она не была установлена в моем дистрибутиве Linux):
export EDITOR="/usr/bin/vi"
один из способов выяснить, относится ли это к вам, — попытаться view
хранилище файлов (с ) и если view
работает нормально, но edit
нет, тогда вам нужно установить редактор переменная env для вашего любимого редактора.
некоторые разработчики, использующие Windows, столкнулись с той же проблемой. т. е. возникновение ERROR: Odd-length string
при работе ansible
. Оказалось, что файлы, содержащие переменные ASCII text, with CRLF line terminators
:
user@host ~/path/to/ansible $ file *_vars/*/*
group_vars/groupname/vars: ASCII text, with CRLF line terminators
host_vars/hostname/vars: ASCII text, with CRLF line terminators
после sed -i 's/r//' *_vars/*/*
на crlf
было изъято:
user@host ~/path/to/ansible $ file *_vars/*/*
group_vars/groupname/vars: ASCII text
host_vars/hostname/vars: ASCII text
и запуск ansible удался.
Как уже было связано выше @Mxx (Thx!) Я разбавил необходимые изменения для того, чтобы иметь на LF-линии окончания на машине Windows:
(при условии, что у вас нет незафиксированных изменений и нет .gitattributes файл пока)
# create the .gitattributes file to set the line endings only for this repo
C:projectslfonly>copy con .gitattributes
* text eol=lf
^Z (thats F6 + Enter)
1 file(s) copied.
# delete all cached local file! Warning any uncommited changes will be lost
git rm --cached -r .
git reset --hard
Это сделало работу для меня. Я смог получить доступ к хранилищу без необходимости запускать sed каждый раз.