openssl包使用相应的算术和比较方法实现bignum
类,以对任意大小的整数执行计算。
在密码学中,modular exponent x^p %% m
有一个共同的特例,例如RSA。对于较大的p
,计算x^p
是不可行的,但可以有效地计算x^p %% m
OpenSSL在BN_mod_exp()
中实现的内容。
R是否提供了实施^.bignum
和%%.bignum
方法的任何机制,以便在评估x^y %% z
时我们可以调用此特例而不是实际计算x^p
?
答案 0 :(得分:3)
晚会但是是,这绝对是可能的,而且它在某些语言中是一种适度常见的编程技术,例如C ++,其中该技术被称为expression templates。< / p>
R,弱类型,无法完全利用模式。但仍然可以使用“轻型”版本。
简而言之,您定义了^.bignum
运算符,以便相反或立即计算结果,它返回表示“取幂运算”的代理对象。此代理对象具有一个特殊重写的%%
方法,该方法调用ExpMod实现(例如BM_mod_exp
)。它还定义了一种方法,通过评估实际的bignum
操作将其强制转换为x ^ y
。
在代码中,这可能如下所示:
# Vectorisation left as an exercise for the reader.
`^.bignum` = function (x, y)
structure(c(x, y), class = 'bignum_mod_exp_proxy')
eval_exp = function (x)
call_actual_exp(x[1], x[2])
as.bignum = function (x)
if (inherits(x, 'bignum_mod_exp_proxy'))
eval_exp(x)
else
# … implement other coercions to bignum, e.g. from `numeric`.
`%%.bignum_mod_exp_proxy` = function (x, y)
call_BN_mod_exp(x[1], x[2], y)
# Pretend that a `bignum_mod_exp_proxy` in all other contexts. E.g.:
print.bignum_mod_exp_proxy = function (x, ...)
print(eval_exp(x))
# … etc., for the rest of the `bignum` operations.
事实上,您甚至可以覆盖=.bignum_mod_exp_proxy
,<-.bignum_mod_exp_proxy
和assign.bignum_mod_exp_proxy
(将assign
转换为S3通用),以便分配z = x ^ y
热切地评估为bignum
。但是,这可能是过度的,并且每次任务都会产生开销。