在安全软件设计中,避免以明文形式存储密码。相反,应采用哈希和加密技术来保护敏感信息。
将凭证从字符串迁移到字符数组。字符串是不可变的,使得数据在清理之前容易暴露。另一方面,字符数组可以立即清理。
加密凭证,同时保留原始哈希以确保安全。仅在身份验证过程中解密凭据。建议避免对凭据进行硬编码,而是安全地存储它们,例如存储在加密的配置文件中。
实施 TLS 或 SSL 来加密数据客户端和服务器之间的传输。这可以保护凭证免遭窃听。
应用混淆技术以防止恶意方访问安全措施,即使在反编译的情况下也是如此。混淆使攻击者更难发现漏洞。
以下代码片段说明了加密和解密凭据:
import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; public class SecureCredentials { private static final char[] PASSWORD = "YourEncryptionKey".toCharArray(); private static final byte[] SALT = { (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12 }; public static void encrypt(char[] property) throws Exception { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20)); // Encrypt and save to temporary storage String encrypted = Base64.encodeBytes(pbeCipher.doFinal(property)); // Cleanup data sources for (int i = 0; i < property.length; i++) { property[i] = 0; } property = null; System.gc(); // Return encryption result return encrypted; } public static String decrypt(String property) throws Exception { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20)); return new String(pbeCipher.doFinal(Base64.decode(property))); } // Usage example public static void main(String[] args) { try { char[] password = "MySecurePassword".toCharArray(); String encryptedPassword = encrypt(password); String decryptedPassword = decrypt(encryptedPassword); System.out.println("Original Password: " + String.valueOf(password)); System.out.println("Encrypted Password: " + encryptedPassword); System.out.println("Decrypted Password: " + decryptedPassword); } catch (Exception e) { e.printStackTrace(); } } }
以上是如何在软件中安全存储用户凭证?的详细内容。更多信息请关注PHP中文网其他相关文章!