From 5ce137a2c7f9bdea70a7222ade9e99a069226b9d Mon Sep 17 00:00:00 2001 From: Iru Cai Date: Tue, 20 Nov 2018 11:47:58 +0800 Subject: add mt19937 code --- source/pdf/pdf-crypt.c | 103 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/source/pdf/pdf-crypt.c b/source/pdf/pdf-crypt.c index b9cbc05f..cc333039 100644 --- a/source/pdf/pdf-crypt.c +++ b/source/pdf/pdf-crypt.c @@ -2,6 +2,109 @@ #include "mupdf/pdf.h" #include +#include + +typedef struct +{ + int n; + uint32_t MT[1248]; + uint32_t cc; +} mt19937; + +static void fcn_40c060(mt19937 *ctx) +{ + uint32_t *edi = &ctx->MT[624]; + uint32_t eax, ecx, edx; + + for (int i = 0; i < 227; i++) { + edx = ((edi[i] ^ edi[i + 1]) & 0x7fffffff) ^ edi[i]; + if (edx & 1) { + eax = 0x9908b0df; + } else { + eax = 0; + } + edx >>= 1; + edi[i - 624] = eax ^ edi[i + 397] ^ edx; + } + + uint32_t *esi = &ctx->MT[851]; + + for (int i = 0; i < 396; i++) { + ecx = ((esi[i] ^ esi[i + 1]) & 0x7fffffff) ^ esi[i]; + + if (ecx & 1) { + eax = 0x9908b0df; + } else { + eax = 0; + } + ecx >>= 1; + esi[i - 624] = eax ^ esi[i - 851] ^ ecx; + } + + ecx = ((ctx->MT[1247] ^ ctx->MT[0]) & 0x7fffffff) ^ ctx->MT[1247]; + if (ecx & 1) { + eax = 0x9908b0df; + } else { + eax = 0; + } + ecx >>= 1; + ctx->MT[623] = eax ^ ctx->MT[396] ^ ecx; + ctx->n = 0; +} + +static void fcn_40c120(mt19937* ctx) +{ + uint32_t *mt = ctx->MT; + uint32_t ecx, edx; + + for (int i = 0; i < 624; i++) { + edx = ((mt[i] ^ mt[i + 1]) & 0x7fffffff) ^ mt[i]; + + if (edx & 1) { + ecx = 0x9908b0df; + } else { + ecx = 0; + } + edx >>= 1; + + ecx ^= mt[i + 397]; + ecx ^= edx; + + mt[i + 624] = ecx; + } +} + +uint32_t mt19937_next(mt19937 *ctx) +{ + int n = ctx->n; + uint32_t eax, edx; + + if (n == 624) { + fcn_40c120(ctx); + } else if (n >= 1248) { + fcn_40c060(ctx); + } + ctx->n++; + + edx = ctx->MT[n] ^ (ctx->cc & (ctx->MT[n] >> 11)); + eax = (edx & 0xff3a58ad) << 7; + edx ^= eax; + eax = (edx & 0xffffdf8c) << 15; + edx ^= eax; + eax = edx >> 18; + return eax ^ edx; +} + +void mt19937_init(mt19937 *ctx, uint32_t seed) +{ + ctx->n = 624; + ctx->cc = ~0; + + ctx->MT[0] = seed; + for (int i = 1; i < 624; i++) { + ctx->MT[i] = 0x6c078965 * (ctx->MT[i] ^ (ctx->MT[i-1] >> 30)) + i; + } +} enum { -- cgit v1.2.3