java 密钥保存在哪里_Java加密-密钥的保存与获取

密钥一般存放在密钥文件中,常见的密钥文件有:jks、pfx、cer。jks是Java的keytools证书工具支持的证书私钥格式,pfx是微软支持的私钥格式,cer是证书的公钥。

从cer文件中获取公钥

/**

* 从cer文件中获取公钥

*

*/

@Test

public PublicKey getPublicKey(String certPath) throws CertificateException, IOException {

CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");

Certificate certificate = certificateFactory.generateCertificate(new FileInputStream(certPath));

return certificate.getPublicKey();

}

pfx文件中提取私钥

/**

* 从pfx文件中提取私钥

*

*/

public PrivateKey getPrivateKey(String argPfxFilePath, String argPfxPassword) throws Exception {

KeyStore keyStore = KeyStore.getInstance("PKCS12");

FileInputStream fis = new FileInputStream(argPfxFilePath);

keyStore.load(fis, argPfxPassword.toCharArray());

fis.close();

Enumeration enumeration = keyStore.aliases();

String keyAlias = null;

if (enumeration.hasMoreElements()) {

keyAlias = enumeration.nextElement();

}

return (PrivateKey) keyStore.getKey(keyAlias, argPfxPassword.toCharArray());

}

自己通过文件保存公私钥

将公私钥byte直接保存在文件中

/**

* 提取公钥的比特编码经过Base64转换后保存到文件,注意公钥的比特编码是X.509格式

*

* @param publicKey

* @param outPutFile

*/

public void savePublicKey2File(PublicKey publicKey, File outPutFile) throws Exception {

byte[] pbks = Base64.getEncoder().encode(publicKey.getEncoded());

FileOutputStream fos = new FileOutputStream(outPutFile);

fos.write(pbks);

fos.flush();

fos.close();

}

/**

* 提取私钥的比特编码经过Base64转换后保存到文件,注意私钥的比特编码是pkcs8格式

*

* @param privateKey

* @param outPutFile

*/

public void savePrivateKey2File(PrivateKey privateKey, File outPutFile) throws Exception {

byte[] prks = Base64.getEncoder().encode(privateKey.getEncoded());

FileOutputStream fos = new FileOutputStream(outPutFile);

fos.write(prks);

fos.flush();

fos.close();

}

从文件读取公私钥

/**

* 从文件中获取公钥(公钥的比特编码是X.509格式)

*

* @param certPath

* @return

* @throws Exception

*/

public PublicKey getPublicKeyByFile(String certPath) throws Exception {

FileInputStream fis = new FileInputStream(certPath);

ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len;

while ((len = fis.read(buffer)) > 0) {

bos.write(buffer, 0, len);

}

byte[] pbks = Base64.getDecoder().decode(bos.toByteArray());

X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(pbks);

PublicKey newPbk = KeyFactory.getInstance("RSA").generatePublic(encodedKeySpec);

return newPbk;

}

/**

* 从文件中获取公钥(私钥的比特编码是pkcs8格式)

*

* @param keyPath

* @return

* @throws Exception

*/

public PrivateKey getPrivateKeyByFile(String keyPath) throws Exception {

FileInputStream fis = new FileInputStream(keyPath);

ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = 0;

while ((len = fis.read(buffer)) > 0) {

bos.write(buffer, 0, len);

}

byte[] prks = Base64.getDecoder().decode(bos.toByteArray());

/**/

PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(prks);

PrivateKey newPrk = KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec);

return newPrk;

}

测试

@Test

public void testSaveKeyPair() throws Exception {

/**

* 随机生成秘钥对

*/

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

keyPairGenerator.initialize(1024);

KeyPair keyPair = keyPairGenerator.generateKeyPair();

PublicKey publicKey = keyPair.getPublic();

PrivateKey privateKey = keyPair.getPrivate();

/**

* 使用原始私钥加密,重新生成的公钥解密

*/

Cipher cipher = Cipher.getInstance("RSA");

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

byte[] bytes = cipher.doFinal("helloworld".getBytes());

System.out.println("原始公钥加密=" + Base64.getEncoder().encodeToString(bytes));

cipher.init(Cipher.DECRYPT_MODE, privateKey);

bytes = cipher.doFinal(bytes);

System.out.println("原始私钥解密=" + new String(bytes));

/**

* 从文件中提取公钥比特编码并恢复成公钥

*/

File privateKeyFile = new File("private_key");

this.savePrivateKey2File(privateKey, privateKeyFile);

File publicKeyFile = new File("public.key");

this.savePublicKey2File(publicKey, publicKeyFile);

cipher.init(Cipher.ENCRYPT_MODE, this.getPublicKeyByFile(publicKeyFile.getPath()));

bytes = cipher.doFinal("helloworld".getBytes());

System.out.println("从文件中获取公钥加密: " + Base64.getEncoder().encodeToString(bytes));

cipher.init(Cipher.DECRYPT_MODE, this.getPrivateKeyByFile(privateKeyFile.getPath()));

bytes = cipher.doFinal(bytes);

System.out.println("从文件中获取私钥解密: " + new String(bytes));

}

非对称加密算法是一种常用的加密方式,它采用了一对密钥,即公钥和私钥。公钥是公开的,可以任意分发,而私钥则只能由密钥的所有者持有,用于解密加密数据。常见的非对称加密算法包括RSA、DSA、ECC等。 下面是一个使用RSA算法实现非对称加密Java示例代码: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import javax.crypto.Cipher; public class RSAEncryptionExample { public static void main(String[] args) throws Exception { String input = "Hello World!"; KeyPair keyPair = generateRSAKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); byte[] encryptedData = rsaEncrypt(input.getBytes(), publicKey); byte[] decryptedData = rsaDecrypt(encryptedData, privateKey); System.out.println("Original data: " + input); System.out.println("Encrypted data: " + new String(encryptedData)); System.out.println("Decrypted data: " + new String(decryptedData)); } public static KeyPair generateRSAKeyPair() throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); // key size KeyPair keyPair = generator.generateKeyPair(); return keyPair; } public static byte[] rsaEncrypt(byte[] data, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedData = cipher.doFinal(data); return encryptedData; } public static byte[] rsaDecrypt(byte[] data, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedData = cipher.doFinal(data); return decryptedData; } } ``` 这个示例代码中,我们首先生成了一个RSA密钥对,包括公钥和私钥。然后使用公钥对原始数据进行加密,得到加密后的数据。接着使用私钥对加密后的数据进行解密,得到原始数据。 需要注意的是,RSA算法使用的密钥长度越长,安全性就越高,但加解密的速度也越慢。在实际应用中,需要根据实际需求和环境选择合适的密钥长度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值