Personal book of passwords

file.go 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package main
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "crypto/md5"
  6. "encoding/json"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. )
  11. func save(file, passphrase string, sites []Site) error {
  12. // If the file doesn't exist then create it
  13. if _, err := os.Stat(file); os.IsNotExist(err) {
  14. _, err = os.Create(file)
  15. if err != nil {
  16. return err
  17. }
  18. }
  19. // Marshal the JSON
  20. b, err := json.Marshal(sites)
  21. if err != nil {
  22. return err
  23. }
  24. b, err = encrypt(encodeBase64(b), passphrase)
  25. if err != nil {
  26. return err
  27. }
  28. // Compress the contents
  29. var buffer bytes.Buffer
  30. gzip := gzip.NewWriter(&buffer)
  31. if err != nil {
  32. return err
  33. }
  34. gzip.Write(b)
  35. gzip.Close()
  36. // Write to the file
  37. fi, err := os.OpenFile(file, os.O_WRONLY, 0666)
  38. if err != nil {
  39. return err
  40. }
  41. _, err = fi.Write(buffer.Bytes())
  42. if err != nil {
  43. return err
  44. }
  45. fi.Close()
  46. return nil
  47. }
  48. // Read the password book
  49. func read(file, passphrase string) ([]Site, error) {
  50. // If the file doesn't exist yet no worries
  51. if _, err := os.Stat(file); os.IsNotExist(err) {
  52. return []Site{}, nil
  53. }
  54. // Bring in the compressed data
  55. fi, err := os.Open(file)
  56. if err != nil {
  57. return nil, err
  58. }
  59. // Decompress the file contents
  60. gzip, err := gzip.NewReader(fi)
  61. if err != nil {
  62. return nil, err
  63. }
  64. decompressed, err := ioutil.ReadAll(gzip)
  65. gzip.Close()
  66. // Decrypt the contents
  67. decompressed, err = decrypt(decompressed, passphrase)
  68. if err != nil {
  69. return nil, err
  70. }
  71. decompressed = decodeBase64(decompressed)
  72. // Unmarshal the JSON information
  73. var sites []Site
  74. err = json.Unmarshal(decompressed, &sites)
  75. if err != nil {
  76. return nil, err
  77. }
  78. fi.Close()
  79. return sites, nil
  80. }
  81. // Get the book name
  82. func getBookname(profile string) string {
  83. hash := md5.New()
  84. hash.Write([]byte(profile))
  85. return fmt.Sprintf("%x", string(hash.Sum(nil)))
  86. }