Python binascii error odd length string

binascii.Error: Odd-length string #4 Comments 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, […]

Содержание

  1. binascii.Error: Odd-length string #4
  2. Comments
  3. Footer
  4. TypeError: Odd-length string #27
  5. Comments
  6. TypeError: Odd-length string after updating to the latest version #15
  7. Comments
  8. AnsibleVaultFormatError does not point to the source of the error #72276
  9. Comments

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.

Источник

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)

Источник

TypeError: Odd-length string after updating to the latest version #15

Firstly, thank you so very much for writing such a simple library for TOTP generation.

We’ve been using this library for a long time. I updated the library’s code to the latest version and immediately bumped into this issue of TypeError: Odd-length string .

The source of the error seems to be:

To check the issue, I used the simple test suggested in the source code:
hotp(‘343434′, 2, format=’dec6’)
This correctly generated a PIN value of 791303.

But if I added to an extra character to the key, then I would run into this error.

On our platform it’s not possible to control the length of the key, because it is generated through a unique combination of a user’s ID + document ID. This can yield both an Odd/Even length key string.

Is there some way I can resolve this situation?

The text was updated successfully, but these errors were encountered:

Your bug is not really solvable at the library level, keys are byte strings and an hexadecimal number must have two digits to represent a byte; so I would have to add a zero on the left or the right to make your key looks of for unhexlify(). I would advise you to do it, add a zero on the left or the right of the key and it will work. Do you know of another widely deployed implementation of TOTP which accept odd length hexadecimal keys ? That would incite me to do something at the library level.

Oh, the problem at our end is that we’ve got a bunch of apps on Android and iOS which rely on the TOTP system without the provision to alter their key lengths to always be even. So, even if I were to do something at the server side to convert odd-length strings to even-length, I fear I’ll just end up breaking the system.

I was digging through how our code was working earlier, and I came across a modification put in the _hotp module’s hotp method, which is something like this:

If I replace the current hotp method with this one, then my code starts to work just fine. I feel this is so because the _totp module only invokes this method in the _hotp module.

To be sure, I just wanted to run this by you and understand whether it’s a reasonable thing to do, or will this code break something else (bearing in mind that we are only using this library for TOTP generation).

Источник

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.

Источник

У меня есть шестнадцатеричное значение, которое я беру из текстового файла, затем я передаю его в a2b_hex, чтобы преобразовать его в правильное двоичное представление. Вот что у меня есть:

k = open('./' + basefile + '.key', 'r')
k1 = k.read()
k.close()
my_key = binascii.a2b_hex(k1)

Когда я печатаю k1, это, как и ожидалось: 81e3d6df

Вот сообщение об ошибке:

Traceback (most recent call last):
  File "xor.py", line 26, in <module>
    my_key = binascii.a2b_hex(k1)
TypeError: Odd-length string

Какие-либо предложения? Спасибо!

4 ответы

Вы уверены, что в файле нет ничего лишнего? Пробелы, например?

Пытаться k1.strip()

Создан 16 сен.

Я подозреваю, что в конце файла есть завершающая новая строка. Разделите строку перед передачей ее в binascii.

Обратите внимание, что теперь есть и более простое написание: k1.strip().decode('hex').

Создан 16 сен.

Меня больше интересует, что произойдет, если вы выполните следующий код:

with open("./" + basefile + ".key") as key_file:
   key = key_file.read()
   print len(key), key

Хотите сказать? Вероятно, есть какой-то дополнительный символ, который вы просто не видите при печати. В этих случаях обязательно напечатайте длину строки.

Создан 16 сен.

read() не удаляет новые строки. Если есть 'n' в конце вашего файла он будет в k1.

Пытаться binascii.a2b_hex(k1.strip()) или, возможно, binascii.a2b_hex(k1[:8]).

Создан 16 сен.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

python

or задайте свой вопрос.

C

This problem you are having there is due to the fact that https://pt.wikipedia.org/wiki/Buffer_(ci%C3%AAncia_da_computa%C3%A7%C3%A3o) from the keyboard not being clean, when you press enter gets a /n stored in the keyboard buffer, to end this error just clean the buffer.For this use the function setbuf, it serves to assign a value to the buffer. In case we will assign a null value, then before each fgets that you give you will add the following setbuf (stdin, NULL);, for thus you will be saying that you want to assign the value of NULL, that is, zero to stdin that is the keyboard buffer, so that your main Stay like this:int main()
{
printf («n CADASTRO DE ALUNO:»);
printf («n DIGITE O NOME DO ALUNO: «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.nome, 50, stdin);
printf (» DIGITE A DATA DE NASCIMENTO: «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.nasc, 10, stdin);
printf (» DIGITE UM NUMERO PARA
CONTATO: «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.tel, 20, stdin);
printf (» DIGITE A RUA «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.end, 20, stdin);
printf (» DIGITE O BAIRRO «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.bairro, 10, stdin);
printf (» DIGITE A CIDADE «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.cidade, 10, stdin);
printf (» DIGITE O NOME DA MAE «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.mae, 20, stdin);
printf (» DIGITE O NOME DO PAI «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.pai, 20, stdin);
system(«pause»);
returne 0;
}
This is the first step, in addition by good programming practice, take that global variable you are using, and incorporate it into the main, so you have a more beautiful code and less susceptible to errors.In addition it is remarkable that when you type 03 ABRIL 2001 you are giving a https://pt.wikipedia.org/wiki/Transbordamento_de_dados , because you created a string, to store the date, of only 10 characters, remembering that the last is reserved to soon you will have only 9 characters available, and this sentence, 03 APRIL 2001, has 20 counting on , then you would need a larger string, i.e., to solve the second error just increase the string size to a more adequate size when, I believe that 30 is more than enough, after the changes your code look like this:#include <string.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct aluno
{
char nome[50];
char nasc[30];
char tel[20];
char end[20];
char bairro[10];
char cidade[10];
char mae[20];
char pai[20];

} aluno;
int main()
{
aluno CAD_ALUNO;
printf («n CADASTRO DE ALUNO:»);

printf («n DIGITE O NOME DO ALUNO: «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.nome, 50, stdin);

printf (» DIGITE A DATA DE NASCIMENTO: «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.nasc, 30, stdin);

printf (» DIGITE UM NUMERO PARA CONTATO: «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.tel, 20, stdin);

printf (» DIGITE A RUA «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.end, 20, stdin);

printf (» DIGITE O BAIRRO «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.bairro, 10, stdin);

printf (» DIGITE A CIDADE «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.cidade, 10, stdin);

printf (» DIGITE O NOME DA MAE «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.mae, 20, stdin);

printf (» DIGITE O NOME DO PAI «);
setbuf (stdin, NULL);
fgets(CAD_ALUNO.pai, 20, stdin);

system («pause»);
return 0;

}
In addition there are also other ways to read a string with spaces, I particularly do not like the use of fgets for this, I prefer to use the scanf.To be able to read everything until n with scanf just do the following, scanf(» %[^n]s», nome_da_string);, so you are adding a condition in it saying it is for him to read up to the n, that is, until the end of the line, also do not forget to place the space between the quotes («) and the percentage (%), because so you will not have buffer error, and you will not have to be cleaning the buffer, so the code in the main It would be like this:int main()
{
aluno CAD_ALUNO;
printf («n CADASTRO DE ALUNO:»);

printf («n DIGITE O NOME DO ALUNO: «);
scanf(» %[^n]s», CAD_ALUNO.nome);

printf (» DIGITE A DATA DE NASCIMENTO: «);
scanf(» %[^n]s», CAD_ALUNO.nasc);

printf (» DIGITE UM NUMERO PARA CONTATO: «);
scanf(» %[^n]s», CAD_ALUNO.tel);

printf (» DIGITE A RUA «);
scanf(» %[^n]s», CAD_ALUNO.end);

printf (» DIGITE O BAIRRO «);
scanf(» %[^n]s», CAD_ALUNO.bairro);

printf (» DIGITE A CIDADE «);
scanf(» %[^n]s», CAD_ALUNO.cidade);

printf (» DIGITE O NOME DA MAE «);
scanf(» %[^n]s», CAD_ALUNO.mae);

printf (» DIGITE O NOME DO PAI «);
scanf(» %[^n]s», CAD_ALUNO.pai);

system («pause»);
return 0;

}
I hope I have helped, anything just ask, and good luck in programming studies (^_^)/

Понравилась статья? Поделить с друзьями:
  • Python baseexception вывод ошибки
  • Python base error class
  • Python assert no error
  • Python 401 error
  • Pytest error unrecognized arguments