如何将PBKDF2生成的密码字节数组转换为字符串?
The core problem here is that the byte array returned by your getEncryptedPassword method is raw binary data—it’s not designed to be directly decoded into a human-readable string using standard character encodings like UTF-8 or ISO-8859-1. When you call new String(byteArray), Java tries to interpret those binary bytes as characters in your system’s default charset, which will almost always produce garbled text (like ��%x�F�) because most binary values don’t map to valid characters.
To properly convert the PBKDF2 output to a string, you need to encode the binary data into a printable text format. The two most common and reliable options are Base64 encoding or hexadecimal (hex) encoding.
Option 1: Base64 Encoding (Compact & Efficient)
Base64 converts binary data into a set of 64 ASCII characters, making it ideal for storage or transmission. Java 8+ includes a built-in Base64 class for this:
import java.util.Base64; // Convert PBKDF2 byte array to Base64 string String encryptedPassword = Base64.getEncoder().encodeToString( getEncryptedPassword(p, s, iterations, derivedKeyLength) ); System.out.println(encryptedPassword); // If you need to convert the string back to a byte array later (e.g., for verification) byte[] decodedBytes = Base64.getDecoder().decode(encryptedPassword);
Option 2: Hexadecimal Encoding (Human-Readable, Longer)
Hex encoding converts each byte into two hexadecimal characters (0-9, A-F). It’s less compact than Base64 but easier to read manually. You can implement a simple helper method for this:
// Convert byte array to hex string public static String bytesToHex(byte[] bytes) { StringBuilder hexBuilder = new StringBuilder(); for (byte b : bytes) { // %02x ensures each byte is represented as two characters (padding with 0 if needed) hexBuilder.append(String.format("%02x", b)); } return hexBuilder.toString(); } // Usage String encryptedPasswordHex = bytesToHex( getEncryptedPassword(p, s, iterations, derivedKeyLength) ); System.out.println(encryptedPasswordHex); // To convert the hex string back to a byte array (for verification) public static byte[] hexToBytes(String hexString) { int byteCount = hexString.length() / 2; byte[] bytes = new byte[byteCount]; for (int i = 0; i < byteCount; i++) { int index = i * 2; // Parse two hex characters into a single byte int value = Integer.parseInt(hexString.substring(index, index + 2), 16); bytes[i] = (byte) value; } return bytes; }
Key Takeaway
Never convert raw cryptographic byte arrays to strings using new String(byteArray)—this will corrupt your data. Always use a standard encoding like Base64 or hex to preserve the full binary information in a printable format.
内容的提问来源于stack exchange,提问作者user5182503

