crypto.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. package sprig
  2. import (
  3. "bytes"
  4. "crypto"
  5. "crypto/aes"
  6. "crypto/cipher"
  7. "crypto/dsa"
  8. "crypto/ecdsa"
  9. "crypto/ed25519"
  10. "crypto/elliptic"
  11. "crypto/hmac"
  12. "crypto/rand"
  13. "crypto/rsa"
  14. "crypto/sha1"
  15. "crypto/sha256"
  16. "crypto/sha512"
  17. "crypto/x509"
  18. "crypto/x509/pkix"
  19. "encoding/asn1"
  20. "encoding/base64"
  21. "encoding/binary"
  22. "encoding/hex"
  23. "encoding/pem"
  24. "errors"
  25. "fmt"
  26. "hash/adler32"
  27. "io"
  28. "math/big"
  29. "net"
  30. "strings"
  31. "time"
  32. "github.com/google/uuid"
  33. bcrypt_lib "golang.org/x/crypto/bcrypt"
  34. "golang.org/x/crypto/scrypt"
  35. )
  36. func sha512sum(input string) string {
  37. hash := sha512.Sum512([]byte(input))
  38. return hex.EncodeToString(hash[:])
  39. }
  40. func sha256sum(input string) string {
  41. hash := sha256.Sum256([]byte(input))
  42. return hex.EncodeToString(hash[:])
  43. }
  44. func sha1sum(input string) string {
  45. hash := sha1.Sum([]byte(input))
  46. return hex.EncodeToString(hash[:])
  47. }
  48. func adler32sum(input string) string {
  49. hash := adler32.Checksum([]byte(input))
  50. return fmt.Sprintf("%d", hash)
  51. }
  52. func bcrypt(input string) string {
  53. hash, err := bcrypt_lib.GenerateFromPassword([]byte(input), bcrypt_lib.DefaultCost)
  54. if err != nil {
  55. return fmt.Sprintf("failed to encrypt string with bcrypt: %s", err)
  56. }
  57. return string(hash)
  58. }
  59. func hashSha(password string) string {
  60. s := sha1.New()
  61. s.Write([]byte(password))
  62. passwordSum := []byte(s.Sum(nil))
  63. return base64.StdEncoding.EncodeToString(passwordSum)
  64. }
  65. type HashAlgorithm string
  66. const (
  67. HashBCrypt = "bcrypt"
  68. HashSHA = "sha"
  69. )
  70. func htpasswd(username string, password string, hashAlgorithm HashAlgorithm) string {
  71. if strings.Contains(username, ":") {
  72. return fmt.Sprintf("invalid username: %s", username)
  73. }
  74. switch hashAlgorithm {
  75. case HashSHA:
  76. return fmt.Sprintf("%s:{SHA}%s", username, hashSha(password))
  77. default:
  78. return fmt.Sprintf("%s:%s", username, bcrypt(password))
  79. }
  80. }
  81. func randBytes(count int) (string, error) {
  82. buf := make([]byte, count)
  83. if _, err := rand.Read(buf); err != nil {
  84. return "", err
  85. }
  86. return base64.StdEncoding.EncodeToString(buf), nil
  87. }
  88. func uuidv4() string {
  89. return uuid.New().String()
  90. }
  91. var masterPasswordSeed = "com.lyndir.masterpassword"
  92. var passwordTypeTemplates = map[string][][]byte{
  93. "maximum": {[]byte("anoxxxxxxxxxxxxxxxxx"), []byte("axxxxxxxxxxxxxxxxxno")},
  94. "long": {[]byte("CvcvnoCvcvCvcv"), []byte("CvcvCvcvnoCvcv"), []byte("CvcvCvcvCvcvno"), []byte("CvccnoCvcvCvcv"), []byte("CvccCvcvnoCvcv"),
  95. []byte("CvccCvcvCvcvno"), []byte("CvcvnoCvccCvcv"), []byte("CvcvCvccnoCvcv"), []byte("CvcvCvccCvcvno"), []byte("CvcvnoCvcvCvcc"),
  96. []byte("CvcvCvcvnoCvcc"), []byte("CvcvCvcvCvccno"), []byte("CvccnoCvccCvcv"), []byte("CvccCvccnoCvcv"), []byte("CvccCvccCvcvno"),
  97. []byte("CvcvnoCvccCvcc"), []byte("CvcvCvccnoCvcc"), []byte("CvcvCvccCvccno"), []byte("CvccnoCvcvCvcc"), []byte("CvccCvcvnoCvcc"),
  98. []byte("CvccCvcvCvccno")},
  99. "medium": {[]byte("CvcnoCvc"), []byte("CvcCvcno")},
  100. "short": {[]byte("Cvcn")},
  101. "basic": {[]byte("aaanaaan"), []byte("aannaaan"), []byte("aaannaaa")},
  102. "pin": {[]byte("nnnn")},
  103. }
  104. var templateCharacters = map[byte]string{
  105. 'V': "AEIOU",
  106. 'C': "BCDFGHJKLMNPQRSTVWXYZ",
  107. 'v': "aeiou",
  108. 'c': "bcdfghjklmnpqrstvwxyz",
  109. 'A': "AEIOUBCDFGHJKLMNPQRSTVWXYZ",
  110. 'a': "AEIOUaeiouBCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz",
  111. 'n': "0123456789",
  112. 'o': "@&%?,=[]_:-+*$#!'^~;()/.",
  113. 'x': "AEIOUaeiouBCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz0123456789!@#$%^&*()",
  114. }
  115. func derivePassword(counter uint32, passwordType, password, user, site string) string {
  116. var templates = passwordTypeTemplates[passwordType]
  117. if templates == nil {
  118. return fmt.Sprintf("cannot find password template %s", passwordType)
  119. }
  120. var buffer bytes.Buffer
  121. buffer.WriteString(masterPasswordSeed)
  122. binary.Write(&buffer, binary.BigEndian, uint32(len(user)))
  123. buffer.WriteString(user)
  124. salt := buffer.Bytes()
  125. key, err := scrypt.Key([]byte(password), salt, 32768, 8, 2, 64)
  126. if err != nil {
  127. return fmt.Sprintf("failed to derive password: %s", err)
  128. }
  129. buffer.Truncate(len(masterPasswordSeed))
  130. binary.Write(&buffer, binary.BigEndian, uint32(len(site)))
  131. buffer.WriteString(site)
  132. binary.Write(&buffer, binary.BigEndian, counter)
  133. var hmacv = hmac.New(sha256.New, key)
  134. hmacv.Write(buffer.Bytes())
  135. var seed = hmacv.Sum(nil)
  136. var temp = templates[int(seed[0])%len(templates)]
  137. buffer.Truncate(0)
  138. for i, element := range temp {
  139. passChars := templateCharacters[element]
  140. passChar := passChars[int(seed[i+1])%len(passChars)]
  141. buffer.WriteByte(passChar)
  142. }
  143. return buffer.String()
  144. }
  145. func generatePrivateKey(typ string) string {
  146. var priv interface{}
  147. var err error
  148. switch typ {
  149. case "", "rsa":
  150. priv, err = rsa.GenerateKey(rand.Reader, 4096)
  151. case "dsa":
  152. key := new(dsa.PrivateKey)
  153. if err = dsa.GenerateParameters(&key.Parameters, rand.Reader, dsa.L2048N256); err != nil {
  154. return fmt.Sprintf("failed to generate dsa params: %s", err)
  155. }
  156. err = dsa.GenerateKey(key, rand.Reader)
  157. priv = key
  158. case "ecdsa":
  159. priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  160. case "ed25519":
  161. _, priv, err = ed25519.GenerateKey(rand.Reader)
  162. default:
  163. return "Unknown type " + typ
  164. }
  165. if err != nil {
  166. return fmt.Sprintf("failed to generate private key: %s", err)
  167. }
  168. return string(pem.EncodeToMemory(pemBlockForKey(priv)))
  169. }
  170. type DSAKeyFormat struct {
  171. Version int
  172. P, Q, G, Y, X *big.Int
  173. }
  174. func pemBlockForKey(priv interface{}) *pem.Block {
  175. switch k := priv.(type) {
  176. case *rsa.PrivateKey:
  177. return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
  178. case *dsa.PrivateKey:
  179. val := DSAKeyFormat{
  180. P: k.P, Q: k.Q, G: k.G,
  181. Y: k.Y, X: k.X,
  182. }
  183. bytes, _ := asn1.Marshal(val)
  184. return &pem.Block{Type: "DSA PRIVATE KEY", Bytes: bytes}
  185. case *ecdsa.PrivateKey:
  186. b, _ := x509.MarshalECPrivateKey(k)
  187. return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
  188. default:
  189. b, err := x509.MarshalPKCS8PrivateKey(k)
  190. if err != nil {
  191. return nil
  192. }
  193. return &pem.Block{Type: "PRIVATE KEY", Bytes: b}
  194. }
  195. }
  196. func parsePrivateKeyPEM(pemBlock string) (crypto.PrivateKey, error) {
  197. block, _ := pem.Decode([]byte(pemBlock))
  198. if block == nil {
  199. return nil, errors.New("no PEM data in input")
  200. }
  201. if block.Type == "PRIVATE KEY" {
  202. priv, err := x509.ParsePKCS8PrivateKey(block.Bytes)
  203. if err != nil {
  204. return nil, fmt.Errorf("decoding PEM as PKCS#8: %s", err)
  205. }
  206. return priv, nil
  207. } else if !strings.HasSuffix(block.Type, " PRIVATE KEY") {
  208. return nil, fmt.Errorf("no private key data in PEM block of type %s", block.Type)
  209. }
  210. switch block.Type[:len(block.Type)-12] {
  211. case "RSA":
  212. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  213. if err != nil {
  214. return nil, fmt.Errorf("parsing RSA private key from PEM: %s", err)
  215. }
  216. return priv, nil
  217. case "EC":
  218. priv, err := x509.ParseECPrivateKey(block.Bytes)
  219. if err != nil {
  220. return nil, fmt.Errorf("parsing EC private key from PEM: %s", err)
  221. }
  222. return priv, nil
  223. case "DSA":
  224. var k DSAKeyFormat
  225. _, err := asn1.Unmarshal(block.Bytes, &k)
  226. if err != nil {
  227. return nil, fmt.Errorf("parsing DSA private key from PEM: %s", err)
  228. }
  229. priv := &dsa.PrivateKey{
  230. PublicKey: dsa.PublicKey{
  231. Parameters: dsa.Parameters{
  232. P: k.P, Q: k.Q, G: k.G,
  233. },
  234. Y: k.Y,
  235. },
  236. X: k.X,
  237. }
  238. return priv, nil
  239. default:
  240. return nil, fmt.Errorf("invalid private key type %s", block.Type)
  241. }
  242. }
  243. func getPublicKey(priv crypto.PrivateKey) (crypto.PublicKey, error) {
  244. switch k := priv.(type) {
  245. case interface{ Public() crypto.PublicKey }:
  246. return k.Public(), nil
  247. case *dsa.PrivateKey:
  248. return &k.PublicKey, nil
  249. default:
  250. return nil, fmt.Errorf("unable to get public key for type %T", priv)
  251. }
  252. }
  253. type certificate struct {
  254. Cert string
  255. Key string
  256. }
  257. func buildCustomCertificate(b64cert string, b64key string) (certificate, error) {
  258. crt := certificate{}
  259. cert, err := base64.StdEncoding.DecodeString(b64cert)
  260. if err != nil {
  261. return crt, errors.New("unable to decode base64 certificate")
  262. }
  263. key, err := base64.StdEncoding.DecodeString(b64key)
  264. if err != nil {
  265. return crt, errors.New("unable to decode base64 private key")
  266. }
  267. decodedCert, _ := pem.Decode(cert)
  268. if decodedCert == nil {
  269. return crt, errors.New("unable to decode certificate")
  270. }
  271. _, err = x509.ParseCertificate(decodedCert.Bytes)
  272. if err != nil {
  273. return crt, fmt.Errorf(
  274. "error parsing certificate: decodedCert.Bytes: %s",
  275. err,
  276. )
  277. }
  278. _, err = parsePrivateKeyPEM(string(key))
  279. if err != nil {
  280. return crt, fmt.Errorf(
  281. "error parsing private key: %s",
  282. err,
  283. )
  284. }
  285. crt.Cert = string(cert)
  286. crt.Key = string(key)
  287. return crt, nil
  288. }
  289. func generateCertificateAuthority(
  290. cn string,
  291. daysValid int,
  292. ) (certificate, error) {
  293. priv, err := rsa.GenerateKey(rand.Reader, 2048)
  294. if err != nil {
  295. return certificate{}, fmt.Errorf("error generating rsa key: %s", err)
  296. }
  297. return generateCertificateAuthorityWithKeyInternal(cn, daysValid, priv)
  298. }
  299. func generateCertificateAuthorityWithPEMKey(
  300. cn string,
  301. daysValid int,
  302. privPEM string,
  303. ) (certificate, error) {
  304. priv, err := parsePrivateKeyPEM(privPEM)
  305. if err != nil {
  306. return certificate{}, fmt.Errorf("parsing private key: %s", err)
  307. }
  308. return generateCertificateAuthorityWithKeyInternal(cn, daysValid, priv)
  309. }
  310. func generateCertificateAuthorityWithKeyInternal(
  311. cn string,
  312. daysValid int,
  313. priv crypto.PrivateKey,
  314. ) (certificate, error) {
  315. ca := certificate{}
  316. template, err := getBaseCertTemplate(cn, nil, nil, daysValid)
  317. if err != nil {
  318. return ca, err
  319. }
  320. template.KeyUsage = x509.KeyUsageKeyEncipherment |
  321. x509.KeyUsageDigitalSignature |
  322. x509.KeyUsageCertSign
  323. template.IsCA = true
  324. ca.Cert, ca.Key, err = getCertAndKey(template, priv, template, priv)
  325. return ca, err
  326. }
  327. func generateSelfSignedCertificate(
  328. cn string,
  329. ips []interface{},
  330. alternateDNS []interface{},
  331. daysValid int,
  332. ) (certificate, error) {
  333. priv, err := rsa.GenerateKey(rand.Reader, 2048)
  334. if err != nil {
  335. return certificate{}, fmt.Errorf("error generating rsa key: %s", err)
  336. }
  337. return generateSelfSignedCertificateWithKeyInternal(cn, ips, alternateDNS, daysValid, priv)
  338. }
  339. func generateSelfSignedCertificateWithPEMKey(
  340. cn string,
  341. ips []interface{},
  342. alternateDNS []interface{},
  343. daysValid int,
  344. privPEM string,
  345. ) (certificate, error) {
  346. priv, err := parsePrivateKeyPEM(privPEM)
  347. if err != nil {
  348. return certificate{}, fmt.Errorf("parsing private key: %s", err)
  349. }
  350. return generateSelfSignedCertificateWithKeyInternal(cn, ips, alternateDNS, daysValid, priv)
  351. }
  352. func generateSelfSignedCertificateWithKeyInternal(
  353. cn string,
  354. ips []interface{},
  355. alternateDNS []interface{},
  356. daysValid int,
  357. priv crypto.PrivateKey,
  358. ) (certificate, error) {
  359. cert := certificate{}
  360. template, err := getBaseCertTemplate(cn, ips, alternateDNS, daysValid)
  361. if err != nil {
  362. return cert, err
  363. }
  364. cert.Cert, cert.Key, err = getCertAndKey(template, priv, template, priv)
  365. return cert, err
  366. }
  367. func generateSignedCertificate(
  368. cn string,
  369. ips []interface{},
  370. alternateDNS []interface{},
  371. daysValid int,
  372. ca certificate,
  373. ) (certificate, error) {
  374. priv, err := rsa.GenerateKey(rand.Reader, 2048)
  375. if err != nil {
  376. return certificate{}, fmt.Errorf("error generating rsa key: %s", err)
  377. }
  378. return generateSignedCertificateWithKeyInternal(cn, ips, alternateDNS, daysValid, ca, priv)
  379. }
  380. func generateSignedCertificateWithPEMKey(
  381. cn string,
  382. ips []interface{},
  383. alternateDNS []interface{},
  384. daysValid int,
  385. ca certificate,
  386. privPEM string,
  387. ) (certificate, error) {
  388. priv, err := parsePrivateKeyPEM(privPEM)
  389. if err != nil {
  390. return certificate{}, fmt.Errorf("parsing private key: %s", err)
  391. }
  392. return generateSignedCertificateWithKeyInternal(cn, ips, alternateDNS, daysValid, ca, priv)
  393. }
  394. func generateSignedCertificateWithKeyInternal(
  395. cn string,
  396. ips []interface{},
  397. alternateDNS []interface{},
  398. daysValid int,
  399. ca certificate,
  400. priv crypto.PrivateKey,
  401. ) (certificate, error) {
  402. cert := certificate{}
  403. decodedSignerCert, _ := pem.Decode([]byte(ca.Cert))
  404. if decodedSignerCert == nil {
  405. return cert, errors.New("unable to decode certificate")
  406. }
  407. signerCert, err := x509.ParseCertificate(decodedSignerCert.Bytes)
  408. if err != nil {
  409. return cert, fmt.Errorf(
  410. "error parsing certificate: decodedSignerCert.Bytes: %s",
  411. err,
  412. )
  413. }
  414. signerKey, err := parsePrivateKeyPEM(ca.Key)
  415. if err != nil {
  416. return cert, fmt.Errorf(
  417. "error parsing private key: %s",
  418. err,
  419. )
  420. }
  421. template, err := getBaseCertTemplate(cn, ips, alternateDNS, daysValid)
  422. if err != nil {
  423. return cert, err
  424. }
  425. cert.Cert, cert.Key, err = getCertAndKey(
  426. template,
  427. priv,
  428. signerCert,
  429. signerKey,
  430. )
  431. return cert, err
  432. }
  433. func getCertAndKey(
  434. template *x509.Certificate,
  435. signeeKey crypto.PrivateKey,
  436. parent *x509.Certificate,
  437. signingKey crypto.PrivateKey,
  438. ) (string, string, error) {
  439. signeePubKey, err := getPublicKey(signeeKey)
  440. if err != nil {
  441. return "", "", fmt.Errorf("error retrieving public key from signee key: %s", err)
  442. }
  443. derBytes, err := x509.CreateCertificate(
  444. rand.Reader,
  445. template,
  446. parent,
  447. signeePubKey,
  448. signingKey,
  449. )
  450. if err != nil {
  451. return "", "", fmt.Errorf("error creating certificate: %s", err)
  452. }
  453. certBuffer := bytes.Buffer{}
  454. if err := pem.Encode(
  455. &certBuffer,
  456. &pem.Block{Type: "CERTIFICATE", Bytes: derBytes},
  457. ); err != nil {
  458. return "", "", fmt.Errorf("error pem-encoding certificate: %s", err)
  459. }
  460. keyBuffer := bytes.Buffer{}
  461. if err := pem.Encode(
  462. &keyBuffer,
  463. pemBlockForKey(signeeKey),
  464. ); err != nil {
  465. return "", "", fmt.Errorf("error pem-encoding key: %s", err)
  466. }
  467. return certBuffer.String(), keyBuffer.String(), nil
  468. }
  469. func getBaseCertTemplate(
  470. cn string,
  471. ips []interface{},
  472. alternateDNS []interface{},
  473. daysValid int,
  474. ) (*x509.Certificate, error) {
  475. ipAddresses, err := getNetIPs(ips)
  476. if err != nil {
  477. return nil, err
  478. }
  479. dnsNames, err := getAlternateDNSStrs(alternateDNS)
  480. if err != nil {
  481. return nil, err
  482. }
  483. serialNumberUpperBound := new(big.Int).Lsh(big.NewInt(1), 128)
  484. serialNumber, err := rand.Int(rand.Reader, serialNumberUpperBound)
  485. if err != nil {
  486. return nil, err
  487. }
  488. return &x509.Certificate{
  489. SerialNumber: serialNumber,
  490. Subject: pkix.Name{
  491. CommonName: cn,
  492. },
  493. IPAddresses: ipAddresses,
  494. DNSNames: dnsNames,
  495. NotBefore: time.Now(),
  496. NotAfter: time.Now().Add(time.Hour * 24 * time.Duration(daysValid)),
  497. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  498. ExtKeyUsage: []x509.ExtKeyUsage{
  499. x509.ExtKeyUsageServerAuth,
  500. x509.ExtKeyUsageClientAuth,
  501. },
  502. BasicConstraintsValid: true,
  503. }, nil
  504. }
  505. func getNetIPs(ips []interface{}) ([]net.IP, error) {
  506. if ips == nil {
  507. return []net.IP{}, nil
  508. }
  509. var ipStr string
  510. var ok bool
  511. var netIP net.IP
  512. netIPs := make([]net.IP, len(ips))
  513. for i, ip := range ips {
  514. ipStr, ok = ip.(string)
  515. if !ok {
  516. return nil, fmt.Errorf("error parsing ip: %v is not a string", ip)
  517. }
  518. netIP = net.ParseIP(ipStr)
  519. if netIP == nil {
  520. return nil, fmt.Errorf("error parsing ip: %s", ipStr)
  521. }
  522. netIPs[i] = netIP
  523. }
  524. return netIPs, nil
  525. }
  526. func getAlternateDNSStrs(alternateDNS []interface{}) ([]string, error) {
  527. if alternateDNS == nil {
  528. return []string{}, nil
  529. }
  530. var dnsStr string
  531. var ok bool
  532. alternateDNSStrs := make([]string, len(alternateDNS))
  533. for i, dns := range alternateDNS {
  534. dnsStr, ok = dns.(string)
  535. if !ok {
  536. return nil, fmt.Errorf(
  537. "error processing alternate dns name: %v is not a string",
  538. dns,
  539. )
  540. }
  541. alternateDNSStrs[i] = dnsStr
  542. }
  543. return alternateDNSStrs, nil
  544. }
  545. func encryptAES(password string, plaintext string) (string, error) {
  546. if plaintext == "" {
  547. return "", nil
  548. }
  549. key := make([]byte, 32)
  550. copy(key, []byte(password))
  551. block, err := aes.NewCipher(key)
  552. if err != nil {
  553. return "", err
  554. }
  555. content := []byte(plaintext)
  556. blockSize := block.BlockSize()
  557. padding := blockSize - len(content)%blockSize
  558. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  559. content = append(content, padtext...)
  560. ciphertext := make([]byte, aes.BlockSize+len(content))
  561. iv := ciphertext[:aes.BlockSize]
  562. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  563. return "", err
  564. }
  565. mode := cipher.NewCBCEncrypter(block, iv)
  566. mode.CryptBlocks(ciphertext[aes.BlockSize:], content)
  567. return base64.StdEncoding.EncodeToString(ciphertext), nil
  568. }
  569. func decryptAES(password string, crypt64 string) (string, error) {
  570. if crypt64 == "" {
  571. return "", nil
  572. }
  573. key := make([]byte, 32)
  574. copy(key, []byte(password))
  575. crypt, err := base64.StdEncoding.DecodeString(crypt64)
  576. if err != nil {
  577. return "", err
  578. }
  579. block, err := aes.NewCipher(key)
  580. if err != nil {
  581. return "", err
  582. }
  583. iv := crypt[:aes.BlockSize]
  584. crypt = crypt[aes.BlockSize:]
  585. decrypted := make([]byte, len(crypt))
  586. mode := cipher.NewCBCDecrypter(block, iv)
  587. mode.CryptBlocks(decrypted, crypt)
  588. return string(decrypted[:len(decrypted)-int(decrypted[len(decrypted)-1])]), nil
  589. }