How to export symmetric encryption key?

情到浓时终转凉″ 提交于 2021-02-18 08:41:11

问题


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.


回答1:


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:

Initial generation and export

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");

Import/re-creation

// 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");


来源:https://stackoverflow.com/questions/20330494/how-to-export-symmetric-encryption-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!