如何解决PyCryptodome 上下文如何链接 AES 密码的消息?
TL;DR:PyCryptodome AES 上下文如何链接消息?
考虑这段代码:
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
exports.scheduledFunction = functions.pubsub.schedule('every 5 minutes').onRun(async (context) => {
var user = ... // Set the value of user
const db = admin.database(); // Admin SDK
const snapshot1 = await db.database().ref("...").get();
if (snapshot1.val() !== 0) {
const snapshot2 = await db.database().ref("...").get();
if (snapshot2.val() <= 7) {
await db.ref("...").update({
fieldName: firebase.database.ServerValue.increment(1)
});
//send the notification
// See https://github.com/firebase/functions-samples/blob/main/fcm-notifications/functions/index.js
} else {
return null;
}
} else {
return null;
}
});
如您所见,相同的操作使用相同的 init。向量给出不同的结果。造成这种情况的原因是重用 AES 上下文(在本例中为 from Crypto.Util.Padding import pad,unpad
from Crypto.Cipher import AES
# Create AES-128-CBC context; pad message; encrypt x2.
cipher = AES.new(b'Sixteen byte key',AES.MODE_CBC,b'16-byte init.vec')
pt = pad(b'The quick brown fox jumped over the lazy dog',16)
print(cipher.encrypt(pt).hex()) # First output: 95c44b...
print(cipher.encrypt(pt).hex()) # Second output: dfa658...
)。
问题是,PyCryptodome 如何链接加密消息以获得不同的结果。换句话说,如何将其描述为抽象算法?如何在不使用内置链接的情况下获得第二个输出?
我已经查看了 PyCryptodome 文档甚至源代码,但没有找到答案。我认为它重新创建了一个 IV 或其他东西..
解决方法
正如@Topaco 在评论中所述,PyCryptodome 使用上一个加密的最后一个块作为下一条消息的 IV。可以用以下代码演示:
from Crypto.Util.Padding import pad,unpad
from Crypto.Cipher import AES
cipher = AES.new(b'Sixteen byte key',AES.MODE_CBC,b'16-byte init.vec')
pt = pad(b'The quick brown fox jumped over the lazy dog',16)
lb = cipher.encrypt(pt)[-16:] # last block of ciphertext
# Reinitialize context - for demonstration purposes
cipher = AES.new(b'Sixteen byte key',lb)
print(cipher.encrypt(pt).hex()) # Second output: dfa658...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。