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());
Related
I have created a ECDSA key and now need to convert this to SSH2 key.
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA");
ECGenParameterSpec params = new ECGenParameterSpec("secp384r1");
keyGen.initialize(params);
final KeyPair keyPair = keyGen.generateKeyPair();
//format publicKey in ssh2
final ECPublicKey ecPublicKey = (ECPublicKey) keyPair.getPublic();
writeJavaECPublicKeyToSSH2(ecPublicKey) ??
How do we implement this ?
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
I've used the following code to convert the public and private key to a string
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048);
KeyPair keyPair = keyPairGen.genKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
String publicK = Base64.encodeBase64String(publicKey.getEncoded());
String privateK = Base64.encodeBase64String(privateKey.getEncoded());
Now I'm trying to convert it back to public ad private key
PublicKey publicDecoded = Base64.decodeBase64(publicK);
I'm getting error of cannot convert from byte[] to public key. So I tried like this
PublicKey publicDecoded = new SecretKeySpec(Base64.decodeBase64(publicK),"RSA");
This leads to error like below
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: Neither a public nor a private key
Looks like I'm doing wrong key conversion here. Any help would be appreciated.
I don't think you can use the SecretKeySpec with RSA.
This should do:
byte[] publicBytes = Base64.decodeBase64(publicK);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
And to decode the private use PKCS8EncodedKeySpec
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-----
I am generating a key pair on the platform using the Bouncy Castle package.
SecureRandom random = new SecureRandom();
ECKeyPairGenerator pGen = new ECKeyPairGenerator();
ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(params,random);
pGen.init(genParam);
AsymmetricCipherKeyPair pair = pGen.generateKeyPair();
Here, pair is of type AsymmetricCipherKeyPair. And, i need to generate a X509V1Certificate at the server using this pair. But, X509Certificate's setPublicKey(PublicKey pubkey) accepts only objects of type PublicKey. So I need to retrieve a PublicKey from an AsymmetricCipherKeyPair at server. But, I am getting ECPublicKeyParameters, which is not accepted in the setPublicKey method.
So, my requirement here is to get a PublicKey from an AsymmetricCipherKeyPair.
The most simple way is to use BouncyCastle as JavaCryptoProvider :
Generate KeyPair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", "BC");
ECGenParameterSpec ecsp = new ECGenParameterSpec(keyAlg);
kpg.initialize(ecsp);
KeyPair kp = kpg.generateKeyPair();
Make X509v1 Cert
X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
X500Principal dnName = new X500Principal("CN=C3");
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, 10);
certGen.setSerialNumber(keyId);
certGen.setIssuerDN(dnName);
certGen.setNotBefore(new Date());
certGen.setNotAfter(c.getTime());
certGen.setSubjectDN(dnName);
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm("SHA256withECDSA");
certGen.generate(keyPair.getPrivate(), "BC");