使用JCE对MongoDB中的数据执行应用程序级加密

时间:2015-04-02 14:20:34

标签: java mongodb encryption mongodb-query jce

我在MongoDB中插入以及从文档中检索以下代码。我想对存储在MongoDB中的数据执行加密。以下是插入和检索数据的代码:

MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
DBCollection coll = db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
BasicDBObject doc = new BasicDBObject("title", "MongoDB").
            append("description", "database").
            append("likes", 100).
            append("url", "http://www.vkpandey.com/mongodb/").
            append("by", "Vineet");
coll.insert(doc);
System.out.println("Document inserted successfully");*/
DBCursor cursor = coll.find();
int i=1;
while (cursor.hasNext()) { 
System.out.println("Inserted Document: "+i); 
System.out.println(cursor.next()); 
i++;
}

以下是使用JCE执行DES加密的代码:

KeyGenerator keyGen = KeyGenerator.getInstance("DES");
SecretKey secretKey = keyGen.generateKey();
Cipher desCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE,secretKey);
/* Encryption */
strDataToEncrypt = "Hello World of Encryption using DES ";
byte[] byteDataToEncrypt = strDataToEncrypt.getBytes();
byte[] byteCipherText = desCipher.doFinal(byteDataToEncrypt); 
strCipherText = new BASE64Encoder().encode(byteCipherText);
System.out.println("Cipher Text generated using DES with CBC mode and PKCS5 Padding is " +strCipherText);
/* Decryption */
desCipher.init(Cipher.DECRYPT_MODE,secretKey,desCipher.getParameters());

byte[] byteDecryptedText = desCipher.doFinal(byteCipherText);
strDecryptedText = new String(byteDecryptedText);
System.out.println(" Decrypted Text message is " +strDecryptedText);

所以请建议我使用上面的代码执行加密的方法。它基本上用于对加密算法的性能进行基准测试,而不是MongoDB中的数据。

1 个答案:

答案 0 :(得分:0)

您到底想要加密什么?如果要加密字段,可以在您尝试存储在BasicDbObject中的数据上调用加密函数,然后将其存储,然后在检索时解密。

我不确定这个基准会被证明是什么。 MongoDB与您在应用程序级别加密数据的方式无关。