Java:如何把SecretKey保存下来

转自:http://berikontech.blogspot.com/2010/12/how-to-store-secretkey-in-java.html


This demo shows how to maintain a secret (symmetric) key in a java class. This key can then be used for encrypting / decrypting data that should be secret outside that class but must be transported. The Cipher used here is DESede, other ciphers could be used as well.

When using a KeyGenerator each time the class is initialized, the encrypted messages can not be read by a another process. Therefore the SecretKey is generated once, and then revived when the class is loaded.

** IMPORTANT **
Note that the SecretKey is now in your java source file, and will be in the compilation result. Your secrets can be read by anyone who can access your source or your binaries.


Generating the key

SecretKey key = KeyGenerator.getInstance("DESede").generateKey();
BigInteger num = new BigInteger(1, key.getEncoded());
System.out.println("Key: "+ num.toString())


Copy the resulting string (a big number)


Making the SecretKey available


public class YourClass {
private static String algorithm = "DESede";
private static byte[] encodedKey = new BigInteger("[[[[ Post the big number here ]]]]", 16).toByteArray();
}


Using the encoded SecretKey


DESedeKeySpec keySpec = new DESedeKeySpec(encodedKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey key = keyFactory.generateSecret(keySpec);

Cipher cipher = Cipher.getInstance(algorithm);
Cipher decipher = Cipher.getInstance(algorithm);

cipher.init(Cipher.ENCRYPT_MODE, key);
decipher.init(Cipher.DECRYPT_MODE, key);


Encrypting and decrypting


String message = "Hello World";
byte[] encryptedBytes = cipher.doFinal(message.getBytes());
String encryptedMessage = Base64.encode(encryptedBytes);

// Transport the base64 string, for example over http

byte[] messageToDecrypt = Base64.decode(encryptedMessage);
byte[] decryptedBytes = decipher.doFinal(messageToDecrypt);
String decryptedMessage = new String(decryptedBytes);
System.out.println(decryptedMessage);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值