Java DSA Signature: fixed key size and signature size - java

I have the following code that signs some String data:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
keyGen.initialize(1024, random);
KeyPair pair = keyGen.generateKeyPair();
PrivateKey privateK = pair.getPrivate();
PublicKey publicK = pair.getPublic();
Signature dsa = Signature.getInstance("SHA1withDSA");
dsa.initSign(privateK);
dsa.update(data.getBytes());
byte[] signature = dsa.sign();
String hexSignature = DatatypeConverter.printHexBinary(signature);
String hexPublicK = DatatypeConverter.printHexBinary(publicK.getEncoded());
However, it's giving me a varying public key size and signature size.
For example,
Why is that? I want both the public key and the signature produced for some data to have fixed sizes.
Thank you for your help!

Related

Java RSA-OAEP generate key pair

I am trying to interface with external system which requires to send an RSA-OAEP SHA-256 public key with key size of 2048.
I am getting an error that the key has wrong bit length: '2350' .
I tried online encryption/decryption services using the generated KP and they seems to accept the key. What I am doing wrong?
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
SecureRandom random = new SecureRandom();
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");
generator.initialize(2048, random);
KeyPair pair = generator.generateKeyPair();
Key pubKey = pair.getPublic();
Key privKey = pair.getPrivate();
// I am sending pubKey.getEncoded()
Example result of the public key:
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuUKRnE07rwQ8Juegbhabv1kaHOrfou8+FNHYyhjn8jUPgwumALonsvztt4goivc1Bwm6sFwCIGnxf+2y1BI1saG3w5S1R24EUAN7efi7CS4LMEhtgJtavtWYEkEZj7OaU/BLnkB1rFAmBDU3vudSd3Gupgnbqtw7VjOH6Qrfnsh3phVr6DdHruq7SftOvCyhBucOax0hwt6enRs5UjBfbgDbbSMFaFdF4jZpE4Jnfl9gwRF51QP934Il1djPT6cezuEYlD8VAklLFPR+rOL73nvBCxLdZwdBlQHO8J8XGjWaNmAMHvyisFxkD8Ud9nC7m9MPb9J6+n3cWG7OL+C97QIDAQAB
Thank you

How to validate a public and private key pair in Java

Is there a way to validate in java if the given private key, say certain *.key file matches with the certain public key, to a certain .pub file using RSA algorithm?
You can verify if a key pair matches by
creating a challenge (random byte sequence of sufficient length)
signing the challenge with the private key
verifying the signature using the public key
This gives you a sufficiently high confidence (almost certainity) that a key pair matches if the signature verification is ok, and an absolute certainity that a key pair does not match otherwise.
Example code:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// create a challenge
byte[] challenge = new byte[10000];
ThreadLocalRandom.current().nextBytes(challenge);
// sign using the private key
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(privateKey);
sig.update(challenge);
byte[] signature = sig.sign();
// verify signature using the public key
sig.initVerify(publicKey);
sig.update(challenge);
boolean keyPairMatches = sig.verify(signature);
This also works with Elliptic Curve (EC) key pairs, but you need to use a different signature algorithm (SHA256withECDSA):
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
keyGen.initialize(new ECGenParameterSpec("sect571k1"));
...
Signature sig = Signature.getInstance("SHA256withECDSA");
The answer that was marked as being correct wastes a lot of CPU cycles. This answer is waaaay more CPU efficient:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// comment this out to verify the behavior when the keys are different
//keyPair = keyGen.generateKeyPair();
//publicKey = (RSAPublicKey) keyPair.getPublic();
boolean keyPairMatches = privateKey.getModulus().equals(publicKey.getModulus()) &&
privateKey.getPublicExponent().equals(publicKey.getPublicExponent());
(the other answer signs a message with the private key and then verifies it with the public key whereas my answer checks to see if the modulus and public exponent are the same)
boolean keyPairMatches = privateKey.getModulus().equals(publicKey.getModulus()) && privateKey.getPublicExponent().equals(publicKey.getPublicExponent());
java.security.interfaces.RSAPrivateKey doesn't have getPublicExponent() method.
org.bouncycastle.asn1.pkcs.RSAPrivateKey has getPublicExponent() method.
So,if you don't want to use bouncycastle, you have to use the sign&verify answer.

How to use passphrase for RSAPrivateKey in JAVA?

I encrypt and decrypt with RSA 2048 keys. But for additional security I need to use passphrase for RSAPrivateKey with a AES 128 method.
I can generate this keys, but I don't know how to use them in JAVA.
In my code I initialize private (witout passphrase) key (public is the same):
String PRIVATE_KEY_FILE_RSA = "src/pri.der";
File privKeyFile = new File(PRIVATE_KEY_FILE_RSA);
// read private key DER file
DataInputStream dis = new DataInputStream(new FileInputStream(privKeyFile));
byte[] privKeyBytes = new byte[(int) privKeyFile.length()];
dis.read(privKeyBytes);
dis.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
// decode private key
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
RSAPrivateKey privKey =(RSAPrivatKey) keyFactory.generatePublic(pubSpec);
And use:
Algorithm algorithm = Algorithm.RSA256(pubKey, privKey);
...
I need for any information or examples how to enter there passphrase.
This solution is better for me.
UPDATE
If the link is not working, look for not-yet-commons-ssl.
I used for not-yet-commons-ssl-0.3.11.jar.
For example:
//path to private key file
String PRIVATE_KEY_FILE_RSA = "C:\\Users\\Adey";
FileInputStream in = new FileInputStream(PRIVATE_KEY_FILE_RSA);
// passphrase - the key to decode private key
String passphrase = "somepass";
PKCS8Key pkcs8 = new PKCS8Key(in, passphrase.toCharArray());
byte[] decrypted = pkcs8.getDecryptedBytes();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decrypted);
RSAPrivateKey privKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(spec);
You have to use PBE (Password Based Encrytion) to protect private key with a password. After some research that I made for you the following code sample may help you:
//Generating keypairs
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// extract the encoded private key, this is an unencrypted PKCS#8 private key
byte[] encodedprivkey = keyPair.getPrivate().getEncoded();
// We must use a PasswordBasedEncryption algorithm in order to encrypt the private key, you may use any common algorithm supported by openssl, you can check them in the openssl documentation http://www.openssl.org/docs/apps/pkcs8.html
String MYPBEALG = "PBEWithSHA1AndDESede";
String password = "pleaseChangeit!";
int count = 20;// hash iteration count
SecureRandom random = new SecureRandom();
byte[] salt = new byte[8];
random.nextBytes(salt);
// Create PBE parameter set
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFac = SecretKeyFactory.getInstance(MYPBEALG);
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
Cipher pbeCipher = Cipher.getInstance(MYPBEALG);
// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
// Encrypt the encoded Private Key with the PBE key
byte[] ciphertext = pbeCipher.doFinal(encodedprivkey);
// Now construct PKCS #8 EncryptedPrivateKeyInfo object
AlgorithmParameters algparms = AlgorithmParameters.getInstance(MYPBEALG);
algparms.init(pbeParamSpec);
EncryptedPrivateKeyInfo encinfo = new EncryptedPrivateKeyInfo(algparms, ciphertext);
// and here we have it! a DER encoded PKCS#8 encrypted key!
byte[] encryptedPkcs8 = encinfo.getEncoded();
See also Java Cryptography Architecture (JCA) Reference Guide

Generating keyPair using Bouncy Castle

I have Java code for generating keypair using BC as follows:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
PrivateKey priv = key.getPrivate();
PublicKey pub = key.getPublic();
String privateKey = new String(Base64.encode(priv.getEncoded(), 0,priv.getEncoded().length, Base64.NO_WRAP));
String publicKey1 = new String(Base64.encode(pub.getEncoded(), 0,pub.getEncoded().length, Base64.NO_WRAP));
String publicKey = new String(Base64.encode(publicKey1.getBytes(),0, publicKey1.getBytes().length, Base64.NO_WRAP));
Now I want to do same in C# using BC. I have downloaded WP8BouncyCastle library via nuget package manager. I have written as:
var kpgen = new RsaKeyPairGenerator();
kpgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));
var keyPair = kpgen.GenerateKeyPair();
AsymmetricKeyParameter privateKey = keyPair.Private;
AsymmetricKeyParameter publicKey = keyPair.Public;
string prvKey = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(privateKey.ToString()));
string pubKey = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(publicKey.ToString()));
string pubKey1 = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(pubKey.ToString()));
But I need getEncoded() method available in Java which is not available in BC library in C#. This getEncoded() method is used to convert given key into X.509 encoded key.In case of Java, public key getting twice converted (getencoded() and getBytes()) ,I am not able to do same in C#.
Is there any solution to it?
Use the following code for private key:
PrivateKeyInfo pkInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
String privateKey = Convert.ToBase64String(pkInfo.GetDerEncoded());
and following for public:
SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
String publicKey = Convert.ToBase64String(info.GetDerEncoded());

Exception when Constructing EncryptedPrivateKeyInfo

I have generated a private key and encrypted it with a password. Now I want to load it to EncryptedPrivateKeyInfo, so that I can construct and export it into a PEM format file. Below is the code I use,
final CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
final X500Name x500Name =
new X500Name("IN", "AP", "HYD", "TEST", "TEST_ORG", "test#xyz.com");
keypair.generate(1024);
final PrivateKey privKey = keypair.getPrivateKey();
final X509Certificate[] chain = new X509Certificate[1];
long validity = 123;
chain[0] = keypair.getSelfCertificate(x500Name, new Date(),
validity * 24 * 60 * 60);
Key key = new SecretKeySpec(password.getBytes(), ALGO);
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(privKey.getEncoded());
AlgorithmParameters params = AlgorithmParameters.getInstance("DES");
params.init(encVal); // <--- exception thrown here
EncryptedPrivateKeyInfo encinfo = new EncryptedPrivateKeyInfo(params, encVal);
// displaying encrypting value
String encryptedValue = Base64.encodeBase64String(encinfo.getEncoded());
System.out.println(encryptedValue);
But while executing the above code, I get the below exception
java.io.IOException: DER input not an octet string
at sun.security.util.DerInputStream.getOctetString(DerInputStream.java:233)
at com.sun.crypto.provider.SunJCE_t.a(DashoA13*..)
at com.sun.crypto.provider.DESParameters.engineInit(DashoA13*..)
at java.security.AlgorithmParameters.init(AlgorithmParameters.java:260)
in the line params.init(encVal);. I don't get what's going wrong from the exception. Any help or suggestion will be really appreciated. Thanks in advance.
A PKCS #8 file containing an encrypted private key has the following ASN.1 structure:
EncryptedPrivateKeyInfo ::= SEQUENCE {
encryptionAlgorithm EncryptionAlgorithmIdentifier,
encryptedData EncryptedData }
Notice how the encrypted data is only part of the total data package. You need to include this data in a sequence along with the encryption algorithm identifier. Your code above produces only the encryptedData part.
I would suggest you consider using BouncyCastle. It looks like they may have improved support for PKCS#8 recently. Here's some sample code:
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = generator.generateKeyPair();
final PrivateKey privKey = keyPair.getPrivate();
JceOpenSSLPKCS8EncryptorBuilder builder =
new JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.PBE_SHA1_3DES);
builder.setIterationCount(10000);
builder.setPasssword("Hello, World!".toCharArray());
OutputEncryptor outputEncryptor = builder.build();
PKCS8Generator pkcs8Generator =
new JcaPKCS8Generator(privKey, outputEncryptor);
try (PemWriter writer = new PemWriter(new PrintWriter(System.out))) {
writer.writeObject(pkcs8Generator);
}
This will output an encrypted private key:
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIICrjAoBgoqhkiG9w0BDAEDMBoEFM1kXgdc0vzEhCwQG5G2wAaSA7POAgInEASC
AoAkBPjKkNVpt9O9+Q63WMscX0eEiGyD6/kFwI+ZgH4/s98uKDHxWTB0fQ+HA+Iy
gQC1b+QhT2HVR0DIB6lfhou4FrcJXBAqf4h0ybkfmE4xTfVQcCpgKm4uUC/FYjks
dgTMajN9NHL06nUjd/0uVsM2bzbJHXlDmPRB0LdfvuxzcGN0Vvn13IJrjRnGwTGR
nv6ZyE3gbjCRanINhMtCDMtg9Ydm7+DHC53YOeqbbhgO9/aJHpRzX/H6zLYp/oa0
GpHM6NzsTfABS8QyqR+EaoFad/XHvC9nKUDqm8LVjmKdlXrLDmpHQ4kxZqMIbijE
/Pu2IfHB0jYYa93F2i0fKkIaeve4oo3/izBn0amXVnsPMnkyrIoUUaLzI/gb/419
vp+1kmAKsEFCRIDQlDCiR9CyuePOaR0d7EckVMDU0uR9MXYAV73Y3VRXe1votrQ/
5Wi8ueio9TBDYj9wYYoYmRpz454HqJ/71k0xr5IJugJIJkUzNN9VkjK9rhgT0Vz5
wY/E1yZZepqCR1xrYgDuu/n4t63EERMo+BgkpKBMnWliU3QdQT2r4qBnma+c9lq8
IWb3y3Phl4LsX3DnLed1rUIOcQKiN2T9/yl+7eEtk8APkKuLK5DDDytgAcOQ1MIF
7Ie2939OG1c3mAwrdeOk20zf0SSbpX17MDmUoMwKsP9u8bqHahNoucjtuVSRtjSe
94xntc0fHkiIueApffxjErJOd2pmjGxJ7D2lkjV4G3AEg3vqFXk6E8nPIqIZL4qI
9KzmAFv88+QDIVTM5fheIOxZpeBkXtq2e19gCijiysqLDWL2CLuN4LVzhKCkJF6x
QGN1FcLk95ikvhI/LEn6qrih
-----END ENCRYPTED PRIVATE KEY-----

Categories

Resources