HmacSHA256 Encoding in java - java

I just want to encode a given string to HmacSHA256 according to a private key in java.anyone can provide a simple program....?

SecureRandom sr = new SecureRandom();
byte[] keyBytes = new byte[20];
sr.nextBytes(keyBytes);
SecretKey key = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac m = Mac.getInstance("HmacSHA1");
m.init(key);
m.update(inputData);
byte[] mac = m.doFinal();
Copied from 'http://oreilly.com/catalog/javacrypt/chapter/ch06.html', you'll find all other cryptographic information there.

Related

How to perform Base64 on top of HASH in Java

I have the following example in Javascript, I can't seem to find the equivalent in Java for it
var rapyd_signature = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA256(data, key));
rapyd_signature = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(rapyd_signature));
What I have (which does not give the same result)
Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
hmacSHA256.init(secretKeySpec);
byte[] tobeEncoded = data.getBytes(StandardCharsets.UTF_8);
String rapyd_signature = Base64.getEncoder().encodeToString(tobeEncoded);
You initialized hmacSHA256 … and then you didn’t do anything with it.
You need to actually hash the data, by calling hmacSHA256.doFinal:
Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
hmacSHA256.init(secretKeySpec);
byte[] tobeEncoded = data.getBytes(StandardCharsets.UTF_8);
toBeEncoded = hmacSHA256.doFinal(toBeEncoded);
String rapyd_signature = Base64.getEncoder().encodeToString(tobeEncoded);

How to use passphrase for RSAPrivateKey in JAVA?

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

BadPaddingException using SecretKey generated by DiffieHellman

I have seen a lot of questions/answers but no one works for me. The problem is that, when I want to decrypt a text, I go throw BadPaddingException and doesn't know why.
Here is my code to encrypt text:
KeyAgreement keyAgreement = this.getSecretKeyAgreement(publicOtherUserKey, privateOwnKey);
SecretKey secretKey = new SecretKeySpec(keyAgreement.generateSecret(), "AES");
Cipher aesCipher = null;
aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] byteDataToEncrypt = text.getBytes();
byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
byte[] encodedBytes = Base64.encodeBase64(byteCipherText);
textEncrypted = new String(encodedBytes);
Where "publicOtherUserKey" and "privateOwnKey" where generated using Diffie-Hellman Protocol.
Here is the code that decrypt the text, that goes throw BadPaddingException
KeyAgreement keyAgreement = this.getSecretKeyAgreement(publicOtherUserKey, privateOwnKey);
byte[] encodedBytes = text.getBytes();
SecretKey secretKey = new SecretKeySpec(keyAgreement.generateSecret(), "AES");
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
Cipher decrypt = Cipher.getInstance("AES");
decrypt.init(Cipher.DECRYPT_MODE, secretKey);
textDecrypted = new String(decrypt.doFinal(decodedBytes));
Where "publicOtherUserKey" and "privateOwnKey" where generated using Diffie-Hellman Protocol, and "text" is the encrypted text.
Can you help me?
EDIT
It's important to mention that all the keys and texts are encoded in Base64
EDIT 2
Code for Start key exchange with Diffie-Hellman
int bitLength = 256; // 256 bits
SecureRandom rnd = new SecureRandom();
BigInteger p = BigInteger.probablePrime(bitLength, rnd);
BigInteger g = BigInteger.probablePrime(bitLength, rnd);
DHParameterSpec dhParams = new DHParameterSpec(p, g);
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH", "BC");
keyGen.initialize(dhParams, new SecureRandom());
KeyAgreement aKeyAgree = KeyAgreement.getInstance("DH", "BC");
KeyPair aPair = keyGen.generateKeyPair();
aKeyAgree.init(aPair.getPrivate());
byte[] aPairPrivateKey = aPair.getPrivate().getEncoded();
byte[] encodedBytesPrivateKey = Base64.encodeBase64(aPairPrivateKey);
String privateKey = new String(encodedBytesPrivateKey);
byte[] aPairPublicKey = aPair.getPublic().getEncoded();
byte[] encodedBytesPublicKey = Base64.encodeBase64(aPairPublicKey);
String publicKey = new String(encodedBytesPublicKey);
Where "publicKey" and "privateKey" are the keys to later generate the secret key. "publicKey" is the Key sended to the other user. "p" and "g" are the numbers to generate the Key too.
The code for complete the exchange:
DHParameterSpec dhParams = new DHParameterSpec(p, g);
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH", "BC");
keyGen.initialize(dhParams, new SecureRandom());
KeyAgreement bKeyAgree = KeyAgreement.getInstance("DH", "BC");
KeyPair bPair = keyGen.generateKeyPair();
bKeyAgree.init(bPair.getPrivate());
byte[] userPublicBytesBase64 = base64EncodedPublicKey.getBytes();
byte[] userPublicKey = Base64.decodeBase64(userPublicBytesBase64);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(userPublicKey);
KeyFactory keyFactory = KeyFactory.getInstance("DH");
PublicKey aPublicKey = keyFactory.generatePublic(keySpec);
bKeyAgree.doPhase(aPublicKey, true);
final byte[] bPairPrivateKey = bPair.getPrivate().getEncoded();
byte[] encodedBytesPrivateKey = Base64.encodeBase64(bPairPrivateKey);
String privateKey = new String(encodedBytesPrivateKey);
final byte[] bPairPublicKey = bPair.getPublic().getEncoded();
byte[] encodedBytesPublicKey = Base64.encodeBase64(bPairPublicKey);
String publicKey = new String(encodedBytesPublicKey);
"base64EncodedPublicKey" is the Key generated in the first block of Code ("publicKey"), and "p" and "g" are too the primes generated in the first block of Code.

Inconsistencies in encryption between Java and Node

I'm trying to replicate a Java-based encryption scheme in Node.js but unfortunately I'm getting inconsistent results.
Here's the Java method:
private Transfer encrypt(byte[] salt, String ticketNumber, String data) throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(ticketNumber.toCharArray(), salt, 1000, 128);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
String encoded = java.util.Base64.getEncoder().encodeToString(secret.getEncoded());
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv ={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
IvParameterSpec ips = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, secret, ips);
AlgorithmParameters params = cipher.getParameters();
Transfer myRetVal = new Transfer();
byte[] ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
//Set some decrypt information
myRetVal.setIv(Base64.encodeBase64String(ivBytes));
//Set the attendee data
myRetVal.setData(Base64.encodeBase64String(cipher.doFinal(data.getBytes())));
//Set the hashed Ticket number
myRetVal.setTicketNumberHashed(Base64.encodeBase64String(getHash(hashIterations, ticketNumber, salt)));
return myRetVal;
}
And my Node version:
exports.getEncryptedString = function(salt, password, data) {
var iv = new Buffer('0000000000000000');
var key = crypto.pbkdf2Sync(password, salt, 1000, 16, 'sha1');
var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
return cipher.update(data, 'utf8', 'base64') + cipher.final('base64');
};
When I pass both functions the string "SomeJSON" and the same key I get different encrypted results.
From Java: ENnQzWowzrl7LQchRmL7sA==
From Node: TGreJNmQH92gHb1bSy4xAA==
I can't figure out what is different in my Node implementation.
new Buffer('0000000000000000') uses utf8 encoding by default, but "0" in UTF-8 is the byte 0x30 whereas in Java you're using 0x00 bytes for the IV. What you want is either
var iv = new Buffer('00000000000000000000000000000000', 'hex');
or
var iv = new Buffer(16);
iv.fill(0);
After you've done your tests, you should change the procedure to generate a new IV for every encryption. The IV doesn't have to be secret, so you can simply prepend it to the ciphertext. When you want to decrypt it later, you can slice the IV off (16 bytes for AES) and use it during decryption.

256bit AES/CBC/PKCS5Padding with Bouncy Castle

I am having trouble mapping the following JDK JCE encryption code to Bouncy Castles Light-weight API:
public String dec(String password, String salt, String encString) throws Throwable {
// AES algorithm with CBC cipher and PKCS5 padding
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
// Construct AES key from salt and 50 iterations
PBEKeySpec pbeEKeySpec = new PBEKeySpec(password.toCharArray(), toByte(salt), 50, 256);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
SecretKeySpec secretKey = new SecretKeySpec(keyFactory.generateSecret(pbeEKeySpec).getEncoded(), "AES");
// IV seed for first block taken from first 32 bytes
byte[] ivData = toByte(encString.substring(0, 32));
// AES encrypted data
byte[] encData = toByte(encString.substring(32));
cipher.init( Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec( ivData ) );
return new String( cipher.doFinal( encData ) );
}
The above works great, but is not very portable due to Oracle's restriction on encryption strengths. I've made several attempts at porting to Bouncy Castles Light-weight API but without success.
public String decrypt1(String password, String salt, String encString) throws Exception {
byte[] ivData = toByte(encString.substring(0, 32));
byte[] encData = toByte(encString.substring(32));
PKCS12ParametersGenerator gen = new PKCS12ParametersGenerator(new SHA256Digest());
gen.init(password.getBytes(), toByte(salt), 50);
CBCBlockCipher cbcBlockcipher = new CBCBlockCipher(new RijndaelEngine(256));
CipherParameters params = gen.generateDerivedParameters(256, 256);
cbcBlockcipher.init(false, params);
PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(cbcBlockcipher, new PKCS7Padding());
byte[] plainTemp = new byte[aesCipher.getOutputSize(encData.length)];
int offset = aesCipher.processBytes(encData, 0, encData.length, plainTemp, 0);
int last = aesCipher.doFinal(plainTemp, offset);
byte[] plain = new byte[offset + last];
System.arraycopy(plainTemp, 0, plain, 0, plain.length);
return new String(plain);
}
The above attempt results in a org.bouncycastle.crypto.DataLengthException: last block incomplete in decryption.
I have searched for examples online, but there isn't many examples of providing your own IV data for 256bit AES with CBC using PKCS5/PKCS7 as padding.
NB: The toByte function converts a String into a byte array using base64 or similar.
This should work for you:
public String dec(String password, String salt, String encString)
throws Exception {
byte[] ivData = toByte(encString.substring(0, 32));
byte[] encData = toByte(encString.substring(32));
// get raw key from password and salt
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(),
toByte(salt), 50, 256);
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
SecretKeySpec secretKey = new SecretKeySpec(keyFactory.generateSecret(
pbeKeySpec).getEncoded(), "AES");
byte[] key = secretKey.getEncoded();
// setup cipher parameters with key and IV
KeyParameter keyParam = new KeyParameter(key);
CipherParameters params = new ParametersWithIV(keyParam, ivData);
// setup AES cipher in CBC mode with PKCS7 padding
BlockCipherPadding padding = new PKCS7Padding();
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
new CBCBlockCipher(new AESEngine()), padding);
cipher.reset();
cipher.init(false, params);
// create a temporary buffer to decode into (it'll include padding)
byte[] buf = new byte[cipher.getOutputSize(encData.length)];
int len = cipher.processBytes(encData, 0, encData.length, buf, 0);
len += cipher.doFinal(buf, len);
// remove padding
byte[] out = new byte[len];
System.arraycopy(buf, 0, out, 0, len);
// return string representation of decoded bytes
return new String(out, "UTF-8");
}
I assume that you're actually doing hex encoding for toByte() since your code uses 32 characters for the IV (which provides the necessary 16 bytes). While I don't have the code you used to do the encryption, I did verify that this code will give the same decrypted output as your code.

Categories

Resources