A privacy-first, self-hosted, fully open source personal knowledge management software, written in typescript and golang. (PERSONAL FORK)
1// SiYuan - Refactor your thinking
2// Copyright (c) 2020-present, b3log.org
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU Affero General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU Affero General Public License for more details.
13//
14// You should have received a copy of the GNU Affero General Public License
15// along with this program. If not, see <https://www.gnu.org/licenses/>.
16
17package util
18
19import (
20 "bytes"
21 "crypto/aes"
22 "crypto/cipher"
23 "encoding/hex"
24
25 "github.com/siyuan-note/logging"
26)
27
28var SK = []byte("696D897C9AA0611B")
29
30func AESEncrypt(str string) string {
31 buf := &bytes.Buffer{}
32 buf.Grow(4096)
33 _, err := hex.NewEncoder(buf).Write([]byte(str))
34 if err != nil {
35 logging.LogErrorf("encrypt failed: %s", err)
36 return ""
37 }
38 data := buf.Bytes()
39 block, err := aes.NewCipher(SK)
40 if err != nil {
41 logging.LogErrorf("encrypt failed: %s", err)
42 return ""
43 }
44 cbc := cipher.NewCBCEncrypter(block, []byte("RandomInitVector"))
45 content := data
46 content = pkcs5Padding(content, block.BlockSize())
47 crypted := make([]byte, len(content))
48 cbc.CryptBlocks(crypted, content)
49 return hex.EncodeToString(crypted)
50}
51
52func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
53 padding := blockSize - len(ciphertext)%blockSize
54 padtext := bytes.Repeat([]byte{byte(padding)}, padding)
55 return append(ciphertext, padtext...)
56}
57
58func AESDecrypt(cryptStr string) []byte {
59 crypt, err := hex.DecodeString(cryptStr)
60 if err != nil {
61 logging.LogErrorf("decrypt failed: %s", err)
62 return nil
63 }
64
65 block, err := aes.NewCipher(SK)
66 if err != nil {
67 return nil
68 }
69 cbc := cipher.NewCBCDecrypter(block, []byte("RandomInitVector"))
70 decrypted := make([]byte, len(crypt))
71 cbc.CryptBlocks(decrypted, crypt)
72 return pkcs5Trimming(decrypted)
73}
74
75func pkcs5Trimming(encrypt []byte) []byte {
76 padding := encrypt[len(encrypt)-1]
77 return encrypt[:len(encrypt)-int(padding)]
78}