清单 6. 加密 MongoDB 中的数据
@Test public void encryptMongoDBRecords() throws Exception { KeyStore.SecretKeyEntry pkEntry = getKeyStoreEntry(); Cryptographical crypto = AESCryptoImpl.initialize(new AESCryptoKey(pkEntry.getSecretKey())); DB db = getMongoConnection(); DBCollection coll = db.getCollection("accounts"); BasicDBObject encryptedDoc = new BasicDBObject(); encryptedDoc.put("name", crypto.encrypt("Acme Life, LLC")); coll.insert(encryptedDoc); BasicDBObject encryptedQuery = new BasicDBObject(); encryptedQuery.put("name", crypto.encrypt("Acme Life, LLC")); DBObject result = coll.findOne(encryptedQuery); String value = result.get("name").toString(); Assert.assertEquals("Acme Life, LLC", crypto.decrypt(value)); } |
我在 清单 6 中所做的第一步是,使用 getKeyStoreEntry
方法读取一个现有的密钥库。接下来获取一个 MongoDB 实例的连接,在本例中,它恰好位于 MongoHQ 上的云中。然后我会获取帐户集合(RDBMS 程序员会称之为帐户表)的链接,继续插入一个新帐户记录,其相应的名称已加密。最后,我会通过加密我的搜索字符串,搜索相同的记录(其中 name
等于加密的 “Acme Life, LLC”)。
MongoDB 中的记录看起来将类似清单 7 中所示的内容。(请注意,您加密的 “Acme Life, LLC” 字符串将与我的不同,因为您将使用不同的密钥。)