我正在尝试javax.crypto
通过intnet在我的应用程序之间实现加密。我按照这个(接受的答案):https://stackoverflow.com/questions/4319496/how-to-encrypt-and-decrypt-data-in-java。问题是,我明白我需要有相同的SecretKeySpec key
两个我的应用程序以加密/解密数据。我不知道如何导出它(作为字符串或其他任何东西),然后在两个应用程序中对其进行硬编码。
您可以SecretKey
使用getEncoded()
方法导出一个。这将返回一个字节数组,您可以将其编码为字符串,例如使用base 64编码。所述SecretKeySpec
对象可以从该编码的字节数组被重新创建。
只是为了给您一个更好的主意,未经测试:
import org.apache.commons.codec.binary.Base64;
// "AES" is the key generation algorith, you might want to use a different one.
KeyGenerator kg = KeyGenerator.getInstance("AES");
// 256-bit key, you may want more or fewer bits.
kg.init(256);
SecretKey key = kg.generateKey();
byte[] keyBytes = key.getEncoded();
// Encode to a String, e.g. base 64 encoded
String encodedKey = new String(Base64.encodeBase64(keyBytes), "UTF-8");
// Base 64 decode
byte[] keyBytes = Base64.decodeBase64(encodedKey.getBytes("UTF-8"));
// Need to put the same key generation algorithm in here:
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句