package crypto import "testing" func TestCipherRoundTrip(t *testing.T) { tests := []struct { name string plaintext string }{ {name: "普通文本", plaintext: "hello oci-portal"}, {name: "空串", plaintext: ""}, {name: "PEM 多行", plaintext: "-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----"}, } c, err := NewCipher("test-master-key") if err != nil { t.Fatalf("NewCipher: %v", err) } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { enc, err := c.EncryptString(tt.plaintext) if err != nil { t.Fatalf("EncryptString: %v", err) } got, err := c.DecryptString(enc) if err != nil { t.Fatalf("DecryptString: %v", err) } if got != tt.plaintext { t.Errorf("roundtrip: got %q, want %q", got, tt.plaintext) } }) } } func TestCipherWrongKeyFails(t *testing.T) { c1, _ := NewCipher("key-one") c2, _ := NewCipher("key-two") enc, err := c1.EncryptString("secret") if err != nil { t.Fatalf("EncryptString: %v", err) } if _, err := c2.DecryptString(enc); err == nil { t.Error("decrypt with wrong key: got nil error, want failure") } } func TestCipherRejectsGarbage(t *testing.T) { c, _ := NewCipher("key") tests := []struct { name string input string }{ {name: "非 base64", input: "not-base64!!"}, {name: "过短密文", input: "YWJj"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if _, err := c.DecryptString(tt.input); err == nil { t.Errorf("DecryptString(%q): got nil error, want failure", tt.input) } }) } } func TestNewCipherEmptyKey(t *testing.T) { if _, err := NewCipher(""); err == nil { t.Error("NewCipher(\"\"): got nil error, want failure") } }