tobischo / gokeepasslib

A library to read and write keepass 2 files written in go
MIT License
251 stars 30 forks source link

Example: Write in existing DB and rootGroup #93

Closed nullsoft8411 closed 1 year ago

nullsoft8411 commented 1 year ago

Hallo @tobischo can we have a example to write in existing DB and rootGroup? the entry should be added as subGroup.

tobischo commented 1 year ago

Hi @nullsoft8411,

I don't really understand the question? While yes, there is not 1 example that does everything, it is pretty much just a combination of the reading and writing example.

The basic flow would be:

I haven't tested that against an example but it should look roughly like this:

file, err := os.Open("./example.kdbx")
if err != nil {
  log.Fatalf("Failed to open DB file: %s", err)
}

db := gokeepasslib.NewDatabase()
db.Credentials = gokeepasslib.NewPasswordCredentials("abcdefg12345678")
err = gokeepasslib.NewDecoder(file).Decode(db)
if err != nil {
  log.Fatalf("Failed to decode DB: %s", err)
}

db.UnlockProtectedEntries()

rootGroup := db.Content.Root.Groups[0]

subGroup := gokeepasslib.NewGroup()
subGroup.Name = "sub group"

subEntry := gokeepasslib.NewEntry()
subEntry.Values = append(subEntry.Values, mkValue("Title", "Another password"))
subEntry.Values = append(subEntry.Values, mkValue("UserName", "johndough"))
subEntry.Values = append(subEntry.Values, mkProtectedValue("Password", "123456"))

subGroup.Entries = append(subGroup.Entries, subEntry)

rootGroup.Groups = append(rootGroup.Groups, subGroup)

db.Content.Root.Groups[0] = rootGroup

db.LockProtectedEntries()

// and encode it into the file
keepassEncoder := gokeepasslib.NewEncoder(file)
if err := keepassEncoder.Encode(db); err != nil {
  log.Fatalf("Failed to write DB file: %s", err)
}