Initialize 初始化 OTP 配置 1. 生成随机 OTP seed 2. 使用密码加密 seed 3. 生成恢复码 4. 保存配置
(opts *InitOptions)
| 40 | // 3. 生成恢复码 |
| 41 | // 4. 保存配置 |
| 42 | func Initialize(opts *InitOptions) (seed []byte, recoveryCodes []string, err error) { |
| 43 | // 验证密码强度 |
| 44 | if err := ValidatePasswordStrength(opts.Password); err != nil { |
| 45 | return nil, nil, fmt.Errorf("密码强度不足: %w", err) |
| 46 | } |
| 47 | |
| 48 | // 1. 生成随机 OTP seed (20 字节,标准 TOTP seed 长度) |
| 49 | seed = make([]byte, 20) |
| 50 | if _, err := rand.Read(seed); err != nil { |
| 51 | return nil, nil, fmt.Errorf("生成 OTP seed 失败: %w", err) |
| 52 | } |
| 53 | |
| 54 | // 2. 生成加密参数 |
| 55 | seedSalt := make([]byte, 32) |
| 56 | if _, err := rand.Read(seedSalt); err != nil { |
| 57 | return nil, nil, fmt.Errorf("生成 seed salt 失败: %w", err) |
| 58 | } |
| 59 | |
| 60 | seedNonce := make([]byte, 12) // AES-GCM nonce 12 字节 |
| 61 | if _, err := rand.Read(seedNonce); err != nil { |
| 62 | return nil, nil, fmt.Errorf("生成 seed nonce 失败: %w", err) |
| 63 | } |
| 64 | |
| 65 | masterKeySalt := make([]byte, 32) |
| 66 | if _, err := rand.Read(masterKeySalt); err != nil { |
| 67 | return nil, nil, fmt.Errorf("生成 master key salt 失败: %w", err) |
| 68 | } |
| 69 | |
| 70 | // 3. 派生加密密钥 (PBKDF2) |
| 71 | encKey := pbkdf2.Key([]byte(opts.Password), seedSalt, 100000, 32, sha256.New) |
| 72 | |
| 73 | // 4. 加密 OTP seed |
| 74 | encryptedSeed, err := crypt.EncryptAEAD(encKey, seedNonce, seed, nil) |
| 75 | if err != nil { |
| 76 | return nil, nil, fmt.Errorf("加密 OTP seed 失败: %w", err) |
| 77 | } |
| 78 | |
| 79 | // 5. 生成恢复码 |
| 80 | var recoveryCodesHash []string |
| 81 | if opts.GenerateRecovery { |
| 82 | recoveryCodes, err = GenerateRecoveryCodes(10) |
| 83 | if err != nil { |
| 84 | return nil, nil, fmt.Errorf("生成恢复码失败: %w", err) |
| 85 | } |
| 86 | recoveryCodesHash = HashRecoveryCodes(recoveryCodes) |
| 87 | } |
| 88 | |
| 89 | // 6. 创建配置 |
| 90 | cfg := &Config{ |
| 91 | Version: "fssh-otp/v1", |
| 92 | Algorithm: opts.Algorithm, |
| 93 | Digits: opts.Digits, |
| 94 | Period: opts.Period, |
| 95 | EncryptedSeed: base64.StdEncoding.EncodeToString(encryptedSeed), |
| 96 | SeedSalt: base64.StdEncoding.EncodeToString(seedSalt), |
| 97 | SeedNonce: base64.StdEncoding.EncodeToString(seedNonce), |
| 98 | MasterKeySalt: base64.StdEncoding.EncodeToString(masterKeySalt), |
| 99 | SeedUnlockTTLSeconds: opts.SeedUnlockTTL, |
no test coverage detected