basic.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "encryption/util/include/crypto/basic.h"
  15. namespace util {
  16. namespace crypto {
  17. int Basic::byte_to_hex(const unsigned char* in_byte, int len,
  18. std::string& out_hex) {
  19. std::ostringstream oss;
  20. oss << std::hex << std::setfill('0');
  21. for (int i = 0; i < len; ++i) {
  22. oss << std::setw(2) << int(in_byte[i]);
  23. }
  24. out_hex = oss.str();
  25. return 0;
  26. }
  27. int Basic::hex_to_byte(const std::string& in_hex, unsigned char* out_byte) {
  28. int i = 0;
  29. int j = 0;
  30. int len = in_hex.length() / 2;
  31. const unsigned char* hex;
  32. if (in_hex.length() % 2 != 0 || out_byte == NULL) {
  33. return -1;
  34. }
  35. hex = (unsigned char*)in_hex.c_str();
  36. for (; j < len; i += 2, ++j) {
  37. unsigned char high = hex[i];
  38. unsigned char low = hex[i + 1];
  39. if (high >= '0' && high <= '9') {
  40. high = high - '0';
  41. } else if (high >= 'A' && high <= 'F') {
  42. high = high - 'A' + 10;
  43. } else if (high >= 'a' && high <= 'f') {
  44. high = high - 'a' + 10;
  45. } else {
  46. return -2;
  47. }
  48. if (low >= '0' && low <= '9') {
  49. low = low - '0';
  50. } else if (low >= 'A' && low <= 'F') {
  51. low = low - 'A' + 10;
  52. } else if (low >= 'a' && low <= 'f') {
  53. low = low - 'a' + 10;
  54. } else {
  55. return -2;
  56. }
  57. out_byte[j] = high << 4 | low;
  58. }
  59. return 0;
  60. }
  61. int Basic::random(unsigned char* random, int len) {
  62. std::random_device rd;
  63. int i = 0;
  64. if (len <= 0 || random == NULL) {
  65. return -1;
  66. }
  67. for (; i < len; ++i) {
  68. random[i] = rd() % 256;
  69. }
  70. return 0;
  71. }
  72. } // namespace crypto
  73. } // namespace util