Created
November 27, 2021 22:02
-
-
Save NaserKhoshfetrat/42a82a5d967604b65f95e3583c16acb4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mkyong.crypto.utils; | |
import javax.crypto.KeyGenerator; | |
import javax.crypto.SecretKey; | |
import javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.PBEKeySpec; | |
import javax.crypto.spec.SecretKeySpec; | |
import java.security.NoSuchAlgorithmException; | |
import java.security.SecureRandom; | |
import java.security.spec.InvalidKeySpecException; | |
import java.security.spec.KeySpec; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class CryptoUtils { | |
public static byte[] getRandomNonce(int numBytes) { | |
byte[] nonce = new byte[numBytes]; | |
new SecureRandom().nextBytes(nonce); | |
return nonce; | |
} | |
// AES secret key | |
public static SecretKey getAESKey(int keysize) throws NoSuchAlgorithmException { | |
KeyGenerator keyGen = KeyGenerator.getInstance("AES"); | |
keyGen.init(keysize, SecureRandom.getInstanceStrong()); | |
return keyGen.generateKey(); | |
} | |
// Password derived AES 256 bits secret key | |
public static SecretKey getAESKeyFromPassword(char[] password, byte[] salt) | |
throws NoSuchAlgorithmException, InvalidKeySpecException { | |
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); | |
// iterationCount = 65536 | |
// keyLength = 256 | |
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256); | |
SecretKey secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES"); | |
return secret; | |
} | |
// hex representation | |
public static String hex(byte[] bytes) { | |
StringBuilder result = new StringBuilder(); | |
for (byte b : bytes) { | |
result.append(String.format("%02x", b)); | |
} | |
return result.toString(); | |
} | |
// print hex with block size split | |
public static String hexWithBlockSize(byte[] bytes, int blockSize) { | |
String hex = hex(bytes); | |
// one hex = 2 chars | |
blockSize = blockSize * 2; | |
// better idea how to print this? | |
List<String> result = new ArrayList<>(); | |
int index = 0; | |
while (index < hex.length()) { | |
result.add(hex.substring(index, Math.min(index + blockSize, hex.length()))); | |
index += blockSize; | |
} | |
return result.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment