encryptConfigForSave creates a copy with encrypted passwords for saving to disk. Uses the cached master key only — does not prompt interactively.
(conf *MainConfig)
| 116 | // encryptConfigForSave creates a copy with encrypted passwords for saving to disk. |
| 117 | // Uses the cached master key only — does not prompt interactively. |
| 118 | func encryptConfigForSave(conf *MainConfig) (*MainConfig, error) { |
| 119 | key, err := utils.GetCachedMasterKey() |
| 120 | if err != nil || key == nil { |
| 121 | // No master key — save as plaintext |
| 122 | return conf, nil |
| 123 | } |
| 124 | |
| 125 | cp := *conf |
| 126 | cp.Main.Passwords = make([]string, len(conf.Main.Passwords)) |
| 127 | for i, pwd := range conf.Main.Passwords { |
| 128 | if utils.IsEncrypted(pwd) { |
| 129 | cp.Main.Passwords[i] = pwd |
| 130 | } else { |
| 131 | enc, err := utils.Encrypt(pwd, key) |
| 132 | if err != nil { |
| 133 | return nil, fmt.Errorf("failed to encrypt password[%d]: %w", i, err) |
| 134 | } |
| 135 | cp.Main.Passwords[i] = enc |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | cp.ServerLists = make([]ServerListConfig, len(conf.ServerLists)) |
| 140 | for i, s := range conf.ServerLists { |
| 141 | cp.ServerLists[i] = s |
| 142 | if !utils.IsEncrypted(s.Password) { |
| 143 | enc, err := utils.Encrypt(s.Password, key) |
| 144 | if err != nil { |
| 145 | return nil, fmt.Errorf("failed to encrypt server cache password[%d]: %w", i, err) |
| 146 | } |
| 147 | cp.ServerLists[i].Password = enc |
| 148 | } |
| 149 | } |
| 150 | return &cp, nil |
| 151 | } |