Answers:
您可以将转换SecretKey
为字节数组(byte[]
),然后Base64将其编码为String
。要转换回a SecretKey
,Base64 会对String进行解码,然后在a中使用它SecretKeySpec
来重建您的原始字符串SecretKey
。
字符串的SecretKey:
// create new key
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
// get base64 encoded version of the key
String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());
字符串到SecretKey:
// decode the base64 encoded string
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
注意I:您可以跳过Base64编码/解码部分,而只将其存储byte[]
在SQLite中。也就是说,执行Base64编码/解码并不是一项昂贵的操作,并且您可以将字符串存储在几乎任何数据库中而不会出现问题。
注意II:较早的Java版本在java.lang
或java.util
软件包之一中不包括Base64 。但是,可以使用Apache Commons Codec,Bouncy Castle或Guava中的编解码器。
字符串的SecretKey:
// CREATE NEW KEY
// GET ENCODED VERSION OF KEY (THIS CAN BE STORED IN A DB)
SecretKey secretKey;
String stringKey;
try {secretKey = KeyGenerator.getInstance("AES").generateKey();}
catch (NoSuchAlgorithmException e) {/* LOG YOUR EXCEPTION */}
if (secretKey != null) {stringKey = Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT)}
字符串到SecretKey:
// DECODE YOUR BASE64 STRING
// REBUILD KEY USING SecretKeySpec
byte[] encodedKey = Base64.decode(stringKey, Base64.DEFAULT);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
为了显示创建快速失败的某些功能的乐趣,我编写了以下3个功能。
一个创建一个AES密钥,一个对其进行编码,然后一个对其进行解码。这三种方法可以与Java 8一起使用(不依赖内部类或外部依赖):
public static SecretKey generateAESKey(int keysize)
throws InvalidParameterException {
try {
if (Cipher.getMaxAllowedKeyLength("AES") < keysize) {
// this may be an issue if unlimited crypto is not installed
throw new InvalidParameterException("Key size of " + keysize
+ " not supported in this runtime");
}
final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(keysize);
return keyGen.generateKey();
} catch (final NoSuchAlgorithmException e) {
// AES functionality is a requirement for any Java SE runtime
throw new IllegalStateException(
"AES should always be present in a Java SE runtime", e);
}
}
public static SecretKey decodeBase64ToAESKey(final String encodedKey)
throws IllegalArgumentException {
try {
// throws IllegalArgumentException - if src is not in valid Base64
// scheme
final byte[] keyData = Base64.getDecoder().decode(encodedKey);
final int keysize = keyData.length * Byte.SIZE;
// this should be checked by a SecretKeyFactory, but that doesn't exist for AES
switch (keysize) {
case 128:
case 192:
case 256:
break;
default:
throw new IllegalArgumentException("Invalid key size for AES: " + keysize);
}
if (Cipher.getMaxAllowedKeyLength("AES") < keysize) {
// this may be an issue if unlimited crypto is not installed
throw new IllegalArgumentException("Key size of " + keysize
+ " not supported in this runtime");
}
// throws IllegalArgumentException - if key is empty
final SecretKeySpec aesKey = new SecretKeySpec(keyData, "AES");
return aesKey;
} catch (final NoSuchAlgorithmException e) {
// AES functionality is a requirement for any Java SE runtime
throw new IllegalStateException(
"AES should always be present in a Java SE runtime", e);
}
}
public static String encodeAESKeyToBase64(final SecretKey aesKey)
throws IllegalArgumentException {
if (!aesKey.getAlgorithm().equalsIgnoreCase("AES")) {
throw new IllegalArgumentException("Not an AES key");
}
final byte[] keyData = aesKey.getEncoded();
final String encodedKey = Base64.getEncoder().encodeToString(keyData);
return encodedKey;
}
getEncoded()
不可用的位置),则存储/检索密钥可能不起作用。
实际上,路易斯提出的建议对我没有用。我不得不想办法。这就是帮助我的原因。可能也会帮助您。链接:
* .getEncoded():https://docs.oracle.com/javase/7/docs/api/java/security/Key.html
编码器信息:https : //docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html
解码器信息:https : //docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html
代码段:用于编码:
String temp = new String(Base64.getEncoder().encode(key.getEncoded()));
对于解码:
byte[] encodedKey = Base64.getDecoder().decode(temp);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");
您不想使用.toString()
。
请注意,SecretKey继承自java.security.Key,而java.security.Key本身也继承自Serializable。因此,这里的键(没有双关语)是将键序列化为ByteArrayOutputStream,获取byte []数组并将其存储到db中。相反的过程是从数据库中取出byte []数组,创建一个由byte []数组组成的ByteArrayInputStream,然后反序列化SecretKey。
...甚至更简单,只需使用.getEncoded()
从java.security.Key(这是SecretKey的父接口)继承的方法即可。此方法从Key / SecretKey返回编码的byte []数组,您可以从数据库存储或检索该数组。
所有这些都假设您的SecretKey实现支持编码。否则,getEncoded()
将返回null。
您应该查看Key / SecretKey Javadocs(可在Google页面的开始处找到):
http://download.oracle.com/javase/6/docs/api/java/security/Key.html
或者从CodeRanch(也可以通过相同的Google搜索找到):
http://www.coderanch.com/t/429127/java/java/Convertion-between-SecretKey-String-or
将SecretKeySpec转换为String,反之亦然:
您可以使用其中将给出的getEncoded()
方法,从该方法可以获取in 对象的值。SecretKeySpec
byteArray
encodeToString()
string
SecretKeySpec
Base64
虽然转换SecretKeySpec
到String
:使用decode()
中Base64
会给byteArray
,从您可以创建实例SecretKeySpec
与PARAMS为byteArray
重现您SecretKeySpec
。
String mAesKey_string;
SecretKeySpec mAesKey= new SecretKeySpec(secretKey.getEncoded(), "AES");
//SecretKeySpec to String
byte[] byteaes=mAesKey.getEncoded();
mAesKey_string=Base64.encodeToString(byteaes,Base64.NO_WRAP);
//String to SecretKeySpec
byte[] aesByte = Base64.decode(mAesKey_string, Base64.NO_WRAP);
mAesKey= new SecretKeySpec(aesByte, "AES");
试试这个,它可以在没有Base64的情况下工作(仅在JDK 1.8中包含),该代码也可以在以前的Java版本中运行:)
private static String SK = "Secret Key in HEX";
// To Encrupt
public static String encrypt( String Message ) throws Exception{
byte[] KeyByte = hexStringToByteArray( SK);
SecretKey k = new SecretKeySpec(KeyByte, 0, KeyByte.length, "DES");
Cipher c = Cipher.getInstance("DES","SunJCE");
c.init(1, k);
byte mes_encrypted[] = cipher.doFinal(Message.getBytes());
String MessageEncrypted = byteArrayToHexString(mes_encrypted);
return MessageEncrypted;
}
// To Decrypt
public static String decrypt( String MessageEncrypted )throws Exception{
byte[] KeyByte = hexStringToByteArray( SK );
SecretKey k = new SecretKeySpec(KeyByte, 0, KeyByte.length, "DES");
Cipher dcr = Cipher.getInstance("DES","SunJCE");
dc.init(Cipher.DECRYPT_MODE, k);
byte[] MesByte = hexStringToByteArray( MessageEncrypted );
byte mes_decrypted[] = dcipher.doFinal( MesByte );
String MessageDecrypeted = new String(mes_decrypted);
return MessageDecrypeted;
}
public static String byteArrayToHexString(byte bytes[]){
StringBuffer hexDump = new StringBuffer();
for(int i = 0; i < bytes.length; i++){
if(bytes[i] < 0)
{
hexDump.append(getDoubleHexValue(Integer.toHexString(256 - Math.abs(bytes[i]))).toUpperCase());
}else
{
hexDump.append(getDoubleHexValue(Integer.toHexString(bytes[i])).toUpperCase());
}
return hexDump.toString();
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
{
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
String
可以清除关键对象和字节数组,但是在Java中没有用于销毁实例的显式方法。这意味着密钥可以在内存中保持更长的时间。使用(受密码保护)KeyStore
,最好是由运行时系统/ OS甚至硬件支持的密码。