给sqlite数据库加密的两种方法

一个是采用SQLCipher

Need to store sensitive information in your app? SQLCipher extends SQLite enabling transparent encryption and decryption of data using AES. Its source is available on Github.

SQLite is pluggable. Developers can create extensions and chain them into SQLite’s engine. Using this mechanism, SQLCipher embeds itself low enough in the stack to be transparent. As a developer, you simply issue queries as you normally would and all of the crypto is handled transparently.

 

SQLCipher’s author, Stephen Lombardo of Zetetic, has also released Cryptographically Secure File I/O a library that supports random access file IO on encrypted files.

 

另外一个

Strong Encryption for Cocoa / Cocoa Touch

AES is a strong encryption standard that has mostly replaced the aging  DESstandard. AES is widely used and fairly secure encryption mechanism (but I am not an expert at cryptography by any stretch of the imagination; I’m trusting experts for that opinion). AES supports three different key sizes, 128, 192, and 256 (the larger the key, the more secure the encryption and the more processing power it takes to  encrypt or decrypt). Apple uses AES-128 and AES-256 in several places in Mac OS X, including for Disk Image encryption. 

 

There are several public-domain implementations of AES. I chose a public domain implementation of AES by Philip J. Erdelsky to use as the basis some Objective-C categories that make encrypting and decrypting files and data using AES-256 easy.

The first category is on NSFileManager, and allows you to encrypt a file in the filesystem. It takes a file at a particular pathname, encrypts it using a passphrase, and then writes the encrypted contents to a new specified file location. This version has relatively low memory overhead, as it streams the data in chunks both for reading and writing, so only the chunk currently being encrypted is in memory. The category adds two methods to NSFileManager, one for encrypting, the other for decrypting. These methods are the best choice when your source data already exists in the file system, especially on the iPhone, because of how little memory it uses to do the work. Here is an example of using the category on NSFileManager to encrypt a file:

    NSError *error = nil;
    if (![[NSFileManager defaultManager] AESEncryptFile:@"/path/to/input file" toFile:@"/path/to/output file" usingPassphrase:@"My secret password" error:&error])
    {
        NSLog(@"Failed to write encrypted file. Error = %@", [[error userInfo] objectForKey:AESEncryptionErrorDescriptionKey]);
    }

There is also a category on NSData that will let you encrypt a chunk of data that’s already in memory. This version creates a new NSData object with the encrypted contents of the original NSData instance. If your data is already in memory, and you want an encrypted or decrypted version of it, then the NSDatamethods are the way to go. Here is an example of using encrypting an NSDataobject with AES:

    NSData *encryptedData = [data AESEncryptWithPassphrase:@"My secret password"];

Pretty easy, huh? Okay, now, this is a symmetric block cypher, it is not public-key encryption, so if you store your passphrase as a string in your application (as opposed to making the user enter it or storing it in the keychain) then you’re giving somebody the ability to decrypt your encrypted application data, so just be forewarned.

Also, I make no warranties about how secure this is. As far as I know, AES-256 has not been broken yet, however I cannot say for certaint that there are no weaknesses in the AES implementation I’ve used. I don’t see any obvious problems but I am not a cryptographer. I haven’t heard of any weaknesses in this particular implementation, but any use of this is completely at your own risk.

Here is a zip file containing the two categories and the AES implementation. Just add these to your Xcode project, include the appropriate headers, andencrypt away.

Oh, and, one more important thing: If you use this in an iPhone application that you plan to sell on the App Store, it may lengthen the review process, as you will have to declare that you are using encryption, and will likely have to create and upload a CCATS form and wait for Apple to review it before your app will go up for sale. Read the iTunes Connect Developer Guide for more information on CCATS and the process before deciding to use this in an iPhone application for sale, please.

UPDATE: Jim Dovey author of the terrific Output iPhone App, posted a category on NSMutableData in the comments to this post that uses the crypto libraries already available on the Mac and iPhone to do AES-256 encryption. According to Jim, this means you don’t need a CCATS form because Apple’s exporting the encryption code, not you, so check it out Thanks, Jim.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,我可以为您介绍两种gorm sqlite数据库加密的方式: 1. 对数据库中的数据进行加密: 这种方式是将数据库中的数据进行加密,保护敏感信息。您可以使用加密算法对数据进行加密,然后存储到数据库中。在读取数据时,再进行解密操作。这种方式的优点是可以保护数据的机密性,但缺点是需要在每次读写数据时进行加解密操作,可能会影响性能。 2. 对数据库文件进行加密: 这种方式是对整个数据库文件进行加密,保护整个数据库的机密性。您可以使用加密算法对数据库文件进行加密,然后在使用时解密。这种方式的优点是可以一次性对整个数据库进行加解密,不需要在每次读写数据时进行操作,但缺点是可能会增加数据库的访问时间。 以下是两种加密方式的示例代码: 1. 对数据库中的数据进行加密: ```go import ( "gorm.io/driver/sqlite" "gorm.io/gorm" "crypto/aes" "crypto/cipher" "encoding/base64" ) // 定义加密密钥 var key = []byte("0123456789abcdef") // 定义加密函数 func encrypt(data []byte) []byte { block, _ := aes.NewCipher(key) ciphertext := make([]byte, aes.BlockSize+len(data)) iv := ciphertext[:aes.BlockSize] stream := cipher.NewCTR(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], data) return ciphertext } // 定义解密函数 func decrypt(ciphertext []byte) []byte { block, _ := aes.NewCipher(key) iv := ciphertext[:aes.BlockSize] ciphertext = ciphertext[aes.BlockSize:] stream := cipher.NewCTR(block, iv) stream.XORKeyStream(ciphertext, ciphertext) return ciphertext } func main() { db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // 自动迁移模式 db.AutoMigrate(&User{}) // 创建用户 user := User{Name: "Alice", Age: 18} // 加密用户数据 encryptedData := encrypt([]byte(user.Name)) user.Name = base64.StdEncoding.EncodeToString(encryptedData) // 存储用户数据 db.Create(&user) // 查询用户 var result User db.First(&result, user.ID) // 解密用户数据 decryptedData, _ := base64.StdEncoding.DecodeString(result.Name) result.Name = string(decrypt(decryptedData)) fmt.Println(result) } ``` 2. 对数据库文件进行加密: ```go import ( "gorm.io/driver/sqlite" "gorm.io/gorm" "crypto/aes" "crypto/cipher" "io/ioutil" "os" ) // 定义加密密钥 var key = []byte("0123456789abcdef") // 定义加密函数 func encryptFile(filename string) error { plaintext, err := ioutil.ReadFile(filename) if err != nil { return err } block, _ := aes.NewCipher(key) ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] stream := cipher.NewCTR(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) return ioutil.WriteFile(filename, ciphertext, os.ModePerm) } // 定义解密函数 func decryptFile(filename string) error { ciphertext, err := ioutil.ReadFile(filename) if err != nil { return err } block, _ := aes.NewCipher(key) iv := ciphertext[:aes.BlockSize] ciphertext = ciphertext[aes.BlockSize:] stream := cipher.NewCTR(block, iv) stream.XORKeyStream(ciphertext, ciphertext) return ioutil.WriteFile(filename, ciphertext, os.ModePerm) } func main() { db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // 自动迁移模式 db.AutoMigrate(&User{}) // 创建用户 user := User{Name: "Alice", Age: 18} db.Create(&user) // 加密数据库文件 err = encryptFile("gorm.db") if err != nil { panic("failed to encrypt database file") } // 解密数据库文件 err = decryptFile("gorm.db") if err != nil { panic("failed to decrypt database file") } // 查询用户 var result User db.First(&result, user.ID) fmt.Println(result) } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值