JWT for Android with secret key - android

I have to get a JWT using the SHA-256 algorithm and a secret key (for example "blablablamysecretkey").
Despite checking SO, several libraries and their documentations I don't know yet how to perform this.
If I use this library https://github.com/jwtk/jjwt (one of the most used) this is the code sample:
Key key = MacProvider.generateKey();
String s = Jwts.builder().setSubject("stringtoencode").signWith(SignatureAlgorithm.HS512, key).compact();
Since I have to use SHA-256 algorithm I guess that I should use:
Key key = MacProvider.generateKey();
String s = Jwts.builder().setSubject("stringtoencode").signWith(SignatureAlgorithm.HS256, key).compact();
My problem is that this sample (and all of the samples I've seen by the way) use Key key = MacProvider.generateKey();, and if I'm not wrong this generates a generic key. In fact this is what the documentation says:
// We need a signing key, so we'll create one just for this example. Usually
// the key would be read from your application configuration instead.
So my problem is how could I convert my secret key (string) into something of Key class?

MacProvider.generateKey() generates a random secret key, which is safer than using a passphrase. Keys need to be chosen at random. Read this post if you want to know how hmac keys have to be generated https://security.stackexchange.com/questions/95972/what-are-requirements-for-hmac-secret-key
// We need a signing key, so we'll create one just for this example. Usually
// the key would be read from your application configuration instead.
The text you have highlighted means that you have to persist the key in your server in order to verify JWT signature when a client sends a token. HMAC keys are symmetric, the key is used both for sign and verify
If you want to generate a Key from a passphrase String use
byte hmacKey[] = passphrase.getBytes(StandardCharsets.UTF8);
Key key = new SecretKeySpec(hmacKey,signatureAlgorithm.getJcaName());

Related

We need to encrypt a product serial number, which has to be decrypted in an App

We have a physical product with an QRCode, like this:
http://example.com/product/[encryptedProductKey]
We need to check in an app when the qrcode is scanned if the product key is valid and was made by us.
The qrcode will be lasered onto the product and cannot be changed afterwards.
Unfortunately we are a small startup and noone here really knows about encryption. Is there some kind of dummy approach to this?
You probably don't actually need encryption but rather a MAC: Message Authentication Code or a Digital Signature.
If you are both generating and verifying the codes then a MAC is sufficient (I assume this is the case?).
In which case, the product code can be a random set of characters (cryptographically strong random number) and the HMAC (Hash based Message Authentication Code). It could be quite long but would be a simple solution.
The steps would be something like (the below is pseudo code):
Generate a strong secret key that you use to generate and verify codes (don't share this)
Generate a product code:
code = cryptoRandom(16) // 16 strong random bytes
tag = HMAC(code, secretKey)
Encode the key say with Base64
Give the resulting base64 string to your customer
To verify the key:
Split the decoded product customer key string into the code and tag
Generate the tag from the code
tag = HMAC(code, secretKey)
Check that the tag that you generate matches the tag in the customer key
secureCompare(tag, tagFromCustomer)
Note that you must not use == to compare the tags as this will be vulnerable to timing attacks. Your language should have a secure compare library. See What's the difference between a secure compare and a simple ==(=)
As an alternative, if you want to keep the customer key to 32-bytes in length you could take the below approach. However, this would require that you keep a secret key for every customer.
Generate a secret key for the customer
Use that key to generate a customer key by using the HMAC of a zero string (say 16)
code = HMAC("0000000000000000", customerSecretKey)
Give the customer the code
To verify, use the customers secret key to verify
secureCompare(customerCode, HMAC("0000000000000000", customerSecretKey))
For this to be secure, the customer keys must be secret AND unique.

"Your app contains unsafe cryptographic encryption patterns" - How I can get rid of this warning?

Few days ago, In "Pre-launch report for APK" in Google Play Console, it start to flag me
Unsafe encryption
Detected in APK ???
Your app contains unsafe cryptographic encryption patterns. Please see this Google Help Centre article for details.
Vulnerable classes:
c.j.a.s.J.b
However, since the early day of APK, I do not change anything in encryption code/ description code. Hence, I'm not sure why Google starts to warn me on recent APK?
Any idea how to resolve? As, the information for vulnerable classes c.j.a.s.J.b is not helpful.
I try to use Proguard + mapping.txt to retrace c.j.a.s.J.b but able to figure what class is that.
Any idea how I can get rid of Google security warning?
The google play suggests with vulnerable classes with the function name, you can see in the dialog.
Review your app for statically computed keys, initialization vectors, and/or salts that are used in cryptographic encryption operations and ensure that these values are constructed safely
For example :
public byte[] encryptionUtil(String key, String iv, byte[] plainText) {
Cipher cipher = Cipher.getInstance(“AES/GCM/NoPadding”);
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), “AES”);
GCMParameterSpec paramSpec = new GCMParameterSpec(256, iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, paramSpec);
return cipher.doFinal(plainText);
}
And you are calling a function as:
byte[] cipherText = encryptionUtil(“abcdef...”, “010203040506”, plainText);
Here your encryption key “abcdef...” is provides as a static string. A statically computed value is a value that is the same on every execution of your app. Statically computed cryptographic values can be extracted from your app and used to attack your app’s encrypted data.
So you can use EncryptedSharedPreferences to store locally data
Reference link https://developer.android.com/reference/androidx/security/crypto/EncryptedSharedPreferences
OR
Jetpack Security
For more details:
Remediation for Unsafe Cryptographic Encryption
I think you are using some encryption/decryption code with statically stored key.
A statically computed value is a value that is the same on every execution of your app. Statically computed cryptographic values can be extracted from your app and used to attack your app’s encrypted data.
So Google give this warning to change that stored key with dynamically generated key.
For that you can generate different key on every launch.
To solve this problem generate dynamic encryption/decryption key on every launch.
For that you can find more info here https://developer.android.com/jetpack/androidx/releases/security

RSA key signing and verifying in Java(Android)

I am having a slight problem with understanding the concept of RSA signing and verifying.
The problem is that I can create key pair (public and private key) which is perfectly fine.
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
random = SecureRandom.getInstance("SHA1PRNG");
keyGen.initialize(2048, random);
KeyPair pair = keyGen.generateKeyPair();
myPrivateKey = pair.getPrivate();
myPublicKey = pair.getPublic();
Signing and verifying are as follows:
//Singing with private key
Signature s = Signature.getInstance("SHA1withRSA");
s.initSign(javaPrivateKey);
//Verifying with public key
Signature s = Signature.getInstance("SHA1withRSA");
s.initVerify(javaPublicKey);
When I print myPrivateKey and myPublicKey, I see modulus(n) and public exponent(e) are the same for public and private key.
I have converted public and private keys to base64 and hex and I get the different values which is perfectly fine. However, I cannot sign the message with base64 or hex. I can sign it only with what I get from this:
myPrivateKey = pair.getPrivate();
I am aware of that verifying needs to be done with the public key which is visible to everyone. When the message is verified by the receiver, does the receiver use modulus and exponent only? What part of the public key needs to be shared by the sender? Modulus and exponent or Base64 or hex value of the key?
Yes, the receiver uses modulus and exponent only; there are no other components that are required mathematically speaking to verify a signature for RSA.
The mathematical operations are performed using large numbers (BigInteger values commonly when RSA is implemented in software). To perform any kind of calculation the implementation must regenerate these numbers. How these numbers are transmitted doesn't matter to the algorithm.
Commonly RSA public keys are encoded using something based on PKCS#1, which specifies the public key format using ASN.1 (which defines the structure) and BER/DER (which defines the encoding of that structure). Of course, different protocols may use different encodings of public keys. PGP for instance uses an entirely different "package format" to encode keys.
Java however returns a SubjectPublicKeyInfo structure which is defines in the X.509 (certificate and CRL) specifications; besides the modulus and exponent is also contains an algorithm identifier to show that it is an RSA public key. So this structure can also be used to distribute other kind of key values. It can be retrieved by calling getEncoded() on the RSAPublicKey instance - assuming that this instance is compatible with the Oracle provided one - they generally are. Android's implementations certainly should be compatible with this structure. Note that the SubjectPublicKeyInfo structure contains the PKCS#1 public key structure inside of it.
To reverse you need an KeyFactory.getInstance("RSA") and derive the key using X509EncodedKeySpec, initialized with the given byte array.
If you need textual strings instead of binary then you can convert the bytes returned by getEncoded() into base 64 and hexadecimals. Of course, in that case, you need to reverse the encoding (i.e. decode) the result before being able to decode the bytes themselves.
It is also possible to encode the modulus and public exponent yourself. You can retrieve them using RSAPublicKey.getModulus() and RSAPublicKey.getPublicExponent(). To reverse them back into an RSAPublicKey you can use KeyFactory.getInstance("RSA") and RSAPublicKeySpec. That way you can for instance just create a string "(<modulus>, <exp>)" and use that to distribute the key. Generally you would want to keep to predefined standards though.
Not covered in this answer is the fact that to verify with a public key you first need to establish trust in the public key. If you cannot trust the public key then you don't know who created the public key. In that case you can also not trust the result of your verification operation; the signature may have been created with a key pair of an adversary. Delving into Public Key Infrastructures (PKI / PKIX) is a bit too much for this answer though.
Likewise: SHA-1 is not considered secure anymore, especially for signature generation / verification. You would want to use at least SHA256withRSA or - slightly more advanced and somewhat more secure - an RSA scheme that uses PSS. 2048 bits is ever so slightly too small for comfort; using a 4096 bit key is advisable if your scheme allows it.

Create custom key for DES encryption and decryption - Android

I'm looking to encrypt a string using DES in one app and then decrypt it in another app. Currently I think its not working because the key to encrypt is generated randomly and so in the second app, the key generated when attempting to decrypt is different.
I need to be able to set my own key for when I am encrypting and then set the same key in the second app when decrypting but cannot find an explicit method on how to do so
Currently my key is being generated as follows:
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
How can I create a dummy key to use (e.g. 12345678)
Thanks
see this article, perhaps it can help you:
http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-with-des-using-pass-phrase/

how to encrypt and decrypt a message by using RSA with signature in android

no key distribution, public and private keys will be known by users (random key generator will not be used). I have to encrypt hashed message with private key in order to provide signature
message will only 10-20 characters, so system can be as simple as it is possible
For generating a digital signature, you don't need to encrypt the hash. Signing is a separate crypto primitive; the hash is not encrypted raw anyway, there's some padding. That said, the code is:
Signature Signer = Signature.getInstance("SHA1withRSA");
Signer.initSign(MyKey, new SecureRandom()); //Where do you get the key?
byte []Message = MyMessage(); //Initialize somehow
Signer.update(Message, 0, Message.length);
byte [] Signature = Sign.sign();
Okay, back up and tell us what you want. Are you trying to get privacy by protecting the contents of the message, or guarantee authenticity by showing that the message really came from the originator?
If you're looking for privacy, RSA isn't the way to go: use RSA to generate a private/public pair, and then use them to excahnge keys -- or exchange keys out of band. Use a streaming algorithm like AES to encrypt the message.
If you just want signature to show the message was originated by who you think it was, then have a look at the Wiki article on digital signature -- it's reasonably straightforward.

Categories

Resources