Attach two encrypted database failed

I met a problem while attaching two encrypted database whose key are same.

Following steps can reproduce the issue.

localhost:2h zhangli.pear$ sqlcipher T/test_attach_cipher1.db 
SQLCipher version 3.30.1 2019-10-10 20:19:45
Enter ".help" for usage hints.
sqlite> pragma key='123';
ok
sqlite> .tables
c1
sqlite> ATTACH DATABASE 'T/test_attach_cipher2.db' AS c;
Error: file is not a database
sqlite> .exit

The most weird is that if .table query is ignored before attach, the problem will disappear.

localhost:2h zhangli.pear$ sqlcipher T/test_attach_cipher1.db 
SQLCipher version 3.30.1 2019-10-10 20:19:45
Enter ".help" for usage hints.
sqlite> pragma key='123';
ok
sqlite> ATTACH DATABASE 'T/test_attach_cipher2.db' AS c;
sqlite> .tables
c.c2  c1  
sqlite> .exit

I can’t figure it out, hope someone can help me.
Thanks

Hi @pearzl

In your first scenario, while the password is the same between the two databases, they each have a different database salt. Per the implementation notes, when you do not specify a KEY parameter in the attach statement, the raw key and database salt are copied over during attach. When you invoke .tables, the encryption key is derived to produce a result from the first database. A separate context is created when you attach a database, and the keyspec (representation of your encryption key and database salt) is copied over from the main database to the attached database. Because each database has a unique salt, it is unable to decrypt the content in the second database.

In the second scenario, because the encryption key has not yet be derived at the point when you perform the attach operation, each context will derive their encryption key independently. This will allow each database to decrypt their content.

You can address this issue by using the KEY specifier when attaching a database.