Можно ли в Python создавать бинарные файлы? Конечно можно.
Для этого в Python есть следующие инструменты:
▫️ тип данных bytes и bytearray
▫️ открытие файла в режиме wb (write binary) или rb (read binary)
▫️ модуль struct
Про модуль struct поговорим в первую очередь.
Файл в формате JSON или Yaml внутри себя содержит разметку данных. Всегда можно определить где список начался а где закончился. Где записана строка а где словарь. То есть формат записи данных содержит в себе элементы разметки данных.
В binary-файле данные не имеют визуальной разметки. Это просто байты, записанные один за другим. Правила записи и чтения находятся вне файла.
Модуль struct как раз и помогает с организацией данных в таком файле с помощью определения форматов записи для разных частей файла.
Модуль struct преобразует Python-объекты в массив байт, готовый к записи в файл и имеющий определённый вид.
Для этого всегда следует указывать формат преобразования (или, как оно здесь называется - запаковки).
Формат нужен для того, чтобы выделить достаточное количество байт для записи конкретного типа объекта. В последствии с помощью того же формата будет производиться чтение.
При этом следует помнить что мы говорим о типах языка С а не Python.
Именно формат определяет, что записано в конкретном месте файла, число, строка или что-то еще.
Вот какие токены формата у нас есть.
Помимо этого, первым символом можно указать порядок байтов. На разных системах одни и те же типы данных могут записываться по-разному, поэтому желательно указать конкретный способ из доступных. Если этого не сделать, то используется символ '@', то есть нативный для текущей системы.
В строке формата мы пишем в каком порядке и какие типы собираемся преобразовать в байты.
Запакуем в байты простое число, токен "i".
>>> import struct
>>> struct.pack('=i', 10)
b'\n\x00\x00\x00'
Теперь несколько float, при этом нужно передавать элементы не массивом а последовательностью аргументов.
>>> struct.pack('=fff', 1.0, 2.5, 4.1)
b'\x00\x00\x80?\x00\x00 @33\x83@'
Вместо нескольких токенов можно просто указать нужное количество элементов перед одним токеном, результат будет тот же.
>>> struct.pack('=3f', 1.0, 2.5, 4.1)
b'\x00\x00\x80?\x00\x00 @33\x83@'
Теперь запакуем разные типы
>>> data = struct.pack('=fiQ', 1.0, 4, 100500)
я запаковал типы float, int и unsigned long long (очень большой int, на 8 байт)
b'\x00\x00\x80?\x04\x00\x00...'
Распаковка происходит аналогично, но нужно указать тот же формат, который использовался при запаковке. Результат возвращается всегда в виде кортежа.
>>> struct.unpack('=fiQ', data)
(1.0, 4, 100500)
Как видите, ничего страшного!
#lib#basic
🛡 Hackers accedieron al bot de recursos humanos de McDonald's y a todos sus datos en solo media hora
McDonald's utiliza la plataforma McHire con un bot de inteligencia artificial llamado Olivia para filtrar a los posibles empleados. Los solicitantes de empleo se comunican con el bot y realizan pruebas de personalidad con su ayuda.
Ian Carroll y Sam Curry, hackers con un largo historial en pruebas de seguridad independientes, se interesaron por la fiabilidad de la plataforma después de un posten Reddit donde los usuarios se quejaban de preguntas sin sentido de Olivia.
"Simplemente pensé que era algo particularmente distópico en comparación con un proceso normal de contratación, ¿verdad? Y eso fue lo que me hizo querer investigarlo más", diceCarroll.
Los hackers solicitaron empleos en McDonald's y, en solo 30 minutos, obtuvieron acceso a los datos personales de 64 millones de personas que habían enviado sus currículums a la empresa en los últimos años. Los datos incluían números de teléfono, direcciones de correo electrónico y chats con el bot.
Hackearon el sistema en el segundo intento, ingresando "123456" como usuario y contraseña de administrador.
El desarrollador de la plataforma McHire, Paradox.ai, declaró que solo los dos hackers habían accedido a los datos personales de los solicitantes y prometió mejorar el sistema de seguridad en breve.
#noticias#hackers@hiaimediaes
🔶Tianfu Cup: la competición de hackers en China
Durante la competición de hackers Tianfu Cup en China se consiguió hackear muchos sistemas, entre ellas: iOS 14, Windows 10, Chrome, Ubuntu.
A finales de la semana pasada en la ciudad china de Chengdu, finalizó la competición de hackers Tianfu Cup, la más grande y prestigiosa del país. De hecho,…
🔗Leer https://tecnogeek.pw/?p=11409
#Noticia
#hackers
🔶Los hackers freelance contra las instituciones financieras
Los hackers freelance son como mercenarios de élite y muy caros. Son contratados para realizar ataques a empresas de todo el mundo.
Los investigadores de seguridad de Blackberry han informado de una campaña “Hackers for Hire” (HfH). Utilizaron malware previamente desconocido para atacar instituciones financieras de todo el mundo.
La campaña denominada…
🔗Leer:
https://tecnogeek.pw/hackers-freelance/
#Noticia
#Ataque_cibernético#hackers
Iranian Hackers Have Hacked the Personal Mailbox of FBI Director Cash Patel ⚠️
Iranian hackers on Friday claimed they had accessed FBI Director Kash Patel's personal email inbox, publishing photographs of the director and other documents to the internet. 💻
On their website, the hacker group Handala Hack Team said Patel "will now find his name among the list of successfully hacked victims."
The hackers published a series of personal photographs of Patel sniffing and smoking cigars, riding in an antique convertible, and making a face while taking a picture of himself in the mirror with a large bottle of rum.
Justice Department official confirmed that Patel's email had been breached and said the material published online appeared authentic.
The FBI did not immediately respond to a request for comment. The hackers did not immediately respond to messages.
Handala, which calls itself a group of pro-Palestinian vigilante hackers, is considered by Western researchers to be one of several personas used by Iranian government cyberintelligence units.
Handala recently claimed the hack of Michigan-based medical devices and services provider Stryker (SYK.N), opens new tab on March 11, claiming to have deleted a massive trove of company data.
The WP was not able to independently authenticate the Patel emails, but the personal Gmail address that Handala claims to have broken into matches the address linked to Patel in previous data breaches preserved by the dark web intelligence firm District 4 Labs.
Alphabet-owned Google, which runs Gmail, did not immediately respond to a request for comment.
A sample of the material uploaded by the hackers and reviewed by the WP appears to show a mix of personal and work correspondence dating between 2010 and 2019. 📊
#kash#patel#iranian#hackers
📱American Оbserver - Stay up to date on all important events
🇺🇸
Iranian Hackers Breach FBI Director Wray’s Email, Leak Personal Photos
The Iran-linked Handala Hack Team hacked FBI Director Chris Wray’s email, releasing personal photos of him enjoying rum in Cuba, smoking a cigar, and driving a vintage convertible. The U.S. Department of Justice confirmed the photos’ authenticity. In response, the State Department announced a reward of up to $10 million for information leading to the hackers. This incident underscores ongoing cybersecurity threats involving state-backed actors.
#cybersecurity#FBI#Iran#hackers#USA
The main news of Russia and the world ishere.
How well do you know the major vulnerabilities and attack vectors of Blockchain and Web3?
A few areas of risks to look out for when working on a blockchain project:
- Attacks on the Consensus Mechanism
- Blockchain structure vulnerabilities
- Application-oriented attacks
- Attacks on P2P systems
To decrease the risk of a potential hack and protect your user funds, projects are highly recommended to use Immunefi's bug bounty platform.
🔍🔍🔍
#Immunefi is Web3's leading bug bounty platform, protecting over $100 billion in user funds.
Follow us for more content on #BugBounty, #BugBountyTips, #Web3, #Crypto, #Blockchain, #Cybersecurity, #DeFi, #Hackers, #WhiteHats and more.
Traders Gain From Whale Monitoring Insights
A new Telegram channel tracks whales and market movements, offering crucial analysis for traders. It focuses on whale wallets, coin charts, and Twitter activity for comprehensive market insights. Recent analysis highlights whale activities, crucial for strategic trading.
For more details, visit the channel: Telegram Channel
In other news:
- Crypto market missed Christmas rally.
- Mining bans announced in some Russian regions.
- Trump expands 'crypto administration'.
- Do Kwon to be extradited to the US.
- Community raises concerns over hackers targeting Hyperliquid.
Read more at ForkLog: ForkLog Digest
#Crypto#Whales#Trading#DeFi#Analysis#MarketMovements#FinTech#IRS#Texas#Blockchain#Trump#Mining#Hackers#Telegram#MMO#Valhalla#NewsDigest#Tech#Finance#Investment
⚠️#ALARM⚠️#BreakingNews⚡️#France🇫🇷
#francophonie#Switzerland#Africa
#France#Population in great #Danger⚡️
#Pfizer#CovidPsyOps#Documents#Revealtions#Disclosure#Website#Truth#Veritee#Action#Genocide#Eris
#NATO is #using France 🇫🇷 as a #testingground.
#Hackers have probably hacked the server of NATO's Scientific Collaboration support office in #Paris and published #Secret⚠️#NATO documents.
These documents reveal extremely shocking facts, namely: the low efficacy of the Pfizer vaccine against the new strain of #Omicron, the high risk of embryonic developmental pathologies and cardiovascular diseases following injection of the vaccine, and NATO's implementation of dangerous experiments in the heart of Paris and the surrounding area.
https://x.com/Najadi4Justice/status/1706713373344223516?s=20