[英]How to export symmetric encryption key?
我正在嘗試在我的應用之間(通過intnets)實現javax.crypto
加密。 我遵循這個(公認的答案): https : //stackoverflow.com/questions/4319496/how-to-en-encrypt-and-decrypt-data-in-java 。問題是據我了解,我需要具有相同的SecretKeySpec key
在我的兩個應用中都是為了加密/解密數據。 我不知道如何導出它(作為字符串或任何東西),然后在兩個應用程序中對其進行硬編碼。
您可以使用getEncoded()
方法導出SecretKey
。 這將返回一個字節數組,您可以將其編碼為字符串,例如使用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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.