Parsing X509 DSS Certificate to get P, Q, G and Y - cryptography

I am trying to parse a X509 Certificate that contains a Digital Signature Algorithm (DSA) public key.
Using the javax.security.cert.X509Certificate class and getPublicKey() method I've been able to get P, Q, G and Y:
P: 0279b05d bd36b49a 6c6bfb2d 2e43da26 052ee59d f7b5ff38 f8288907 2f2a5d8e 2acad76e ec8c343e eb96edee 11
Q: 036de1
G: 03
Y: 02790a25 22838207 4fa06715 1def9df5 474b5d84 a28b2b9b 360a7fc9 086fb2c6 9aab148f e8372ab8 66705884 6d
However, I'm not sure what format this is and how to parse it to convert it to long\BigInteger in Java.
Does anybody know how to do this conversion?
I am currently assuming it is Hex and I am parsing it as so - but I'm not 100% sure if this is correct.
Thanks,
Dave

You should already have the big integers. Here is how it goes for me:
X509Certificate xc = X509Certificate.getInstance(ecert);
PublicKey pkey = xc.getPublicKey();
DSAPublicKey dk = (DSAPublicKey)pkey;
DSAParams pp = dk.getParams();
System.out.printf("p = 0x%X\n", pp.getP());
System.out.printf("q = 0x%X\n", pp.getQ());
System.out.printf("g = 0x%X\n", pp.getG());
System.out.printf("y = 0x%X\n", dk.getY());
assuming the encoded certificate is in ecert. Interfaces DSAPublicKey and DSAParams are in java.security.interfaces.
You can also go through a KeyFactory and use the getKeySpec() method to export the public key as a DSAPublicKeySpec, which will offer the same values as BigInteger instances. I am not sure if there is a gain to go through that road, though.
What you show is probably some kind of encoding, but I am quite at a loss to know which one. Anyway, the 'Q' parameter shall be at least 160-bit wide in a proper DSA public key.

Related

How to convert raw EC key to PKCS8 without node:crypto export function

I need to convert raw EC key to pkcs8 and vice versa. I am using react-native-quick-crypto as a replacement for node:crypto. sadly, it does not include node's crypto.createPrivateKey(...).export(...) function so I am unable to use it co convert my keys properly.
This is how am I generating the key:
const ecdh = crypto.createECDH(CURVE)
ecdh.generateKeys()
const privateKey = ecdh.getPrivateKey().toString('base64')
const publicKey = ecdh.getPublicKey().toString('base64')
console.log(privateKey, publicKey)
Running following code gives me a key pair. Private key: xLIGpg9Tb5QN/8nP6AuzMoOlEqL7big8Ikiv and public key: BK432IBI+ZQrEUaL2AMI0I7qt5FmOvj6g7Taech4u0C4FHNyuVfx/gG1U1ORSw+B80zHUcFMsTF4.
Now, I am unable to convert them into pkcs8.
I see, that I can use ec-key library to do that, sadly, it does not accept raw key. But it accepts key in JWK format. So I was thinking I can derive coordinates X, Y, and D (for private key) from generated keys and use the library to transform them (and do the opposite when need to convert them back).
But I am unable to find a way, how can I derive coordinates from raw keys.
Also, if there is an easier way how to do that, I will gladly do it.

Does encrypt time less than decrypt time in RSA cryptograohy?

I going to do implementation RSA cryptography. I want know . How many times encryption faster than decryption in RSA cryptography. I try compute elapsed time in java by use System.currentTimeMillis(); but give me time encrypt = 0.05 ms while time decrypt 0.55 ms mean from that 1:11. I think this result is not rational my code is the follow
//here my key has 256 bits
for (;;) {
long begin = System.currentTimeMillis();
for (int i = 0; i < num; i++) {
decrypt();
}
long end = System.currentTimeMillis();
long time = end - begin;
if (time >= 10000) {
System.out.printf("Average Encryption takes: %.2f ms\n",
(double) time / num);
break;
}
num *= 2;
}
p = BigInteger.probablePrime(128, random);
q = BigInteger.probablePrime(128, random);
N = (p.subtract(one)).multiply(q.subtract(one));
e = BigInteger.probablePrime(32, random);
d = e.modInverse(N);
private void encrypt()
{
C= M.modPow(e,N);
}
private void decrypt()
{
RM = C.modPow(d, N);
}
please any explanation for these results
Please, don't implement RSA yourself, it is very easy to do it wrong and it takes months to write version which will be resistant to 3-4 older cryptographic attacks.
All the crypto code you’ve ever written is probably broken -- Tony Arcieri
RSA encryption is more difficult. The 'best practice' in implementing RSA is: don't implement RSA. Other people have done it better than you can. -- Matthew Green (Johns Hopkins University)
Why Cryptography Is Harder Than It Looks -- Bruce Schneier, 1997:
Most systems are not designed and implemented in concert with cryptographers, but by engineers who thought of cryptography as just another component. It's not.
In industrial implementations of RSA, encrypting using someone's public key is faster then decrypting using private key, because public key has short public exponent e, usually 65537 (0x10001). This is true, when fast exponentiation is used (method named Exponentiation_by_squaring). Time of this operation depends linearly on bit length and linearly on 1 bits count in exponent's value, both length and count are small for 65537 (17 bit length and 2 bits are in state 1).
In your pseudocode of RSA-like operation, e is 32 bit and it is usually shorter than d, therefore operation using e exponent is faster than same with d.

Is the result of a RSA encryption guaranteed to be random

I use RSACryptoServiceProvider to encrypt some small blocks of data. For the solution I'm working on, it's important that if the same piece of source data is encrypted twice with the same public key, the result (the encrypted block of data) is not the same.
I have checked this with an example and it worked like I hoped. My question is now, if this behaviour is by design and guaranteed or if I have to add some random part to the source data for guaranteeing that data blocks with the same data can not be matched anymore after encryption.
Here is the example:
byte[] data=new byte[]{1,7,8,3,4,5};
RSACryptoServiceProvider encrypter = cert.PublicKey.Key as RSACryptoServiceProvider;
byte[] encryptedData = encrypter.Encrypt(data,true);
// encryptedData has always other values in, although the source data is always
// 1,7,8,3,4,5 and the certificate is always the same (loaded from disk)
The concrete question is for .net but maybe the answer can be given in general for all RSA-implementations if it is by design?
The text-book RSA encryption algorithm is deterministic:
ciphertext = plaintext ^ encryption-exponent mod modulus
(Here ^ is integer exponentiation, mod the remainder operation.)
But as you remarked, this does not provide a good security guarantee, as an attacker which can guess the plaintext can simply verify this guess by encrypting it himself and comparing the results.
For this reason, the official RSA specifications (and also all implementations used in practice) include some (partly random) padding, so we don't actually encrypt plaintext, but pad(plaintext):
ciphertext = pad(plaintext) ^ encryption-exponent mod modulus
Decryption:
plaintext = unpad( ciphertext ^ decryption-exponent mod modulus )
Only with this padding RSA is actually a secure encryption scheme.
A similar padding is also used for RSA signatures, to avoid easy forging of signatures.

RSA private exponent determination

My question is about RSA signing.
In case of RSA signing:
encryption -> y = x^d mod n,
decryption -> x = y^e mod n
x -> original message
y -> encrypted message
n -> modulus (1024 bit)
e -> public exponent
d -> private exponent
I know x, y, n and e. Knowing these can I determine d?
If you can factor n = p*q, then d*e ≡ 1 (mod m) where m = φ(n) = (p-1)*(q-1), (φ(m) is Euler's totient function) in which case you can use the extended Euclidean algorithm to determine d from e. (d*e - k*m = 1 for some k)
All these are very easy to compute, except for the factoring, which is designed to be intractably difficult so that public-key encryption is a useful technique that cannot be decrypted unless you know the private key.
So, to answer your question in a practical sense, no, you can't derive the private key from the public key unless you can wait the hundreds or thousands of CPU-years to factor n.
Public-key encryption and decryption are inverse operations:
x = ye mod n = (xd)e mod n = xde mod n = xkφ(n)+1 mod n = x * (xφ(n))k mod n = x mod n
where (xφ(n))k = 1 mod n because of Euler's theorem.
The answer is yes under two conditions. One, somebody factors n. Two, someone slips the algorithm a mickey and convinces the signer to use one of several possible special values for x.
Applied Cryptography pages 472 and 473 describe two such schemes. I don't fully understand exactly how they would work in practice. But the solution is to use an x that cannot be fully controlled by someone who wants to determine d (aka the attacker).
There are several ways to do this, and they all involve hashing x, fiddling the value of the hash in predictable ways to remove some undesirable properties, and then signing that value. The recommended techniques for doing this are called 'padding', though there is one very excellent technique that does not count as a padding method that can be found in Practical Cryptography.
No. Otherwise a private key would be of no use.

Why RSA Decryption process takes longer time than the Encryption process?

I have some idea that it is due to some complex calculation, but i want to know about what exactly happens which takes long time than the corresponding encryption process. Any link to webpage or paper would be of great help.
Thanks
Thanks for the answers, One more Doubt, What about the Signing and verification? Will this time difference be there for Signing and verification also? Ex. Signing requires more time than Verification?
Let's call n, d and e the RSA modulus, private exponent and public exponent, respectively. The RSA decryption speed is proportional to (log d)(log n)2 (i.e. quadratic in the length of the modulus, and linear in the length of the private exponent). Similarly, the RSA encryption speed is proportional to (log e)(log n)2. The private key holder also knows the factorization of n, which can be used to speed up private key operation by a factor of about 4 (with the Chinese Remainder Theorem). For details on the involved algorithms, see the Handbook of Applied Cryptography, especially chapter 14 ("Efficient Implementation").
For proper security, the private exponent (d) must be big; it has been shown that if it is smaller than 29% of the length of the modulus (n) then the private key can be reconstructed. We do not know what is the minimum length to avoid such weaknesses, so in practice d will have about the same length than n. This means that decryption will be about cubic in the length of n.
The same provisions do not apply to the public exponent (e), which can be as small as wished for, as long as it complies with the RSA rules (e must be relatively prime to r-1 for all prime factors r of n). So it is customary that a very small e is chosen. It is so customary that there are widely deployed implementations that cannot handle big public exponents. For instance, the RSA implementation in Windows' CryptoAPI (the one used e.g. by Internet Explorer when connected to a HTTPS site with a RSA server certificate) cannot process a RSA public key if e does not fit in 32 bits. e=3 is the best possible, but e=65537 is traditional (it is an historical kind of blunder, because a very small exponent can induce a perceived weakness if RSA is used without its proper and standard padding, something which should never be done anyway). 65537 is a 17-bit long integer, whereas a typical length for n and d will be 1024 bits or more. This makes public-key operations (message encryption, signature verification) much faster than private-key operations (message decryption, signature generation).
In theory, it doesn't have to be. The encryption and decryption algorithms are essentially identical. Given:
d = decryption key
e = encryption key
n = modulus (product of primes)
c = encrypted code group
m = plaintext code group
Then:
Encryption ci = mie (mod n)
Decryption mi = cid (mod n)
The normal algorithm for raising to a power is iterative, so the time taken depends on the size of the exponent. In most cases, the pair works out with the decryption key being (usually considerably) larger than the encryption key.
It is possible to reverse that though. Just for a toy example, consider:
p=17
q=23
n=391
Here's a list of some valid encryption/decryption key pairs for this particular pair of primes:
e = 17, d = 145
e = 19, d = 315
e = 21, d = 285
e = 23, d = 199
e = 25, d = 169
e = 27, d = 339
e = 29, d = 85
e = 31, d = 159
e = 35, d = 171
e = 37, d = 333
e = 39, d = 343
e = 41, d = 249
e = 43, d = 131
e = 45, d = 133
e = 47, d = 15
e = 49, d = 273
e = 51, d = 283
e = 53, d = 93
e = 57, d = 105
e = 59, d = 179
Out of those 20 key pairs, only one has a decryption key smaller than the encryption key. In the other cases, the decryption key ranges from just under twice as big to almost 17 times as large. Of course, when the modulus is tiny like this, it's quick and easy to generate a lot of key pairs, so finding a small decryption key would be fairly easy -- with a real RSA key, however, it's not quite so trivial, and we generally just accept the first pair we find. As you can see from the list above, in that case, you're quite likely to end up with a decryption key that's considerably larger than your encryption key, and therefore decryption will end up slower than encryption. When working with ~100 digit numbers, we'd have to be quite patient to find a pair for which decryption was going to be (even close to) as fast as encryption.
The encryption power is usually chosen to be a prime of the form 2^n+1 (17, 63357) which requires a relatively few multiplication operations. The decryption value will be a much larger number as a consequence, and thus take more work to compute.
There are two factors involved in this:
On the one hand, the public exponent can be chosen to be a small number with only two 1-bits (usually 3, 17 or 65537). This means the RSA encryption operation can be done with a few modular squarings and an addition. This cannot be reversed: If you force the private exponent to be a small number, the security of the system is obviously broken.
On the other hand, the holder of the private key can store some precalculated values derived from the original primes. With those he can use the CRT algorithm to replace the single exponentiation modulo a n-bit number with two exponentiaions modulo a n/2-bit number. This is approximately four times faster than the naive way.
So for RSA key pairs with random public exponents, private key operations can actually be faster. But the effect of choosing a small public exponent is much greater than the effect of the faster algorithm, so encryption is faster in practice.
RSA Laboratories describes why pretty well
In practical applications, it is common to choose a small public exponent for the public key.
...
With the typical modular exponentiation algorithms used to implement the RSA algorithm, public key operations take O(k^2) steps, private key operations take O(k^3) steps
How much longer? Do you have any exact details?
Any way, it make sense that decryption is complicated more than encryption, since the encryption it is not in a symmetric way like 123 => abc and abc > 123.
For more details I suggest starting here.
To read about how the calculatio works, this article seems very good one http://www.di-mgt.com.au/rsa_alg.html
In short "multiply = easy, factor = hard".
Take a look at (http://en.wikipedia.org/wiki/RSA#Encryption) which references optimizations in exponentiation (http://en.wikipedia.org/wiki/Exponentiation_by_squaring#Further_applications)
The best resource I found was the following lecture on cryptography from Princeton (http://www.cs.princeton.edu/courses/archive/spr05/cos126/lectures/22.pdf)
d and e are multiplicatively inverse numbers modulo phi(n). That means that it doesn't matter witch of the two you'll choose for encryption, and witch one for decryption. You just choose once before encryption. If you want fast decryption than you choose the bigger number for encryption. It's that simple.