目前项目有一个后台是使用RSA公钥加密,而后台给我的私钥是字符串, 请问如何把后台给的是要的字符串转换成PrivateKey
得看看是什么样的字符串啊。PrivateKey本身也会转化成字符串。文件的会分cer和pem还有key的。另外还要看语言,没有这些信息没办法转换的。
我贴一个demo,供参考:
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
public class PrivateKeyTest {
/**
* 根据私钥字符串生成私钥对象
*/
private static void test1() throws InvalidKeySpecException, NoSuchAlgorithmException {
byte[] bytes = "xxxx".getBytes();
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(bytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
}
/**
* 1、随机生成一个秘钥对
* 2、加密
* 3、解密
*/
private static void test2() throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, InvalidKeyException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
String text = "abcdefghijklmn";
// 加密
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(byteArrayOutputStream, encryptCipher);
DataOutputStream dataOutputStream = new DataOutputStream(cipherOutputStream);
dataOutputStream.writeUTF(text);
dataOutputStream.flush();
dataOutputStream.close();
byte[] cipherTextData = byteArrayOutputStream.toByteArray();
// 解密
Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic());
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(cipherTextData);
CipherInputStream cipherInputStream = new CipherInputStream(byteArrayInputStream, decryptCipher);
DataInputStream dataInputStream = new DataInputStream(cipherInputStream);
String result = dataInputStream.readUTF();
dataInputStream.close();
System.out.println("result = " + result);
}
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException {
test2();
}
}