github.com/iDigitalFlame/xmt@v0.5.4/util/crypt/crypt.go (about) 1 //go:build crypt 2 // +build crypt 3 4 // Copyright (C) 2020 - 2023 iDigitalFlame 5 // 6 // This program is free software: you can redistribute it and/or modify 7 // it under the terms of the GNU General Public License as published by 8 // the Free Software Foundation, either version 3 of the License, or 9 // any later version. 10 // 11 // This program is distributed in the hope that it will be useful, 12 // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 // GNU General Public License for more details. 15 // 16 // You should have received a copy of the GNU General Public License 17 // along with this program. If not, see <https://www.gnu.org/licenses/>. 18 // 19 20 // Package crypt is a builtin package that provides compile-time encoded string 21 // values to be decoded and used when first starting up. 22 // 23 // This package should only be used with the "crypt" tag, which is auto compiled 24 // during build. 25 package crypt 26 27 import ( 28 "encoding/base64" 29 "os" 30 31 "github.com/iDigitalFlame/xmt/data/crypto/subtle" 32 "github.com/iDigitalFlame/xmt/util/xerr" 33 ) 34 35 const cryptMax = 0xFF 36 37 var ( 38 key string 39 values [cryptMax]string 40 payload string 41 ) 42 43 func init() { 44 if len(payload) == 0 || len(key) == 0 { 45 if xerr.ExtendedInfo { 46 panic("crypt: no data supplied during build") 47 } 48 os.Exit(2) 49 } 50 var ( 51 b = make([]byte, base64.URLEncoding.DecodedLen(len(payload))) 52 v, err = base64.URLEncoding.Decode(b, []byte(payload)) 53 ) 54 if err != nil || len(b) == 0 || v == 0 { 55 if xerr.ExtendedInfo { 56 panic("crypt: cannot read supplied data") 57 } 58 os.Exit(2) 59 } 60 var ( 61 k = make([]byte, base64.URLEncoding.DecodedLen(len(key))) 62 c int 63 ) 64 if c, err = base64.URLEncoding.Decode(k, []byte(key)); err != nil || len(k) == 0 || c == 0 { 65 if xerr.ExtendedInfo { 66 panic("crypt: empty or invalid crypt encoded data") 67 } 68 os.Exit(2) 69 } 70 subtle.XorOp(b[:v], k[:c]) 71 for s, e, n := 0, 0, 0; e < v && n < cryptMax; e++ { 72 if b[e] != 0 { 73 continue 74 } 75 if e-s > 0 { 76 values[n] = string(b[s:e]) 77 } 78 s, n = e+1, n+1 79 } 80 key, payload = "", "" 81 } 82 83 // Get returns the crypt value at the provided string index. 84 func Get(i uint8) string { 85 return values[i] 86 }