How to generate a finger print for a public key to validate the public key? - c

I need to validate the incoming connection in my application. The incoming connection will be sending a public key and the finger print of the public key. I need to validate this public key by calculating the finger print for the public key and then compare the calculated finger print with the finger print sent by the client. I am not able to find a way to calculate this finger print for the public key. I am using open-ssl library in C platform.
Any help regarding the calculation of this finger print of the public key will be very much appreciated.

I computed SHA1 hash which can be used as fingerprint as following:
X509 * cert = ... /*Initialize certificate*/
unsigned char buffer[SHA1_DIGEST_LENGTH];
X509_check_purpose (cert, -1, 0);
/*Copy sha1_hash from the certificate.*/
memcpy(abuffer, rCert->sha1_hash, SHA1_DIGEST_LENGTH);
I hope this would help you.

Related

how to openSSL 1.1.1 ECDH with 25519

i need to implement ecdh with 25519 using openssl.
using:
key = EC_KEY_new_by_curve_name(NID_X25519)
fails.
using this:
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(NID_X25519, NULL);
EVP_PKEY_keygen_init(pctx);
EVP_PKEY_keygen(pctx, &pkey);
seems to work but i have no idea how to export the public key in uncompressed bin format. or how to import the other sides public key.
any help?
Importing the other side's public key from raw binary format can be done with the EVP_PKEY_new_raw_public_key() function. Man page here:
https://www.openssl.org/docs/man1.1.1/man3/EVP_PKEY_new_raw_public_key.html
Exporting the public key in raw binary format is a little more tricky since there is no function to do it. You can do it in SubjectPublicKeyInfo format using i2d_PUBKEY() described here:
https://www.openssl.org/docs/man1.1.1/man3/i2d_PUBKEY.html
Fortunately the SubjectPublicKeyInfo format has the raw public key as the last 32 bytes of its output. So you can use i2d_PUBKEY() and just use the last the 32 bytes.

JDO + PostgreSQL Arrays

I've implemented store_mapping extension but it currently uses ObjectAsStringMapping. As a result I can read array values from database but any insert or update causes underlying postgresql driver error "INTEGER[]" is not "VARCHAR".
Is there any way to implement PGSQL arrays in JDO? It looks quite flexible with all that extension points. Any hints on extension points I have to implement are appreciated, thanks in advance!
Edit:
I'm using postgres int8 as a bit field as a "replacement" for arrays after I figured out that I'll be okay with 63 possible values.
Sample class would be:
#PersistenceCapable(detachable="true", table="campaigns")
public class Campaign implements Serializable {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
public Long id;
public List<Integer> regions;
}
And I think I have to implement some mapping from List to java.sql.Array but still didn't figure out how to do that. I could write extension and override default behavior but what extension-point should it be?
Looks like you need to build a custom field strategy to handle the mapping.
The key then is to transform the representation in this case to PostgreSQL array representation, namely a comma separated value (with " escaping text with any special characters but can be used on all values, double quotes are escaped by doubling them). The string is then bracketed betweed { and }. So ARRAY[1,2,3]::int[] becomes '{1,2,3}' or '{"1","2","3"}'

Adding to a collection in google-appengine

So I've been stuck on this problem for about 3 weeks now. I've read this: http://code.google.com/appengine/docs/java/datastore/jdo/relationships.html and it doesn't seem to be working out. Basically I have a persistent object, called a pool, and I need to add players into this pool. The players are also persistent objects. I have an unowned relationship between the pool and the players, where the pool has a set of player ID's (primaryKey ids...)
So things I've tried:
1) I used a Long as the primary key for both, this didn't work.
2) Tried using Key from the appengine as the primary key, and this didn't work because you can't use the implementation of Key on the client side. None of the workarounds I found work, and a data transfer object is sloppy/messy/errorprone/hackish and all kinds of bad.
3) Tried using a string as the id, like this...
#Extension(vendorName="datanucleus", key="gae.encoded-pk", value="true")
private String id;
and that didn't work either. When I try to add a string into its set, like this...
public void addPlayers(Pool pool, List<String> players) {
PersistenceManager pm = getPersistenceManagerFactory().getPersistenceManager();
try {
pm.currentTransaction().begin();
Pool oldPool = pm.getObjectById(Pool.class, pool.getID());
for(String id : players) {
oldPool.addPlayer(id);
System.out.println("Added id:" + id);
}
pm.currentTransaction().commit();
} catch (Exception e) {
pm.currentTransaction().rollback();
e.printStackTrace();
} finally {
pm.close();
}
}
it will fail silently. As in...it just doesn't persist them.
Any suggestions would be great. This is for a school project, so unfortunately I'm forced to do it in GWT using JDO. My prof and TA's aren't able to help me because they aren't familiar with GWT...funny...so this is my last resort :)
Thanks!
Although there are valid reasons to represent your relationship as a list on the 'one' side of the entity, a more usual approach is to have the entities on the 'many' side have a reference to the entity on the 'one' side. That is, instead of each Pool having a list of Players, each Player should have a reference to a single Pool that it belongs to.
Is there a reason you're not taking this approach? Have you tried it?

Fileformat for EC public/private keys?

If I wanted to store both a private and a public key in a single file, what would be the easiest format to use? Especially if I'm planning to use the BouncyCastle library for Java?
On a theoretical point of view, the public key can be recomputed from the private key (computational cost for that is slightly lower than the cost for producing a single ECDSA signature, or doing half of ECDH, so it is fast). Therefore, conceptually, you only have to store the private key, and the standard format for that is PKCS#8, which is supported by Java with java.security.spec.PKCS8EncodedKeySpec. Moreover, the PKCS#8 format includes provisions for optionally encoding the public key along the private key in the same blob, so this really looks like what you are looking for.
The tricky thing, however, is to convince the cryptographic provider (e.g. BouncyCastle) to extract the public key as such and/or recompute it. Apparently, if you create a PKCS8EncodedKeySpec from a PKCS#8-encoded EC private key which also contains the public key, BouncyCastle will be kind enough to internally keep a copy of the encoded public key and write it back if you decide to reencode the private key in PKCS#8 format. However, it does nothing else with it; it handles it as an opaque blob.
Hence you must recompute the public key. Wading through the JCE and BouncyCastle API and unimplemented bits, I found the following, which appears to work (JDK 1.6.0_24, BouncyCastle 1.46):
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Provider;
import java.security.spec.PKCS8EncodedKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.provider.JCEECPrivateKey;
import org.bouncycastle.jce.provider.JCEECPublicKey;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.jce.spec.ECPublicKeySpec;
// Create the provider and an appropriate key factory.
Provider pp = new BouncyCastleProvider();
KeyFactory kf = KeyFactory.getInstance("EC", pp);
// Decode the private key (read as a byte[] called 'buf').
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(buf);
PrivateKey sk = kf.generatePrivate(ks);
// Recompute public key.
JCEECPrivateKey priv = (JCEECPrivateKey)sk;
ECParameterSpec params = priv.getParameters();
ECPublicKeySpec pubKS = new ECPublicKeySpec(
params.getG().multiply(priv.getD()), params);
PublicKey pk = kf.generatePublic(pubKS);
// To reencode the private key.
buf = kf.getKeySpec(sk, PKCS8EncodedKeySpec.class).getEncoded();
Conceptually, I should use kf.getkeySpec() with org.bouncycastle.jce.spec.ECPrivateKeySpec instead of ruthlessly casting the private key to the JCEECPrivateKey class, but the clean method appears not to be implemented yet in BouncyCastle.
Try this (BouncyCastle v1.47, using JDK 1.7.* but I assume JDK 1.6.* will be fine too):
// Recreate the private key.
final KeyFactory kf = KeyFactory.getInstance("EC", "BC");
final PKCS8EncodedKeySpec encPrivKeySpec = new PKCS8EncodedKeySpec(rawPrivKey);
final PrivateKey privKey = kf.generatePrivate(encPrivKeySpec);
final byte[] rawPrivKey = privKey.getEncoded();
// Recreate the public key.
final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(rawPubKey);
final PublicKey pubKey = kf.generatePublic(pubKeySpec);
final byte[] rawPubKey = pubKey.getEncoded();
where rawPrivKey and rawPubKey are arrays of byte type.
I suggest you encrypt the encoded private key with a block cipher (i.e. AES) otherwise the file is subject to be stolen and then you are indefinitely exposed.

How can I map a parent-child relationship in JDO, where each parent has a list of children?

I'm new to JDO but I'm willing to use it to to make my code portable (currently I'm using AppEngine, thats why). In the following Google Talk: http://dl.google.com/io/2009/pres/W_0415_Building_Scalable_Complex_App_Engines.pdf, Brett Slatkin showed a new and efficient pattern to retrieve parent entities using child's keys [slides 23 - 25]. In his example, he didn't have any mapping of parent-child relationships for the classes in Python. I don't know how Python works, but I'm guessing in JDO, you need to specify the parent somewhere. So for the following code, how can I map MessageIndex as a child to Message:
// Message.java
#PersistenceCapable
public class Message {
#PrimaryKey
#Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
Long id;
#Persistent String sender;
#Persistent Text body;
}
// MessageIndex.java
public class MessageIndex {
#PrimaryKey
#Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
Long id;
#Persistent List<String> receivers;
}
// Query.java - Query Example
Query query = pm.newQuery("select id from MessageIndex" +
"where receivers == NameParam " +
"parameters String NameParam");
List<Key> indexes = (List<Key>) query.execute("Smith"); // List the child keys here
List<Key> keys = new List<Key>; // A place to store parent keys
for (Key k : indexes)
{
keys.add(k.getParent()); // Here, how would getParent() know who it's parent is?
}
List <Message> messages = new List <Message>
for (Key k : keys)
{
messages.add(pm.getObjectById(Message.class, k));
}
So, how can I map the parent-child relationship between Message and MessageIndex in this example? Did I convert the Python code correctly?
Any comments/suggestions are highly welcome!
P.S. The link for the video is here: http://www.google.com/events/io/2009/sessions/BuildingScalableComplexApps.html --> very interesting!
Thanks.
Never mind. I found another way of doing this. Whenever I create a Message, I'll create the MessageIndex with the same key. This way, MessageIndex is always associated with a Message because they share the same key. Now, I can simply getKey() from MessageIndex and use getObjectById() in the Message entity to get the corresponding message. I would appreciate it if anyone had any better solutions than this, but for now I'll go with this method. Thanks anyways.

Resources