extract public key from RSA private key in c++ without openssl - ios

I know RSA private key contains the information of the associated public key. How can I dump the public key from the private key? I want to do it in iOS environment without openssl. Is it possible?

yes it is possible ...
but you have to handle all the stuff about the way how the key is represented, i.e. how the specific parts of the key are stored in a file, etc
your private key consists of some numbers, usually like this:
d (private exponent), N (common modulus) P,Q (two very large primes) dP and dQ (intermediate values for a computational shortcut ... ignore them for your task)
what you want to do is to calculate PHI = (P-1)*(Q-1) and then run the extended euclidean algorithm (see wikipedia for that) for d and PHI to find the multiplicative inverse element of d mod PHI ... this element is e (public exponent)
your public key then is the tuple (e, N)

Related

How to implement custom constraint using C++?

I am trying to reimplement littledog.ipynb using C++. I find it is hard to translate the function velocity_dynamics_constraint and have 3 questions
What is the function of ad_velocity_dynamics_context? Can we ignore it?
How to reimplement velocity_dynamics_constraint using C++? Do I have to create a new class like class VelocityDynamicsConstraint : public drake::solvers::Constraint? Is three any easier way to implement it?
Why we need to consider isinstance(vars[0], AutoDiffXd) condition?
# Some code from https://github.com/RussTedrake/underactuated/blob/master/examples/littledog.ipynb
ad_velocity_dynamics_context = [
ad_plant.CreateDefaultContext() for i in range(N)
]
def velocity_dynamics_constraint(vars, context_index):
h, q, v, qn = np.split(vars, [1, 1+nq, 1+nq+nv])
if isinstance(vars[0], AutoDiffXd):
if not autoDiffArrayEqual(
q,
ad_plant.GetPositions(
ad_velocity_dynamics_context[context_index])):
ad_plant.SetPositions(
ad_velocity_dynamics_context[context_index], q)
v_from_qdot = ad_plant.MapQDotToVelocity(
ad_velocity_dynamics_context[context_index], (qn - q) / h)
else:
if not np.array_equal(q, plant.GetPositions(
context[context_index])):
plant.SetPositions(context[context_index], q)
v_from_qdot = plant.MapQDotToVelocity(context[context_index],
(qn - q) / h)
return v - v_from_qdot
for n in range(N-1):
prog.AddConstraint(partial(velocity_dynamics_constraint,
context_index=n),
lb=[0] * nv,
ub=[0] * nv,
vars=np.concatenate(
([h[n]], q[:, n], v[:, n], q[:, n + 1]))
What is the function of ad_velocity_dynamics_context? Can we ignore it?
The context caches the intermediate computation result for a given q, v, u. It is very common that several constraints are imposed on the same set of q, v, u (for example, consider at the final time, we typically have a kinematic constraint on the final state, say the robot foot has to land on the ground and its center of mass is at a certain location. At the same time we we have the velocity dynamics constraint on the final state). Hence these different constraints can share some intermediate computation result, such as the rigid transform between each adjacent links. Hence we cache the result in ad_velocity_dynamics_context, and this ad_velocity_dynamics_context can be used later when we impose other constraints.
How to reimplement velocity_dynamics_constraint using C++? Do I have to create a new class like class VelocityDynamicsConstraint : public drake::solvers::Constraint? Is there any easier way to implement it?
That is right, you will need to create a new class VelocityDynamicsConstraint. The main challenge in implementing this class is to write the three overloaded DoEval function for three scalar types (double, AutoDiffXd, symbolic::Expression). You can refer to PositionConstraint as a reference. And for the moment you can ignore the case to call DoEval(const Eigen::Ref<const AutoDiffXd>&, AutoDiffXd*) with a MultibodyPlant<double> case, and only implement the this DoEval function with MultibodyPlant<AutoDiffXd>.
Why we need to consider isinstance(vars[0], AutoDiffXd) condition?
Because when the scalar type is AutoDiffXd, we want to compare not only the value of q against the one stored in context, but also its gradient. If they are different, then we need to call SetPositions to recompute the cache. When the scalar type is double, we then only need to compare the value.

Lowering memory usage in HashMap in Rust

I'm trying to parse a very long file by using a fixed-size sliding window over it. For each such window I'd like to either insert it to a HashMap as the key with custom struct as value, or modify existing value for the window. My main problem is memory usage, since it should scale into very large quantities (up to several billions of distinct windows) and I want to reuse existing keys.
I would like to append windows (or more specifically bytes) to a vector and use the index as a key in the HashMap, but use the window under index for hash computation and key comparison. Because windows are overlapping, I will append only the part of the window which is new (if I have an input AAAB and size 3 I would have 2 windows: AAA and AAB, but would only store 4 bytes - AAAB; windows would have indices 0 and 1 respectively), which is the reason behind not keying the HM with window itself.
Here's the simplified pseudo-code, in which I omitted the minimal-input problem:
let file = // content of the file on which i can call windows()
let vec = Rc::new(RefCell::new(Vec::new())); // RefCell allows me to store Rc in the hashmap while mutating the underlying vector
let hm: HashMap<KeyStruct, ValueStruct> = HashMap::new();
for i in file.windows(FIXED_SIZE) {
let idx = vec.len();
vec.borrow_mut().push(i);
if hm.contains_key(KeyStruct::new(idx)) {
// get the key associated with i
// modify the value associated with i
// do something with the key
vec.borrow_mut().pop(); // window is already in the vector
}
else {
hm.insert(KeyStruct::new(idx), ValueStruct::new(...));
}
}
I have came up with 2 different approaches: either modifying the existing HashMap implementation so that it works as intended, or using a custom struct as key to the HashMap. Since I would only use one vector in order to store windows, I could store a Rc to it in the HashMap and then use that for lookups.
I could also create a struct which would hold both a Rc and index, using it as a key to the HashMap. The latter solution works with a vanilla HashMap, but stores a lot of redundant Rcs to the same vector. I also thought about storing a static pointer to Rc and then get Rc in unsafe blocks, but I would have to guarantee that the position of the Rc on the stack never changes and I'm not sure if I can guarantee that.
I tried to implement the first approach (custom HashMap), but it turns out that Buckets use a lot of features which are gated, and I can't compile the project using the stable compiler.
What's even worse is that I would like to get the key that is already in the HashMap on a successful lookup (because different indices can store the same window, for which the hash/cmp would be identical) and use it inside the value structure. I couldn't find a way to do this using the provided API for HashMap - the closest I get is by using entry(), which can contain an OccupiedEntry, but it doesn't have any way to retrieve the key, and there's no way to get it by unsafe memory lookups, because documentation on repr() says that the order in structs is not guaranteed in the default representation. I can store the key (or only the index) in the value struct, but that adds yet another size_of::<usize>() bytes per entry, only to store the index/key in a reachable manner, which is kept with that entry either way.
My questions are:
Is it possible to compile/reuse parts of std::collections which are not pub, such that I could modify few methods of HashMap and compile the whole project?
Is there any way of getting the key after successful lookup in the HashMap? (I even found out that libs team decided against implementing method over Entry which would allow me to get the key...)
Can you see any alternative to solutions that I mentioned?
EDIT
To clarify the problem let's consider a simple example - input ABABCBACBC and window size of 2. We should give index as a key to the HashMap, and it should get the window-size number of bytes as window starting from that index: with vector [A, A, C], index 1 and window-size 2 HashMap should try to find a hash/key for AC.
We get windows like this:
AB -> BA -> AB -> BC -> CB -> BA -> AC -> CB -> BC
First pair is AB, we append it into the empty vector and give it an index of 0.
vec = [A, B]
hm = [(0, val)]
The next pair is BA:
start with vec = [A, B]
using algorithm not shown here, I know that I have a common part between last inserted window (AB) and current window (BA), namely B
append part of the window to the existing vector, so we have vec = [A, B, A]
perform a lookup using index 1 as the index of window
it has not been found so the new key, val is inserted to HashMap
vec = [A, B, A]
hm = [(0, val0), (1, val1)]
Next up is window AB:
once again we have a common part - A
append: vec = [A, B, A, B]
lookup using index 2
it is successful, so I should delete the newly inserted part of window and get the index of the window inside vector - in this case 0
modify value, do something with the key etc...
vec = [A, B, A]
hm = [(0, val0_modified), (1, val1)]
After looping over this input i should end up with:
vec = [A, B, A, B, C, B, A, C]
and indices for pairs could be represented as: [(AB, 0), (BA, 1), (BC, 3), (CB, 4), (AC, 6)]
I do not want to modify keys. I also don't want to modify the vector with the exception of pushing/popping the window during lookup/insertion.
Sidenote: even though I still have redundant information in this particular example after putting everything into vector, it won't be the case while working with the original data.

How represent message for Elgamal EC?

I am working on my project that uses elgamal elliptic curve.
I know when the elgamal ec encrypt by following steps
Represent the message m as a point M in E(Fp).
Select k ∈R [1,n−1].
Compute C1 = kP.
Compute C2 = M +kQ.
Return(C1,C2).
Where Q is the intended recipient’s public key, P is base point.
My qusetion at number one. how represent m as a point. Is point represent one character or represent group of characters.
There's no obvious way to attach m to points in E(Fp). However, you can use variant algorithm of ElGamal such as Menezes-Vanstone Elliptic curve cryptosystem to encode a message
in a point, a good reference here(P.31).
As for java code, I suggest you do some work, and post another question on SO when you encounter a problem you really can't solve by yourself.

how to build complete certificate name, include serial number using openssl's index.txt

Problem Description:
I need to build a regular expression / pattern to find a value that can either be decimal or hex
Background Information:
I am trying to build a lua function that will lookup a cert in index.txt and return the serial number. Ultimately, I need to be able to take the full cert name and run the following command:
openssl x509 -noout -in
/etc/ssl/cert/myusername.6A756C65654063616E2E77746274732E6E6574.8F.crt
-dates
I have the logic to build the file name, all the way up to the serial number... which in the above example, is 8F.
Here's what the index.txt file looks like:
R 140320154649Z 150325040807Z 8E unknown /CN=test#gmail.com/emailAddress=test#gmail.com
V 160324050821Z 8F unknown /CN=test#yahoo.com/emailAddress=test#yahoo.com
V 160324051723Z 90 unknown /CN=test2#yahoo.com/emailAddress=test2#yahoo.com
The serial number is field 4 in the first record, and field 3 in the rest of the records.
According to the documentation https://www.openssl.org/docs/apps/x509.html, serial number can either be hex or decimal.
I'm not quite sure yet how / who determines whether it's hex or decimal (i'm modifying someone else's code that uses openssl)... but I'm wondering if there's a way to check for both. I'll only be checking the value for records that are not Revoked ...aka. ones that do not have "R" in the first column.
Thanks.
Lua unfortunately does not support grouping of patterns, so that you could make the pattern for the second timestamp optional. What you could do is check for the two-timestamp pattern first, and if no match was found (which means that match returns nil), repeat for the one-timestamp pattern:
sn = string.match(line, "^%a%s+%d+Z%s+%d+Z%s+(%x+)")
if not sn then
sn = string.match(line, "^%a%s+%d+Z%s+(%x+)")
end
Note that you could do this all in one line if you're eager:
sn = string.match(line, "^%a%s+%d+Z%s+%d+Z%s+(%x+)") or string.match(line, "^%a%s+%d+Z%s+(%x+)")
Each set of parentheses captures what is matched inside and adds a return value. For more information on patterns in Lua, see the reference manual.
local cert = {
'R 140320154649Z 150325040807Z 8E unknown /CN=test#gmail.com/emailAddress=test#gmail.com',
'V 160324050821Z 8F unknown /CN=test#yahoo.com/emailAddress=test#yahoo.com',
'V 160324051723Z 90 unknown /CN=test2#yahoo.com/emailAddress=test2#yahoo.com'
}
-- for Lua 5.1
for _, crt in ipairs(cert) do
local n3, n4 = crt:match'^%S+%s+%S+%s+(%S+)%s+(%S+)'
local serial = n3:match'^%x+$' or n4:match'^%x+$'
print(serial)
end
-- for Lua 5.2
for _, crt in ipairs(cert) do
local serial = crt:match'^%S+%s+%S+.-%f[%S](%x+)%f[%s]'
print(serial)
end

Generating an RSA Key Pair with Erlang?

Erlang has a crypto function which generates public private keys (documentation copied below). However the documentation seems vague and I can't find any example code that describes how to generate the shared prime number or the generator. Can someone post an example that generates a public/private key pair? Thanks in advance for any help!
dh_generate_key(DHParams) -> {PublicKey,PrivateKey}
dh_generate_key(PrivateKey, DHParams) -> {PublicKey,PrivateKey}
Types:
DHParameters = [P, G]
P, G = Mpint
Where P is the shared prime number and G is the shared generator.
PublicKey, PrivateKey = Mpint()
Generates a Diffie-Hellman PublicKey and PrivateKey (if not given).
You don't generate the shared prime number or the generator for Diffie-Hellman. See:
http://en.wikipedia.org/wiki/Diffie-Hellman_key_exchange
The parameters P and G are agreed to ahead of time by both sides. Using the notation of the Wikipedia article, crypto:dh_generate_key is used for steps 2 & 3 to generate a/A & b/B, and then crypto:dh_compute_key is used for steps 4 & 5 to compute the shared secret s.
For RSA, I don't know of a standard library function that generates a public/private key pair. Generating primes is a fairly involved algorithm from what I remember; I would strongly recommend you not try to code it yourself. Diffie-Hellman key pairs are not suitable for use with RSA; they are different algorithms intended for different purposes.
Generally you don't need to generate these at runtime since you can reuse the key pair. You can use any number of other sources to actually generate it. (Maybe ssh-keygen would work? And there's always OpenSSL.) To use the key pair you've created, you'd use the crypto:rsa_ public/private _ encrypt/decrypt functions.
See cutkey (https://github.com/yrashk/cutkey)
"cutkey is an Erlang app for generating RSA keys. It is implemented as
a port driver that calls OpenSSL's RSA_generate_key on a thread from
the async pool."
os:command("openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048").
You can use the crypto:generate_key/2 function to create RSA public and private keys:
For a 2048 length
{Pub, Priv} = crypto:generate_key(rsa, {2048,65537}).
Or for a 1024 length
{Pub, Priv} = crypto:generate_key(rsa, {1024,65537}).
See: https://erlang.org/doc/apps/crypto/crypto.pdf (page 37)
generate_key(Type, Params) -> {PublicKey, PrivKeyOut}
Where
Type = rsa
Params = rsa_params() =
{ModulusSizeInBits :: integer(),
PublicExponent :: key_integer()}

Resources