• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# coding:utf-8
3
4#
5# Copyright (C) 2022 Huawei Technologies Co., Ltd.
6# Licensed under the Mulan PSL v2.
7# You can use this software according to the terms and conditions of the Mulan
8# PSL v2.
9# You may obtain a copy of Mulan PSL v2 at:
10#     http://license.coscl.org.cn/MulanPSL2
11# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
12# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
13# NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
14# See the Mulan PSL v2 for more details.
15#
16
17import struct
18import os
19import hashlib
20import stat
21
22HASH256 = 0
23HASH512 = 1
24
25
26def gen_hash(hash_type, in_data, out_file_path):
27    # Initialize a SHA256 object from the Python hash library
28    if int(hash_type) == HASH256:
29        hash_op = hashlib.sha256()
30    elif int(hash_type) == HASH512:
31        hash_op = hashlib.sha512()
32    hash_op.update(in_data)
33
34    #-----hash file used for ras sign---
35    fd_hash = os.open(out_file_path, os.O_WRONLY | os.O_CREAT, \
36        stat.S_IWUSR | stat.S_IRUSR)
37    hash_fp = os.fdopen(fd_hash, "wb")
38    # fixed hash prefix value
39    if int(hash_type) == HASH256:
40        hash_fp.write(struct.pack('B'*19, 0x30, 0x31, 0x30, 0x0d, 0x06, \
41            0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, \
42            0x05, 0x00, 0x04, 0x20))
43    elif int(hash_type) == HASH512:
44        hash_fp.write(struct.pack('B'*19, 0x30, 0x51, 0x30, 0x0d, 0x06, \
45            0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, \
46            0x05, 0x00, 0x04, 0x40))
47    hash_fp.write(hash_op.digest())
48    hash_fp.close()
49    return
50
51
52