Python and MATLAB Hash Function Implementation: MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512

This code provides a versatile hash function implementation in both Python and MATLAB, supporting a wide range of popular hashing algorithms including MD2, MD5, SHA-1, SHA-256, SHA-384, and SHA-512. It handles input data conversion and ensures the correct format for hashing. Additionally, it incorporates error handling to prevent issues arising from invalid hash algorithm inputs.

MATLAB Code

function h = HashFunction(inp,meth)
    inp=inp(:);
    % convert strings and logicals into uint8 format
    if ischar(inp) || islogical(inp)
        inp=uint8(inp);
    else % convert everything else into uint8 format without loss of data
        inp=typecast(inp,'uint8');
    end

    % verify hash method, with some syntactical forgiveness:
    meth=upper(meth);
    switch meth
        case 'SHA1'
            meth='SHA-1';
        case 'SHA256'
            meth='SHA-256';
        case 'SHA384'
            meth='SHA-384';
        case 'SHA512'
            meth='SHA-512';
        otherwise
    end
    algs={'MD2','MD5','SHA-1','SHA-256','SHA-384','SHA-512'};
    if isempty(strmatch(meth,algs,'exact'))
        error(['Hash algorithm must be ' ...
            'MD2, MD5, SHA-1, SHA-256, SHA-384, or SHA-512']);
    end

    % create hash
    x=java.security.MessageDigest.getInstance(meth);
    x.update(inp);
    h=typecast(x.digest,'uint8');
    h=dec2hex(h)';
    if(size(h,1))==1 % remote possibility: all hash bytes < 128, so pad:
        h=[repmat('0',[1 size(h,2)]);h];
    end
    h=lower(h(:)');
    clear x
    return
end

Python Code

import hashlib

def HashFunction(inp, meth):
    inp = str(inp)
    
    # convert strings and logicals into uint8 format
    if isinstance(inp, str) or isinstance(inp, bool):
        inp = inp.encode('utf-8')
    else: # convert everything else into uint8 format without loss of data
        inp = bytes(inp)
    
    # verify hash method, with some syntactical forgiveness
    meth = meth.upper()
    if meth == 'SHA1':
        meth = 'SHA-1'
    elif meth == 'SHA256':
        meth = 'SHA-256'
    elif meth == 'SHA384':
        meth = 'SHA-384'
    elif meth == 'SHA512':
        meth = 'SHA-512'
    else:
        raise ValueError('Hash algorithm must be MD2, MD5, SHA-1, SHA-256, SHA-384, or SHA-512')
    
    # create hash
    x = hashlib.new(meth)
    x.update(inp)
    h = x.hexdigest()
    
    return h

Usage

Both Python and MATLAB code utilize the same function structure: HashFunction(inp, meth). To use the function, simply pass your input data (inp) and the desired hash algorithm (meth) as arguments.

Example (Python):

input_data = 'Hello world!'  # Example input data
algorithm = 'SHA-256'  # Example algorithm

hash_result = HashFunction(input_data, algorithm)
print(hash_result)  # Output the hash value

Example (MATLAB):

input_data = 'Hello world!';  % Example input data
algorithm = 'SHA-256';  % Example algorithm

hash_result = HashFunction(input_data, algorithm);
disp(hash_result);  % Display the hash value

Key Features

  • Algorithm Flexibility: Supports MD2, MD5, SHA-1, SHA-256, SHA-384, and SHA-512.
  • Input Data Handling: Handles various input data types (strings, logicals, and others) by converting them to the appropriate format for hashing.
  • Error Handling: Raises an error if an invalid hash algorithm is specified, preventing potential issues.
  • Cross-Platform Compatibility: The Python and MATLAB code provides cross-platform support for hashing functionality.

This code provides a robust and versatile hash function implementation suitable for various applications requiring secure data hashing.

Python and MATLAB Hash Function Implementation: MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512

原文地址: https://www.cveoy.top/t/topic/qFFo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录