如何导出对称加密密钥? [英] How to export symmetric encryption key?
问题描述
我正在尝试在我的应用程序之间(通过intnets)实现 javax.crypto
加密.我遵循以下(可接受的答案): https://stackoverflow.com/问题/4319496/如何在Java中加密和解密数据.问题是据我了解,我需要在两个应用程序中使用相同的 SecretKeySpec键
为了加密/解密数据.我不知道如何导出它(作为字符串或其他任何东西),然后在两个应用程序中对其进行硬编码.
I'm trying to implement the javax.crypto
encryption between my apps (through intnets). I follow this (accepted answer): https://stackoverflow.com/questions/4319496/how-to-encrypt-and-decrypt-data-in-java .The problem is as I understood I need to have the same SecretKeySpec key
in both of my apps in order to encrypt/decrypt the data. I have no idea how to export it (as a String or anything) and then hardcode it in both of my apps.
推荐答案
您可以使用 getEncoded()
方法导出 SecretKey
.这将返回一个字节数组,您可以将其编码为字符串,例如使用base 64编码.可以从此编码字节数组重新创建 SecretKeySpec
对象.
You can export a SecretKey
using the getEncoded()
method. This returns a byte array, which you could encode to a string, for example using base 64 encoding. The SecretKeySpec
object can be recreated from this encoded byte array.
只是给您一个更好的主意,未经测试:
Just to give you a better idea, not tested:
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");
这篇关于如何导出对称加密密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!