猿问

加密 Web 服务器的属性文件 (AES)

我目前正在开发一个从我的网络服务器请求特定属性的 Android 应用程序,如下所示:


<properties>

<property name="Approved-IP" value="SomeIPAddresses"/>

</properties>

该应用程序将站点保存为临时 XML 文件并尝试检查这些 IP。我想让服务器使用 AES 加密属性,如果应用程序没有设置加密密码,请使用默认密钥,如“test123”。


然后应用程序通过 EasyCrypt 库解密这些信息并使用它。


问题是我真的不知道如何在服务器端执行此操作,因此信息不会以纯文本形式传递。


萧十郎
浏览 202回答 1
1回答

侃侃尔雅

所以我为我的程序找到了一个解决方案(注意,这只是为了锻炼,所以我不会以任何方式称之为安全)我正在使用这种方法来加密我的 WebServer 上的字符串:private static byte[] encrypt(String plain, String key) throws Exception {&nbsp; &nbsp; byte[] clean = plain.getBytes();&nbsp; &nbsp; int ivSize = 16;&nbsp; &nbsp; byte[] iv = new byte[ivSize];&nbsp; &nbsp; SecureRandom random = new SecureRandom();&nbsp; &nbsp; random.nextBytes(iv);&nbsp; &nbsp; IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);&nbsp; &nbsp; MessageDigest digest = MessageDigest.getInstance("SHA-256");&nbsp; &nbsp; digest.update(key.getBytes("UTF-8"));&nbsp; &nbsp; byte[] keyBytes = new byte[16];&nbsp; &nbsp; System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);&nbsp; &nbsp; SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");&nbsp; &nbsp; Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");&nbsp; &nbsp; cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);&nbsp; &nbsp; byte[] encrypted = cipher.doFinal(clean);&nbsp; &nbsp; byte[] encryptedIVAndText = new byte[ivSize + encrypted.length];&nbsp; &nbsp; System.arraycopy(iv, 0, encryptedIVAndText, 0, ivSize);&nbsp; &nbsp; System.arraycopy(encrypted, 0, encryptedIVAndText, ivSize, encrypted.length);&nbsp; &nbsp; return encryptedIVAndText;}然后我用 Base64 编码生成的字符串Base64.getEncoder().encodeToString(encryptedString)并返回 Base64 字符串。我的应用程序使用 getDecoder 函数解码返回的字符串并使用此方法对其进行解密:public static String decrypt(byte[] encryptedIvTextBytes, String key) throws Exception {&nbsp; &nbsp; int ivSize = 16;&nbsp; &nbsp; int keySize = 16;&nbsp; &nbsp; byte[] iv = new byte[ivSize];&nbsp; &nbsp; System.arraycopy(encryptedIvTextBytes, 0, iv, 0, iv.length);&nbsp; &nbsp; IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);&nbsp; &nbsp; int encryptedSize = encryptedIvTextBytes.length - ivSize;&nbsp; &nbsp; byte[] encryptedBytes = new byte[encryptedSize];&nbsp; &nbsp; System.arraycopy(encryptedIvTextBytes, ivSize, encryptedBytes, 0, encryptedSize);&nbsp; &nbsp; byte[] keyBytes = new byte[keySize];&nbsp; &nbsp; MessageDigest md = MessageDigest.getInstance("SHA-256");&nbsp; &nbsp; md.update(key.getBytes());&nbsp; &nbsp; System.arraycopy(md.digest(), 0, keyBytes, 0, keyBytes.length);&nbsp; &nbsp; SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");&nbsp; &nbsp; Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");&nbsp; &nbsp; cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);&nbsp; &nbsp; byte[] decrypted = cipherDecrypt.doFinal(encryptedBytes);&nbsp; &nbsp; return new String(decrypted);}结果是正常的属性文件。
随时随地看视频慕课网APP

相关分类

Java
我要回答