Advertisement
Guest User

Untitled

a guest
Nov 17th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 5.45 KB | None | 0 0
  1. package settings
  2.  
  3. import (
  4.     "crypto/aes"
  5.     "crypto/cipher"
  6.     "crypto/rand"
  7.     "encoding/json"
  8.     "fmt"
  9.     "io"
  10.     "io/ioutil"
  11.     mathrand "math/rand"
  12.     "os"
  13.     "time"
  14. )
  15.  
  16. type urls struct {
  17.     DanbooruURL  string `json:"danbooruURL"`
  18.     SafebooruURL string `json:"safebooruURL"`
  19.     GelbooruURL  string `json:"gelbooruURL"`
  20.     KonachanURL  string `json:"konachanURL"`
  21. }
  22.  
  23. type settings struct {
  24.     BotToken          string `json:"botToken"`
  25.     DatabaseIPAddress string `json:"databaseIPAddress"`
  26.     DatabaseUsername  string `json:"databaseUsername"`
  27.     DatabasePassword  string `json:"databasePassword"`
  28.     DatabaseName      string `json:"databaseName"`
  29.     Addresses         urls   `json:"urls"`
  30.     SettingsProcessed bool   `json:"settingsProcessed"`
  31. }
  32.  
  33. type startupOptions struct {
  34.     SettingsFilePath string
  35.     AESKey           string
  36. }
  37.  
  38. var BotSettings settings
  39. var StartupOptions startupOptions
  40.  
  41. func init() {
  42.     // BotSettings = settings{}
  43.     // StartupOptions = startupOptions{}
  44.  
  45.     loadStartupOptions()
  46.     loadSettings()
  47.     if !BotSettings.SettingsProcessed {
  48.         encryptSettings()
  49.     } else {
  50.         decryptSettings()
  51.     }
  52. }
  53.  
  54. func loadStartupOptions() {
  55.     // TODO: Load the commandline arguments
  56.     if StartupOptions.SettingsFilePath == "" {
  57.         StartupOptions.SettingsFilePath = "settings.json"
  58.     }
  59. }
  60.  
  61. func loadSettings() {
  62.     if _, err := os.Stat(StartupOptions.SettingsFilePath); os.IsNotExist(err) {
  63.         createSettingsFile()
  64.     }
  65.  
  66.     dat, err := ioutil.ReadFile(StartupOptions.SettingsFilePath)
  67.     if err != nil {
  68.         fmt.Printf("[Error reading the bot settings file: %s]\r\n", err)
  69.         panic(err)
  70.     }
  71.  
  72.     fmt.Println("[Loading the settings from the settings file]")
  73.     err = json.Unmarshal([]byte(string(dat)), &BotSettings)
  74.     if err != nil {
  75.         fmt.Printf("[Error while unmarshaling the bot settings file: %s]\r\n", err)
  76.         panic(err)
  77.     }
  78. }
  79.  
  80. func decryptSettings() {
  81.     ciphertext, err := ioutil.ReadFile("myfile.data")
  82.     // if our program was unable to read the file
  83.     // print out the reason why it can't
  84.     if err != nil {
  85.         fmt.Println(err)
  86.     }
  87.  
  88.     c, err := aes.NewCipher([]byte(StartupOptions.AESKey))
  89.     if err != nil {
  90.         fmt.Println(err)
  91.     }
  92.  
  93.     gcm, err := cipher.NewGCM(c)
  94.     if err != nil {
  95.         fmt.Println(err)
  96.     }
  97.  
  98.     nonceSize := gcm.NonceSize()
  99. }
  100.  
  101. func decryptStr(ciphertext string, nonceSize int, gcm cipher.AEAD) string {
  102.     if len(ciphertext) < nonceSize {
  103.         fmt.Println(err)
  104.     }
  105.  
  106.     nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
  107.     plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
  108.     if err != nil {
  109.         fmt.Println(err)
  110.     }
  111.     fmt.Println(string(plaintext))
  112. }
  113.  
  114. func encryptSettings() {
  115.     // create a new random encryption key
  116.     key := encryptGetKey()
  117.  
  118.     // generate a new aes cipher using our 32 byte long key
  119.     c, err := aes.NewCipher(key)
  120.     if err != nil {
  121.         fmt.Printf("[Error creating a new cipher: %s]\r\n", err)
  122.         panic(err)
  123.     }
  124.  
  125.     // gcm or Galois/Counter Mode, is a mode of operation
  126.     // for symmetric key cryptographic block ciphers
  127.     // - https://en.wikipedia.org/wiki/Galois/Counter_Mode
  128.     gcm, err := cipher.NewGCM(c)
  129.     if err != nil {
  130.         fmt.Printf("[Error creating a new cipher: %s]\r\n", err)
  131.         panic(err)
  132.     }
  133.  
  134.     // creates a new byte array the size of the nonce
  135.     // which must be passed to Seal
  136.     nonce := make([]byte, gcm.NonceSize())
  137.     if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
  138.         fmt.Printf("[Error while creating nonce: %s]\r\n", err)
  139.         panic(err)
  140.     }
  141.  
  142.     cpy := BotSettings
  143.     cpy.BotToken = encryptStr(gcm, key, nonce, cpy.BotToken)
  144.     cpy.DatabaseIPAddress = encryptStr(gcm, key, nonce, cpy.DatabaseIPAddress)
  145.     cpy.DatabaseUsername = encryptStr(gcm, key, nonce, cpy.DatabaseUsername)
  146.     cpy.DatabasePassword = encryptStr(gcm, key, nonce, cpy.DatabasePassword)
  147.     cpy.SettingsProcessed = true
  148.     writeOverritedSettings(cpy)
  149.     StartupOptions.AESKey = string(key)
  150.     fmt.Println("ENCRYPTED THE '" + StartupOptions.SettingsFilePath + "' FILE WITH KEY: '" + StartupOptions.AESKey + "'")
  151. }
  152.  
  153. func encryptGetKey() []byte {
  154.     mathrand.Seed(time.Now().UnixNano())
  155.     key := make([]byte, 32)
  156.     letters := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`1234567890-=~!@#$%^&*()_+[]{};:,./<>?"
  157.     for i := 0; i < len(key); i++ {
  158.         key[i] = letters[mathrand.Intn(len(letters))]
  159.     }
  160.     return key
  161. }
  162.  
  163. func encryptStr(gcm cipher.AEAD, key []byte, nonce []byte, str string) string {
  164.     return string(gcm.Seal(nonce, nonce, []byte(BotSettings.BotToken), nil))
  165. }
  166.  
  167. func createSettingsFile() {
  168.     sfc := []byte(`{
  169.     "botToken": "token",
  170.     "databaseIPAddress": "localhost",
  171.     "databaseUsername": "username",
  172.     "databasePassword": "password",
  173.     "databaseName": "kitsune",
  174.     "urls": {
  175.         "danbooruURL": "https://danbooru.donmai.us/",
  176.         "safebooruURL": "https://safebooru.org/",
  177.         "gelbooruURL": "https://gelbooru.com/",
  178.         "konachanURL": "https://konachan.com/"
  179.     },
  180.     "settingsProcessed": false
  181. }`)
  182.     err := ioutil.WriteFile(StartupOptions.SettingsFilePath, sfc, 0644)
  183.     if err != nil {
  184.         fmt.Printf("[Error creating a new settings file: %s]\r\n", err)
  185.         panic(err)
  186.     }
  187.     fmt.Println("A new settings file has been created under the path: " + StartupOptions.SettingsFilePath + ". Please fill out the settings and re-run the bot.")
  188.     os.Exit(0)
  189. }
  190.  
  191. func writeOverritedSettings(s settings) {
  192.     d, err := json.Marshal(s)
  193.     if err != nil {
  194.         fmt.Printf("[Error while marshaling settings: %s]\r\n", err)
  195.         panic(err)
  196.     }
  197.     err = ioutil.WriteFile(StartupOptions.SettingsFilePath, d, 0644)
  198.     if err != nil {
  199.         fmt.Printf("[Error while saving overwrited settings: %s]\r\n", err)
  200.         panic(err)
  201.     }
  202. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement