I'm generating Ed25519 key pairs in my Kotlin app using the BouncyCastle library and have two requirements that are easy to implement in isolation, but seemingly difficult to do in tandem:
Provide the key pair as a JCE KeyPair instance for use with a third-party SSH library
Provide the public key in OpenSSH .pub format for the user to copy and paste into a git repository provider such as GitHub (i.e. ssh-ed25519 <encoded key> <comment>)
I have two options for generating the keys using BouncyCastle, each makes only one of these requirements easy.
Generate directly using BouncyCastle generator
val generator = Ed25519KeyPairGenerator()
generator.init(Ed25519KeyGenerationParameters(SecureRandom()))
val pair = generator.generateKeyPair()
This gives me a key containing Ed25519PublicKeyParameters, which makes it super easy to get the OpenSSH .pub format using OpenSSHPublicKeyUtil provided by BouncyCastle:
"ssh-ed25519 " + toBase64(OpenSSHPublicKeyUtil.encodePublicKey(publicKey))
...but there is no obvious way to get to a JCE KeyPair from here. The BouncyCastle JCE implementation seems to use BCEdDSAPublicKey and BCEdDSAPrivateKey as wrapper classes for exactly this purpose, but their constructors are package-private.
Generate using BouncyCastle as a JCE security provider
Security.addProvider(BouncyCastleProvider())
val keyPairGenerator: KeyPairGenerator = KeyPairGenerator.getInstance(EdDSAParameterSpec.Ed25519, BouncyCastleProvider.PROVIDER_NAME)
keyPairGenerator.initialize(EdDSAParameterSpec(EdDSAParameterSpec.Ed25519), SecureRandom())
val pair = keyPairGenerator.generateKeyPair()
This gives me the JCE KeyPair I'm looking for, but no obvious way to convert it to OpenSSH .pub format. The answers in this RSA-specific question all only support DSA/RSA, or suggest libraries that also don't seem to be able to handle the Ed25519 keys. I have tried:
Apache SSHD
SSHJ
Jsch
What I think I need
Any one of:
A way to convert from BouncyCastle's AsymmetricCipherKeyPair to a JCE KeyPair
A way to get a Ed25519PublicKeyParameters instance from a BCEdDSAPublicKey wrapper so I can use BouncyCastle's OpenSSH utility method
Another way to output a BouncyCastle generated Ed25519 public key from a KeyPair in OpenSSH format
Another way/library to generate an Ed25519 keypair that will support my two requirements
Hack using reflection (wrapped into getter of extension property), following way #2 (get a Ed25519PublicKeyParameters instance from a BCEdDSAPublicKey):
val BCEdDSAPublicKey.pubKey
get() = BCEdDSAPublicKey::class.declaredMemberProperties
.find { it.returnType.javaType == AsymmetricKeyParameter::class.java }!!
.apply { isAccessible = true }
.get(this) as AsymmetricKeyParameter
I am trying to update to OpenSSL 1.1.1 from 1.0.2 and in doing so I have to convert some code. A lot of structures were made opaque in 1.1.0 and now need an accessor function. For the most part I have found something that works or a suitable workaround. However I can't seem to find any accessor function(s) or suitable way to convert the following code snippet from my code:
OBJ_obj2nid(request->sig_alg->algorithm)
Where "request" is a "X509_req_st" struct(in openssl typedefed to X509_REQ) and I want to access the sig_alg as seen in the openssl struct definition:
struct X509_req_st {
X509_REQ_INFO req_info; /* signed certificate request data */
X509_ALGOR sig_alg; /* signature algorithm */
ASN1_BIT_STRING *signature; /* signature */
CRYPTO_REF_COUNT references;
CRYPTO_RWLOCK *lock;
/* Set on live certificates for authentication purposes */
ASN1_OCTET_STRING *distinguishing_id;
};
And then access the algorithm as seen in the openssl X509_ALGOR struct definition
struct X509_algor_st {
ASN1_OBJECT *algorithm;
ASN1_TYPE *parameter;
};
I've have looked through the openssl project on github and especially the x509.h.in file where most of the accessor functions seem to be found as well as scoured the web but can't find how to do this. If there is no accessor function that can do this I'll greatly appreciate any suggestions on how I could approach this or perhaps how/where to .patch in my own accessor function.
Use X509_REQ_get_signature_nid to get the signature algorithm field. Internally, it is implemented using OBJ_obj2nid to the same member.
The equivalent function for X509 struct is also available in 1.0.2, but not the X509_REQ one.
So, in your case, the code should be:
int nid = X509_REQ_get_signature_nid(request)
You can refer this link for info:
https://www.openssl.org/docs/man1.1.1/man3/X509_REQ_get_signature_nid.html
I am writing an encryption application that requires a 64 bit key. I am currently using the following code to automatically generate a key.
Function GenerateKey() As String
' Create an instance of a symmetric algorithm. The key and the IV are generated automatically.
Dim desCrypto As DESCryptoServiceProvider = DESCryptoServiceProvider.Create()
' Use the automatically generated key for encryption.
Return ASCIIEncoding.ASCII.GetString(desCrypto.Key)
End Function
I am wanting the user to create their own key. Can I convert a user defined password (a string) into a 64 bit key that can be used?
The answer depends on how secure you want it to be, I'm no security expert so I wouldn't give advice on it.
I did see this though: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx It can be used to derives bytes from a string key and salt in the way Jodrell eluded to, and would be far better than rolling yor own.
The other constructor that might be suited after that stage is detailed here: http://msdn.microsoft.com/en-us/library/51cy2e75.aspx
I'm sure if you searched for that on the web you could find examples of how to use it.
I am trying to create a serial number checker in an app that I am writing, and it uses cryptography to encode the name and entered number against what it actually should be. I am familiar with the SHA1CryptoServiceProvider used in C#, but is there anything like this in Objective-C?
Here is sample code from C# that I want to convert to Objective-C:
string license = txtnLicense.Text;
SHA1CryptoServiceProvider provider = new SHA1CryptoServiceProvider();
string finalLicense = BitConverter.ToString(provider.ComputeHash(bytes));
bool isGood = (BitConverter.ToString(provider.ComputeHash(bytes)).Replace("-", "") == license.Replace("-", ""));
Mac OS X comes with an easy-to-use encryption and hashing library built-in called CommonCrypto. You don't have to link against anything special to use it. See the headers in /usr/include/CommonCrypto for its interface and CC_SHA1(3cc) for docs.
using openssl for license keys shows how to use SHA1. It may be a good start.
I read this article and try to do the exercise in D Programming Language, but encounter a problem in the first exercise.
(1) Display series of numbers
(1,2,3,4, 5....etc) in an infinite
loop. The program should quit if
someone hits a specific key (Say
ESCAPE key).
Of course the infinite loop is not a big problem, but the rest is. How could I grab a key hit in D/Tango? In tango FAQ it says use C function kbhit() or get(), but as I know, these are not in C standard library, and does not exist in glibc which come with my Linux machine which I use to programming.
I know I can use some 3rd party library like ncurses, but it has same problem just like kbhit() or get(), it is not standard library in C or D and not pre-installed on Windows. What I hope is that I could done this exercise use just D/Tango and could run it on both Linux and Windows machine.
How could I do it?
Here's how you do it in the D programming language:
import std.c.stdio;
import std.c.linux.termios;
termios ostate; /* saved tty state */
termios nstate; /* values for editor mode */
// Open stdin in raw mode
/* Adjust output channel */
tcgetattr(1, &ostate); /* save old state */
tcgetattr(1, &nstate); /* get base of new state */
cfmakeraw(&nstate);
tcsetattr(1, TCSADRAIN, &nstate); /* set mode */
// Read characters in raw mode
c = fgetc(stdin);
// Close
tcsetattr(1, TCSADRAIN, &ostate); // return to original mode
kbhit is indeed not part of any standard C interfaces, but can be found in conio.h.
However, you should be able to use getc/getchar from tango.stdc.stdio - I changed the FAQ you mention to reflect this.
D generally has all the C stdlib available (Tango or Phobos) so answers to this question for GNU C should work in D as well.
If tango doesn't have the needed function, generating the bindings is easy. (Take a look at CPP to cut through any macro junk.)
Thanks for both of your replies.
Unfortunately, my main development environment is Linux + GDC + Tango, so I don't have conio.h, since I don't use DMC as my C compiler.
And I also found both getc() and getchar() is also line buffered in my development environment, so it could not achieve what I wish I could do.
In the end, I've done this exercise by using GNU ncurses library. Since D could interface C library directly, so it does not take much effort. I just declare the function prototype that I used in my program, call these function and linking my program against ncurses library directly.
It works perfectly on my Linux machine, but I still not figure out how could I do this without any 3rd party library and could run on both Linux and Windows yet.
import tango.io.Stdout;
import tango.core.Thread;
// Prototype for used ncurses library function.
extern(C)
{
void * initscr();
int cbreak ();
int getch();
int endwin();
int noecho();
}
// A keyboard handler to quit the program when user hit ESC key.
void keyboardHandler ()
{
initscr();
cbreak();
noecho();
while (getch() != 27) {
}
endwin();
}
// Main Program
void main ()
{
Thread handler = new Thread (&keyboardHandler);
handler.start();
for (int i = 0; ; i++) {
Stdout.format ("{}\r\n", i).flush;
// If keyboardHandler is not ruuning, it means user hits
// ESC key, so we break the infinite loop.
if (handler.isRunning == false) {
break;
}
}
return 0;
}
As Lars pointed out, you can use _kbhit and _getch defined in conio.h and implemented in (I believe) msvcrt for Windows. Here's an article with C++ code for using _kbhit and _getch.