初步写完RSA的加解密
This commit is contained in:
parent
40f7b89454
commit
991d4b1887
34
.clang-format
Normal file
34
.clang-format
Normal file
@ -0,0 +1,34 @@
|
||||
# .clang-format
|
||||
|
||||
# 风格格式化
|
||||
BasedOnStyle: LLVM
|
||||
# 4 空格缩进
|
||||
IndentWidth: 4
|
||||
# 连续对齐变量的声明
|
||||
AlignConsecutiveDeclarations: true
|
||||
# 指针左侧对齐
|
||||
PointerAlignment: Left
|
||||
# 访问说明符(public、private等)的偏移
|
||||
AccessModifierOffset: -4
|
||||
# 大括号
|
||||
BreakBeforeBraces: Custom
|
||||
BraceWrapping:
|
||||
# 函数定义后面大括号在新行
|
||||
AfterFunction: true
|
||||
# class定义后面
|
||||
AfterClass: true
|
||||
|
||||
# 去除C++11的列表初始化的大括号{后和}前的空格
|
||||
Cpp11BracedListStyle: true
|
||||
# 允许重新排版注释
|
||||
ReflowComments: true
|
||||
# 允许排序#include
|
||||
SortIncludes: true
|
||||
# 在尾随的评论前添加的空格数(只适用于//)
|
||||
SpacesBeforeTrailingComments: 3
|
||||
# tab宽度
|
||||
TabWidth: 4
|
||||
# 构造函数的初始化列表要么都在同一行,要么都各自一行
|
||||
ConstructorInitializerAllOnOneLineOrOnePerLine: true
|
||||
# 每行字符的限制,0表示没有限制
|
||||
ColumnLimit: 150
|
12
.clangd
Normal file
12
.clangd
Normal file
@ -0,0 +1,12 @@
|
||||
Hover:
|
||||
ShowAKA: Yes
|
||||
Diagnostics:
|
||||
UnusedIncludes: None # 禁用未使用头文件提示
|
||||
Suppress: [
|
||||
anon_type_definition, # 禁用匿名的typedef提示
|
||||
unused-variable, # 禁用未使用变量提示
|
||||
unused-function, # 禁用未使用函数提示
|
||||
unused-includes, # 禁用未使用的头文件提示
|
||||
]
|
||||
ClangTidy:
|
||||
Remove: misc-unused-alias-decls
|
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
build
|
34
.vscode/settings.json
vendored
Normal file
34
.vscode/settings.json
vendored
Normal file
@ -0,0 +1,34 @@
|
||||
{
|
||||
"files.autoSave": "onFocusChange",
|
||||
"editor.fontSize": 14,
|
||||
"editor.fontFamily": "'FiraCode Nerd Font', 'FiraCode Nerd Font', 'FiraCode Nerd Font'",
|
||||
"cmake.configureOnOpen": true,
|
||||
"cmake.debugConfig": {
|
||||
"console": "integratedTerminal"
|
||||
},
|
||||
"cmake.configureSettings": {
|
||||
"CMAKE_TOOLCHAIN_FILE": "${env:VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
|
||||
},
|
||||
"cmake.options.statusBarVisibility": "visible",
|
||||
"cmake.generator": "Ninja",
|
||||
"C_Cpp.intelliSenseEngine": "disabled",
|
||||
"clangd.arguments": [
|
||||
"--header-insertion=never",
|
||||
"--all-scopes-completion",
|
||||
"--completion-style=detailed",
|
||||
"--clang-tidy",
|
||||
"-j=4",
|
||||
"--pch-storage=memory",
|
||||
"--compile-commands-dir=build",
|
||||
"--background-index",
|
||||
"--ranking-model=heuristics",
|
||||
"--function-arg-placeholders=false",
|
||||
"--query-driver=repaceE"
|
||||
],
|
||||
"editor.inlayHints.enabled": "off",
|
||||
"editor.unicodeHighlight.allowedLocales": {
|
||||
"ja": true,
|
||||
"zh-hant": true,
|
||||
"zh-hans": true
|
||||
}
|
||||
}
|
14
CMakeLists.txt
Normal file
14
CMakeLists.txt
Normal file
@ -0,0 +1,14 @@
|
||||
cmake_minimum_required (VERSION 3.8)
|
||||
project (auxiliarytool)
|
||||
set(CMAKE_CXX_STANDARD 11)
|
||||
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
set(CMAKE_BUILD_TYPE "Release")
|
||||
endif()
|
||||
if (MSVC)
|
||||
add_compile_options(/source-charset:utf-8)
|
||||
add_compile_options(/EHsc)
|
||||
add_compile_options(-D_CRT_SECURE_NO_WARNINGS)
|
||||
endif()
|
||||
|
||||
add_subdirectory(cryp)
|
92
README.md
92
README.md
@ -1,93 +1,3 @@
|
||||
# AuxiliaryTool
|
||||
|
||||
|
||||
|
||||
## Getting started
|
||||
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
|
||||
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||
|
||||
## Add your files
|
||||
|
||||
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
||||
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
|
||||
|
||||
```
|
||||
cd existing_repo
|
||||
git remote add origin https://gitlab.com/taynpg/auxiliarytool.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
```
|
||||
|
||||
## Integrate with your tools
|
||||
|
||||
- [ ] [Set up project integrations](https://gitlab.com/taynpg/auxiliarytool/-/settings/integrations)
|
||||
|
||||
## Collaborate with your team
|
||||
|
||||
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
||||
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
||||
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
||||
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
||||
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
|
||||
|
||||
## Test and Deploy
|
||||
|
||||
Use the built-in continuous integration in GitLab.
|
||||
|
||||
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
|
||||
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
||||
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
||||
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
||||
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
||||
|
||||
***
|
||||
|
||||
# Editing this README
|
||||
|
||||
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||
|
||||
## Suggestions for a good README
|
||||
|
||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
|
||||
## Description
|
||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||
|
||||
## Badges
|
||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||
|
||||
## Visuals
|
||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||
|
||||
## Installation
|
||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||
|
||||
## Usage
|
||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||
|
||||
## Support
|
||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
|
||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||
|
||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
|
||||
## Project status
|
||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||
辅助接口。
|
7
cryp/CMakeLists.txt
Normal file
7
cryp/CMakeLists.txt
Normal file
@ -0,0 +1,7 @@
|
||||
cmake_minimum_required (VERSION 3.8)
|
||||
project (box_cryp)
|
||||
set(CMAKE_CXX_STANDARD 11)
|
||||
|
||||
find_package(OpenSSL REQUIRED)
|
||||
add_library(box_cryp STATIC "box_rsa.h" "box_rsa.cpp")
|
||||
target_link_libraries(box_cryp PRIVATE OpenSSL::SSL OpenSSL::Crypto)
|
278
cryp/box_rsa.cpp
Normal file
278
cryp/box_rsa.cpp
Normal file
@ -0,0 +1,278 @@
|
||||
#include "box_rsa.h"
|
||||
|
||||
#include "openssl/err.h"
|
||||
#include "openssl/evp.h"
|
||||
#include "openssl/pem.h"
|
||||
#include <cassert>
|
||||
#include <openssl/rsa.h>
|
||||
#include <string>
|
||||
|
||||
|
||||
constexpr size_t g_buffsize = 2048;
|
||||
|
||||
namespace cppbox {
|
||||
|
||||
class CRSAOperatorImp
|
||||
{
|
||||
public:
|
||||
CRSAOperatorImp()
|
||||
{
|
||||
err_ = new char[g_buffsize];
|
||||
ioerr_ = BIO_new_mem_buf(err_, g_buffsize);
|
||||
}
|
||||
~CRSAOperatorImp()
|
||||
{
|
||||
BIO_free(ioerr_);
|
||||
delete[] err_;
|
||||
}
|
||||
|
||||
public:
|
||||
bool encrypt_pub(const HData& public_pem, const HData& data, HData& result)
|
||||
{
|
||||
mem_ = BIO_new_mem_buf((void*)public_pem.data, public_pem.len);
|
||||
key_ = PEM_read_bio_PUBKEY(mem_, nullptr, nullptr, nullptr);
|
||||
if (key_ == nullptr) {
|
||||
std::snprintf(err_, g_buffsize, "Read From Public Key Mem Data Failed.");
|
||||
clear();
|
||||
return false;
|
||||
}
|
||||
ctx_ = EVP_PKEY_CTX_new(key_, nullptr);
|
||||
EVP_PKEY_encrypt_init(ctx_);
|
||||
if (EVP_PKEY_encrypt(ctx_, nullptr, &result.len, data.data, data.len) <= 0) {
|
||||
clear();
|
||||
ERR_print_errors(ioerr_);
|
||||
return false;
|
||||
}
|
||||
alloc_data(result);
|
||||
if (EVP_PKEY_encrypt(ctx_, result.data, &result.len, data.data, data.len) <= 0) {
|
||||
free_data(result);
|
||||
clear();
|
||||
return false;
|
||||
}
|
||||
clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool decrypt_pri(const HData& private_pem, const HData& data, HData& result)
|
||||
{
|
||||
mem_ = BIO_new_mem_buf((void*)private_pem.data, private_pem.len);
|
||||
key_ = PEM_read_bio_PrivateKey(mem_, nullptr, nullptr, nullptr);
|
||||
if (key_ == nullptr) {
|
||||
std::snprintf(err_, g_buffsize, "Read From Private Key Mem Data Failed.");
|
||||
clear();
|
||||
return false;
|
||||
}
|
||||
ctx_ = EVP_PKEY_CTX_new(key_, nullptr);
|
||||
EVP_PKEY_decrypt_init(ctx_);
|
||||
if (EVP_PKEY_decrypt(ctx_, nullptr, &result.len, data.data, data.len) <= 0) {
|
||||
clear();
|
||||
ERR_print_errors(ioerr_);
|
||||
return false;
|
||||
}
|
||||
alloc_data(result);
|
||||
if (EVP_PKEY_decrypt(ctx_, result.data, &result.len, data.data, data.len) <= 0) {
|
||||
free_data(result);
|
||||
clear();
|
||||
ERR_print_errors(ioerr_);
|
||||
return false;
|
||||
}
|
||||
clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool encrypt_pub(const char* pub_path, const HData& data, HData& result)
|
||||
{
|
||||
FILE* fp = fopen(pub_path, "r");
|
||||
if (fp == nullptr) {
|
||||
std::snprintf(err_, g_buffsize, "Read File %s Failed.", pub_path);
|
||||
return false;
|
||||
}
|
||||
|
||||
HData file_data{};
|
||||
fseek(fp, 0, SEEK_END);
|
||||
file_data.len = ftell(fp);
|
||||
fseek(fp, 0, SEEK_SET);
|
||||
|
||||
file_data.data = (unsigned char*)malloc(file_data.len);
|
||||
if (file_data.data == NULL) {
|
||||
fclose(fp);
|
||||
std::snprintf(err_, g_buffsize, "Alloc Mem Failed: %zd", file_data.len);
|
||||
return false;
|
||||
}
|
||||
file_data.len = fread(file_data.data, 1, file_data.len, fp);
|
||||
bool ret = encrypt_pub(file_data, data, result);
|
||||
free(file_data.data);
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool decrypt_pri(const char* pri_path, const HData& data, HData& result)
|
||||
{
|
||||
FILE* fp = fopen(pri_path, "r");
|
||||
if (fp == nullptr) {
|
||||
std::snprintf(err_, g_buffsize, "Read File %s Failed.", pri_path);
|
||||
return false;
|
||||
}
|
||||
|
||||
HData file_data{};
|
||||
fseek(fp, 0, SEEK_END);
|
||||
file_data.len = ftell(fp);
|
||||
fseek(fp, 0, SEEK_SET);
|
||||
|
||||
file_data.data = (unsigned char*)malloc(file_data.len);
|
||||
if (file_data.data == NULL) {
|
||||
fclose(fp);
|
||||
std::snprintf(err_, g_buffsize, "Alloc Mem Failed: %zd", file_data.len);
|
||||
return false;
|
||||
}
|
||||
file_data.len = fread(file_data.data, 1, file_data.len, fp);
|
||||
bool ret = decrypt_pri(file_data, data, result);
|
||||
free(file_data.data);
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool generate_keypair(const char* pub_path, const char* pri_path)
|
||||
{
|
||||
FILE* fp_pub = fopen(pub_path, "w");
|
||||
if (fp_pub == nullptr) {
|
||||
std::snprintf(err_, g_buffsize, "Open File Failed: %s", pub_path);
|
||||
return false;
|
||||
}
|
||||
FILE* fp_pri = fopen(pri_path, "w");
|
||||
if (fp_pri == nullptr) {
|
||||
std::snprintf(err_, g_buffsize, "Open File Failed: %s", pri_path);
|
||||
fclose(fp_pub);
|
||||
return false;
|
||||
}
|
||||
key_ = EVP_RSA_gen(g_buffsize / 2);
|
||||
if (key_ == nullptr) {
|
||||
ERR_print_errors_fp(stderr);
|
||||
return false;
|
||||
}
|
||||
PEM_write_PUBKEY(fp_pub, key_);
|
||||
PEM_write_PrivateKey(fp_pri, key_, nullptr, nullptr, 0, nullptr, nullptr);
|
||||
clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool generate_keypair(HData& pub, HData& pri)
|
||||
{
|
||||
key_ = EVP_RSA_gen(g_buffsize / 2);
|
||||
if (key_ == nullptr) {
|
||||
ERR_print_errors_fp(stderr);
|
||||
return false;
|
||||
}
|
||||
BIO* mem_pub = BIO_new(BIO_s_mem());
|
||||
if (mem_pub == nullptr) {
|
||||
std::snprintf(err_, g_buffsize, "Alloc public BIO Failed.");
|
||||
return false;
|
||||
}
|
||||
BIO* mem_pri = BIO_new(BIO_s_mem());
|
||||
if (mem_pri == nullptr) {
|
||||
BIO_free(mem_pub);
|
||||
std::snprintf(err_, g_buffsize, "Alloc private BIO Failed.");
|
||||
return false;
|
||||
}
|
||||
PEM_write_bio_PUBKEY(mem_pub, key_);
|
||||
PEM_write_bio_PrivateKey(mem_pri, key_, nullptr, nullptr, 0, nullptr, nullptr);
|
||||
|
||||
pub.len = BIO_ctrl_pending(mem_pub);
|
||||
pri.len = BIO_ctrl_pending(mem_pri);
|
||||
|
||||
alloc_data(pub);
|
||||
alloc_data(pri);
|
||||
|
||||
pub.len = BIO_read(mem_pub, pub.data, pub.len);
|
||||
pri.len = BIO_read(mem_pri, pri.data, pri.len);
|
||||
|
||||
clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
void free_data(HData& data)
|
||||
{
|
||||
free(data.data);
|
||||
data.len = 0;
|
||||
}
|
||||
void alloc_data(HData& data)
|
||||
{
|
||||
if (data.len < 1) {
|
||||
data.data = nullptr;
|
||||
return;
|
||||
}
|
||||
data.data = static_cast<unsigned char*>(malloc(data.len));
|
||||
}
|
||||
|
||||
void get_last_error(char* buf, int len)
|
||||
{
|
||||
std::snprintf(buf, len, err_, strlen(err_));
|
||||
}
|
||||
|
||||
private:
|
||||
void clear()
|
||||
{
|
||||
BIO_free(mem_);
|
||||
EVP_PKEY_free(key_);
|
||||
EVP_PKEY_CTX_free(ctx_);
|
||||
|
||||
mem_ = nullptr;
|
||||
ctx_ = nullptr;
|
||||
key_ = nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
EVP_PKEY* key_{};
|
||||
EVP_PKEY_CTX* ctx_{};
|
||||
BIO* mem_{};
|
||||
BIO* ioerr_{};
|
||||
char* err_{};
|
||||
};
|
||||
|
||||
CRSAOperator::CRSAOperator()
|
||||
{
|
||||
imp_ = new CRSAOperatorImp();
|
||||
err_ = new char[g_buffsize];
|
||||
}
|
||||
CRSAOperator::~CRSAOperator()
|
||||
{
|
||||
delete imp_;
|
||||
delete[] err_;
|
||||
}
|
||||
|
||||
bool CRSAOperator::encrypt_pub(const HData& public_pem, const HData& data, HData& result)
|
||||
{
|
||||
assert(imp_);
|
||||
return imp_->encrypt_pub(public_pem, data, result);
|
||||
}
|
||||
bool CRSAOperator::encrypt_pub(const char* pub_path, const HData& data, HData& result)
|
||||
{
|
||||
assert(imp_);
|
||||
return imp_->encrypt_pub(pub_path, data, result);
|
||||
}
|
||||
bool CRSAOperator::decrypt_pri(const HData& private_pem, const HData& data, HData& result)
|
||||
{
|
||||
assert(imp_);
|
||||
return imp_->decrypt_pri(private_pem, data, result);
|
||||
}
|
||||
bool CRSAOperator::decrypt_pri(const char* pri_path, const HData& data, HData& result)
|
||||
{
|
||||
assert(imp_);
|
||||
return imp_->decrypt_pri(pri_path, data, result);
|
||||
}
|
||||
bool CRSAOperator::generate_keypair(const char* pub_path, const char* pri_path)
|
||||
{
|
||||
assert(imp_);
|
||||
return imp_->generate_keypair(pub_path, pri_path);
|
||||
}
|
||||
bool CRSAOperator::generate_keypair(HData& pub, HData& pri)
|
||||
{
|
||||
assert(imp_);
|
||||
return imp_->generate_keypair(pub, pri);
|
||||
}
|
||||
const char* CRSAOperator::get_last_error() const
|
||||
{
|
||||
assert(imp_);
|
||||
imp_->get_last_error(err_, g_buffsize);
|
||||
return err_;
|
||||
}
|
||||
|
||||
} // namespace cppbox
|
32
cryp/box_rsa.h
Normal file
32
cryp/box_rsa.h
Normal file
@ -0,0 +1,32 @@
|
||||
#ifndef BOX_CRTP_RSA_H
|
||||
#define BOX_CRTP_RSA_H
|
||||
|
||||
namespace cppbox {
|
||||
|
||||
struct HData {
|
||||
unsigned char* data;
|
||||
size_t len;
|
||||
};
|
||||
|
||||
class CRSAOperatorImp;
|
||||
class CRSAOperator
|
||||
{
|
||||
private:
|
||||
CRSAOperatorImp* imp_{};
|
||||
char* err_{};
|
||||
public:
|
||||
CRSAOperator();
|
||||
~CRSAOperator();
|
||||
public:
|
||||
bool encrypt_pub(const HData& public_pem, const HData& data, HData& result);
|
||||
bool encrypt_pub(const char* pub_path, const HData& data, HData& result);
|
||||
bool decrypt_pri(const HData& private_pem, const HData& data, HData& result);
|
||||
bool decrypt_pri(const char* pri_path, const HData& data, HData& result);
|
||||
bool generate_keypair(const char* pub_path, const char* pri_path);
|
||||
bool generate_keypair(HData& pub, HData& pri);
|
||||
const char* get_last_error() const;
|
||||
};
|
||||
|
||||
} // namespace cppbox
|
||||
|
||||
#endif
|
Loading…
x
Reference in New Issue
Block a user