Is it possible to create a PrivateKey from an encoded byte array alone, without knowing the algorithm in advance?
So in a way it's a twist on that question, that's not adressed in the answers.
Say I have a pair of keys generated this way:
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); // Could be "EC" instead of "RSA"
String privateKeyB64 = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
writePrivateKeyToSafeLocation(privateKeyB64);
To obtain a PrivateKey from the base64-encoded bytes, I can do this, but I have to know the algorithm family in advance:
String privateKeyB64 = readPrivateKeyFromSafeLocation();
EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyB64));
byte[] encodedKeyBytes = encodedKeySpec.getEncoded();
String algorithmFamily = "RSA"; // Can this be deduced from encodedKeyBytes?
PrivateKey key = KeyFactory.getInstance(algorithmFamily).generatePrivate(encodedKeySpec);
Unfortunately encodedKeySpec.getAlgorithm() returns null.
I'm pretty sure the algorithm ID is actually specified within those bytes in PKCS#8 format, but I'm not sure how to read the ASN.1 encoding.
Can I "sniff" the algorithm ID in a reliable way from those bytes?
It's OK to only support RSA and EC (algorithms supported by the JRE, without additional providers).
To get an idea of what I'm after, here is an attempt that seems to work empirically:
private static final byte[] EC_ASN1_ID = {42, -122, 72, -50, 61, 2, 1};
private static final byte[] RSA_ASN1_ID = {42, -122, 72, -122, -9, 13, 1, 1, 1};
private static final int EC_ID_OFFSET = 9;
private static final int RSA_ID_OFFSET = 11;
private static String sniffAlgorithmFamily(byte[] keyBytes) {
if (Arrays.equals(Arrays.copyOfRange(keyBytes, EC_ID_OFFSET, EC_ID_OFFSET + EC_ASN1_ID.length), EC_ASN1_ID)) {
return "EC";
}
if (Arrays.equals(Arrays.copyOfRange(keyBytes, RSA_ID_OFFSET, RSA_ID_OFFSET + RSA_ASN1_ID.length), RSA_ASN1_ID)) {
return "RSA";
}
throw new RuntimeException("Illegal key, this thingy requires either RSA or EC private key");
}
But I have no idea if that is safe to use. Maybe the IDs are not always at those offsets. Maybe they can be encoded in some other ways...
As suggested by James in comments, trying every supported algorithm would work, in a much safer way.
It's possible to dynamically obtain the list of such algorithms:
Set<String> supportedKeyPairAlgorithms() {
Set<String> algos = new HashSet<>();
for (Provider provider : Security.getProviders()) {
for (Provider.Service service : provider.getServices()) {
if ("KeyPairGenerator".equals(service.getType())) {
algos.add(service.getAlgorithm());
}
}
}
return algos;
}
And with that, just try them all to generate the KeyPair:
PrivateKey generatePrivateKey(String b64) {
byte[] bytes = Base64.getDecoder().decode(b64);
for (String algorithm : supportedKeyPairAlgorithms()) {
try {
LOGGER.debug("Attempting to decode key as " + algorithm);
return KeyFactory.getInstance(algorithm).generatePrivate(new PKCS8EncodedKeySpec(bytes));
} catch (NoSuchAlgorithmException e) {
LOGGER.warn("Standard algorithm " + algorithm + " not known by this Java runtime from outer space", e);
} catch (InvalidKeySpecException e) {
LOGGER.debug("So that key is not " + algorithm + ", nevermind", e);
}
}
throw new RuntimeException("No standard KeyFactory algorithm could decode your key");
}
Related
I have the following code on Java that decrypts AES encryption and I need to do the same on Node.js
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String decrypt(String strToDecrypt, String secret)
{
try
{
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e)
{
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
I have tried using Crypt under the following code, but it doesn't give me the same results
var aesDecrypt = (text, password, bit) => {
var decipher = crypto.createDecipheriv('aes-' + bit + '-ecb', password, Buffer.alloc(0));
decipher.setAutoPadding(false);
return Buffer.concat([
decipher.update(text, 'base64'),
decipher.final()
]).toString();
};
How could I mimick that Java code from above into Node.js?
As James says, the Java code is hashing (and truncating) the password to form the key. Also it does use standard padding. The following works for ASCII data:
const crypto = require ('crypto');
const mydecrypt = (pw,ctx) => {
var h = crypto.createHash('sha1'); h.update(pw,'utf8'); var k = h.digest().slice(0,16);
var d = crypto.createDecipheriv('aes-128-ecb', k, Buffer.alloc(0));
return Buffer.concat([d.update(ctx,'base64'), d.final()]) .toString();
}
console.log(mydecrypt('password','ks7qtmk7kt5riV/Qyy3glQ=='));
->
testdata
It may not work for non-ASCII data. Java new String(byte[]) uses a JVM-dependent encoding which may be UTF8 or may be something different depending on your platform, build, and environment, none of which you described. OTOH nodejs Buffer.toString() always uses UTF8. You may need to change it to toString(somethingelse) to match the Java.
If this 'password' is truly a password, i.e. chosen or even remembered by one or more human(s), using a simple hash of it is very weak and will probably be broken if used for anything not utterly trivial; you should use a Password-Based Key Derivation Function designed for the purpose by someone competent, like older (PKCS5) PBKDF2 or newer bcrypt, scrypt, or argon2. However, that's not a programming question and is offtopic here; it has been discussed many times and at length on https://crypto.stackexchange.com and https://security.stackexchange.com .
The C# is on the client end while Java code is used in a service. Windows phone encrypts the data while Java decrypts the data using the same symmetric key.
Below is my C# method for encryption
public static string EncryptAesTest(string data, string password)
{
SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
CryptographicKey AES;
HashAlgorithmProvider HAP = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512);
Windows.Security.Cryptography.Core.CryptographicHash Hash_AES = HAP.CreateHash();
string encrypted;
try
{
byte[] hash = new byte[16];
Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Convert.FromBase64String(password)));
byte[] temp;
CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(data));
encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));
return encrypted;
}
catch
{
return "encryption error";
}
}
Below is my Java class for decryption
private SecretKeySpec secretKey;
public void setKey() {
skey = "mykey";
MessageDigest sha = null;
try {
key = skey.getBytes("UTF-8");
logger.debug("Key length ====> " + key.length);
sha = MessageDigest.getInstance("SHA-512");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public String decrypt(String strToDecrypt) {
Cipher cipher = null;
try {
cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, this.secretKey);
setDecryptedString(new String(cipher.doFinal(Base64
.decodeBase64(strToDecrypt))));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
The key generation is not complete. For some reason, your C# code uses sets the last byte of the key to the same value as the first byte with the following code:
Array.Copy(temp, 0, hash, 0, 16);
Array.Copy(temp, 0, hash, 15, 16);
(To my understanding, this could should throw some exception, because you can't copy 16 bytes into the 16 byte array hash if you begin at index 15.)
You could do the same (bad) thing in Java
public void setKey() {
skey = "mykey";
MessageDigest sha = null;
try {
key = skey.getBytes("UTF-8");
logger.debug("Key length ====> " + key.length);
sha = MessageDigest.getInstance("SHA-512");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
key[15] = key[0]; // added
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Things to consider:
ECB mode does not provide semantic security and it should never be used. Use at the very least CBC mode with a random IV for each encryption under the same key.
Passwords should be hashed multiple times. A single hash makes it easy for an attacker to brute-force the password, because this is operation is fast. You should use Password-based Encryption with a strong key derivation function like PBKDF2 (more than 100,000 iterations), scrypt or bcrypt. Don't forget to use a random salt.
Authenticate your ciphertexts. You would want to detect (malicious) manipulations of your ciphertexts in transit. This can be done either with an authenticated mode like GCM or EAX, or with an encrypt-then-MAC scheme by running a MAC algorithm over your ciphertexts. A strong MAC is HMAC-SHA256.
Blowfish is capable of strong encryption and can use key sizes up to 56 bytes (a 448 bit key).
The key must be a multiple of 8 bytes (up to a maximum of 56).
I want to write example will automatically pad and unpad the key to size. Because Blowfish creates blocks of 8 byte encrypted output, the output is also padded and unpadded to multiples of 8 bytes.
actually want to write java code to simulate-
http://webnet77.com/cgi-bin/helpers/blowfish.pl
I am using info for tool-
ALGORITM = "Blowfish";
HEX KEY = "92514c2df6e22f079acabedce08f8ac3";
PLAIN_TEXT = "sangasong#song.com"
Tool returns-
CD3A08381467823D4013960E75E465F0B00C5E3BAEFBECBB
Please suggest.
Tried the java code:
public class TestBlowfish
{
final String KEY = "92514c2df6e22f079acabedce08f8ac3";
final String PLAIN_TEXT = "sangasong#song.com";
byte[] keyBytes = DatatypeConverter.parseHexBinary(KEY);
}
public static void main(String[] args) throws Exception
{
try
{
byte[] encrypted = encrypt(keyBytes, PLAIN_TEXT);
System.out.println( "Encrypted hex: " + Hex.encodeHexString(encrypted));
}catch (GeneralSecurityException e)
{
e.printStackTrace();
}
}
private static byte[] encrypt(byte[] key, String plainText) throws GeneralSecurityException
{
SecretKey secret_key = new SecretKeySpec(key, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, secret_key);
return cipher.doFinal(plainText.getBytes());
}
Result -
Encrypted hex: 525bd4bd786a545fe7786b0076b3bbc2127425f0ea58c29d
So the script uses an incorrect version of PKCS#7 padding that does not pad when the size of the input is already dividable by the block size - both for the key and the plaintext. Furthermore it uses ECB mode encryption. Neither of which should be used in real life scenarios.
The following code requires the Bouncy Castle provider to be added to the JCE (Service.addProvider(new BouncyCastleProvider())) and that the Hex class of Bouncy Castle libraries is in the class path.
Warning: only tested with limited input, does not cut the key size if the size of the key is larger than the maximum.
WARNING: THE FOLLOWING CODE IS NOT CRYPTOGRAPHICALLY SOUND
import org.bouncycastle.util.encoders.Hex;
public class BadBlowfish {
private static SecretKey createKey(String theKey) {
final byte[] keyData = theKey.getBytes(StandardCharsets.US_ASCII);
final byte[] paddedKeyData = halfPadPKCS7(keyData, 8);
SecretKey secret = new SecretKeySpec(paddedKeyData, "Blowfish");
return secret;
}
private static byte[] halfUnpadPKCS7(final byte[] paddedPlaintext, int blocksize) {
int b = paddedPlaintext[paddedPlaintext.length - 1] & 0xFF;
if (b > 0x07) {
return paddedPlaintext.clone();
}
return Arrays.copyOf(paddedPlaintext, paddedPlaintext.length - b);
}
private static byte[] halfPadPKCS7(final byte[] plaintext, int blocksize) {
if (plaintext.length % blocksize == 0) {
return plaintext.clone();
}
int newLength = (plaintext.length / blocksize + 1) * blocksize;
int paddingLength = newLength - plaintext.length;
final byte[] paddedPlaintext = Arrays.copyOf(plaintext, newLength);
for (int offset = plaintext.length; offset < newLength; offset++) {
paddedPlaintext[offset] = (byte) paddingLength;
}
return paddedPlaintext;
}
public static void main(String[] args) throws Exception {
Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
SecretKey key = createKey("123456781234567");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plaintextData = cipher.doFinal(Hex.decode("085585C60B3D23257763E6D8BB0A0891"));
byte[] unpaddedPlaintextData = halfUnpadPKCS7(plaintextData, cipher.getBlockSize());
String plaintextHex = Hex.toHexString(unpaddedPlaintextData);
System.out.println(plaintextHex);
String plaintext = new String(unpaddedPlaintextData, StandardCharsets.UTF_8);
System.out.println(plaintext);
}
}
I am not sure about the relevance of this question: IMHO there is no point of getting the same output as this script: you have no guaranty about how secure/efficient it is...
What raises my eyebrow is the part about the padding: there are several solution to pad a block, some of then are simple but very unsecured, and maybe this script is using one of these "bad" solution.
Did you check that your program is able to retrieve the correct plain text ? (you will need to code the matching decrypt function).
If so, it means that it works correctly and it can be used for whatever your original purpose was, regardless what the ouput of this script is...
I am asked to verify if the encryption is working ok. I am given input hex text of 238 bytes. Asked to use DESede/CBC/NoPadding algorithm. I am also given encrypted value. Of course, I am given key also ( Given two bytes. Added third byte as copy of first byte to make it three bytes)
(238 bytes+ 2 bytes padding)
Problem is: Encrypted value from my code does not match completely with the given encrypted value ( only First 56 bytes are matching).
What I did is: Decrypted the given encrypted value and encrypted value produced from my code. Both of these decrypted values are matching with the given input.
That means, I have two encrypted values for which the decrypted value is the same.
Using InitialVector of Zeros.(8 zero bytes).
Can somebody throw some light? I am sure I am missing something. Thanks for any help.
Using javax.crypto.Cipher.getInstance for getting Cipher instance. Using SecretKeyFactory and DESedeKeySpec classes to generate key
Edited:
public String encrypt(byte[] sourceDataInBytes, String keyInHex, String cryptoMode, String cryptoPadding)
{
Cipher des3cipher = null;
IvParameterSpec ivParamSpec = null;
String transformation = "DESede"+"/"+ cryptoMode+"/"+cryptoPadding;
byte[] encryptedDataInBytes = null;
try{
des3cipher = Cipher.getInstance(transformation);
Key key = generate3DESKey(keyInHex);
if(cryptoMode.equalsIgnoreCase("CBC"))
{
ivParamSpec = new IvParameterSpec(INITIAL_VECTOR_SALT);
des3cipher.init(CYPHER_ENCRYPT_MODE, key, (AlgorithmParameterSpec)ivParamSpec );
}else{
des3cipher.init(CYPHER_ENCRYPT_MODE, key);
}
if(cryptoPadding.equals("NoPadding")){'
sourceDataInBytes = addPadding(sourceDataInBytes, 8);
}
encryptedDataInBytes = des3cipher.doFinal(sourceDataInBytes);
}catch(Exception e){
e.printStackTrace();
}
return encryptedDataInBytes ;
}
public Key generate3DESKey(String srcInHex)
{
Key key = null;
if(src != null)
{
byte[] bk = null;
try{
bk = hexStringToByte(src + src.length==32 ? src.substring(0,16) : ""));
DESedeKeySpec des3KeySpec = new DESedeKeySpec(bk);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
key = keyFactory.generateSecret(des3KeySpec);
}catch(Exception e){
e,printStyackTrace();
}
}
return key;
}
I've been using the Java security api and was following the tutorial on how to generate digital signatures: http://docs.oracle.com/javase/tutorial/security/apisign/gensig.html
The problem is when I run the code, the output signature is always different even when the private key and data which is to be signed stays constant. I have provided the code below which I used to run. "priv" is a file which holds the private key and is used to sign the data: "hello".
Basically the two outputs show the same data: "hello" signed with the same key but it gives a different output. I was expecting the same output to be given. Also when I run the program again, the signed data is different again from the initial run. Any help would be much appreciated. Thanks in advance
public static void main(String[] args) {
try {
FileInputStream privfis;
privfis = new FileInputStream("priv");
byte[] encKey = new byte[privfis.available()];
// obtain the encoded key in the file
privfis.read(encKey);
privfis.close();
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec( encKey);
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
PrivateKey priv = keyFactory.generatePrivate(privKeySpec);
Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");
dsa.initSign(priv);
String message = "hello";
System.out.println(getHexString(message.getBytes()));
dsa.update(message.getBytes());
byte[] realSig = dsa.sign();
System.out.println(getHexString(realSig));
dsa.update(message.getBytes());
System.out.println(getHexString(message.getBytes()));
byte[] realSig2 = dsa.sign();
System.out.println(getHexString(realSig2));
} catch (Exception e) {
System.err.println("Caught exception " + e.toString());
e.printStackTrace();
}
}
private static String getHexString(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
}