Commit 21d839db authored by Tom Niget's avatar Tom Niget

Add hashlib module

parent a9e353b0
//
// Created by Tom on 04/07/2023.
//
#ifndef TYPON_HASHLIB_HPP
#define TYPON_HASHLIB_HPP
#include "builtins.hpp"
#include <openssl/md5.h>
#include <openssl/sha.h>
// TODO: consider using EVP https://stackoverflow.com/a/40155962/2196124
namespace py_hashlib {
struct hashlib_t {
typedef int (*openssl_init)(void *context);
typedef int (*openssl_update)(void *context, const void *data,
unsigned long len);
typedef int (*openssl_final)(unsigned char *md, void *context);
struct {
struct type {
type(PyObj<void> context, openssl_update update, openssl_final final,
int diglen)
: _context(context), _update(update), _final(final), _diglen(diglen) {
}
type() {}
type(const type &other)
: _context(other._context), _update(other._update),
_final(other._final), _diglen(other._diglen), update(this),
hexdigest(this) {}
PyObj<void> _context;
openssl_update _update;
openssl_final _final;
int _diglen;
METHOD(int, update, (std::string val), {
return self->_update(self->_context.get(), &val[0], val.size());
})
METHOD(std::string, hexdigest, (), {
auto resbuf = new unsigned char[self->_diglen];
self->_final(resbuf, self->_context.get());
std::string hexres;
hexres.resize(self->_diglen * 2);
for (int i = 0; i < self->_diglen; i++) {
sprintf(&hexres[i * 2], "%02x", resbuf[i]);
}
delete[] resbuf;
return hexres;
})
};
} _Hash;
FUNCTION(auto, md5, (), {
auto ctx = pyobj<MD5_CTX>();
MD5_Init(ctx.get());
return decltype(_Hash)::type(ctx, (openssl_update)MD5_Update,
(openssl_final)MD5_Final, MD5_DIGEST_LENGTH);
})
FUNCTION(auto, sha1, (), {
auto ctx = pyobj<SHA_CTX>();
SHA1_Init(ctx.get());
return decltype(_Hash)::type(ctx, (openssl_update)SHA1_Update,
(openssl_final)SHA1_Final, SHA_DIGEST_LENGTH);
})
FUNCTION(auto, sha256, (), {
auto ctx = pyobj<SHA256_CTX>();
SHA256_Init(ctx.get());
return decltype(_Hash)::type(ctx, (openssl_update)SHA256_Update,
(openssl_final)SHA256_Final,
SHA256_DIGEST_LENGTH);
})
FUNCTION(auto, sha512, (), {
auto ctx = pyobj<SHA512_CTX>();
SHA512_Init(ctx.get());
return decltype(_Hash)::type(ctx, (openssl_update)SHA512_Update,
(openssl_final)SHA512_Final,
SHA512_DIGEST_LENGTH);
})
} all;
auto &get_all() { return all; }
} // namespace py_hashlib
// namespace typon {
using Py_Hash = decltype(py_hashlib::all._Hash)::type;
//}
#endif // TYPON_HASHLIB_HPP
# coding: utf-8
class _Hash:
def update(self, data: str) -> None: ...
def hexdigest(self) -> str: ...
def md5() -> _Hash: ...
def sha1() -> _Hash: ...
def sha256() -> _Hash: ...
def sha512() -> _Hash: ...
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment