gpt4 book ai didi

java - Bouncy CaSTLe J2ME 加载现有私钥

转载 作者:行者123 更新时间:2023-12-04 05:15:45 29 4
gpt4 key购买 nike

我有一个 PEM 或 DER 私钥,一个现有的 key 。如何加载此 key
PrivateKeyFactory.createKey or into an AsymmetricCipherKeyPair ?

我试过这个:

InputStream inKey = getClass().getResourceAsStream("/samsjava/user_key_pk8.der");
byte[] binKey = new byte[inKey.available()];
inKey.read(binKey, 0, binKey.length);
inKey.close();


privKey = PrivateKeyFactory.createKey(binKey);
keyPair = new AsymmetricCipherKeyPair(new AsymmetricKeyParameter(false), privKey);

rsaPriv = (RSAPrivateCrtKeyParameters)keyPair.getPrivate();
rsaPub = (RSAPrivateCrtKeyParameters)keyPair.getPublic();

我接下来可以尝试什么?

最佳答案

我在 Java 中尝试了这个东西,这应该让我走上 J2ME 的正确轨道。这是代码:

public class EncrypDecrypt {
private RSAPrivateCrtKey rsaPriv;
private RSAPublicKey rsaPub;
private BASE64Decoder decoder;
private BASE64Encoder encoder;

public EncrypDecrypt(){
decoder = new BASE64Decoder();
encoder = new BASE64Encoder();
byte[] buffer;
try {
FileInputStream in = new FileInputStream("pathtofile.pfx");
KeyStore kStore = KeyStore.getInstance("PKCS12");
kStore.load(in, null);

PrivateKey privKeyEntry = (PrivateKey)kStore.getKey("Key Alias", null);
rsaPriv = (RSAPrivateCrtKey) privKeyEntry;
} catch (Exception ex) {
Logger.getLogger(EncrypDecrypt.class.getName()).log(Level.SEVERE, null, ex);
}
}

public String encrypt(String data){
try{
AsymmetricBlockCipher eng = new RSAEngine();
eng = new PKCS1Encoding(eng);
RSAKeyParameters publicKey = new RSAKeyParameters(true, rsaPriv.getModulus(), rsaPriv.getPublicExponent());
eng.init(true, publicKey);

byte[] encrypted = eng.processBlock(data.getBytes(), 0, data.getBytes().length);
return encoder.encode(encrypted);
}
catch(Exception err){
return "";
}
}

public String decrypt(String data){
try
{
byte[] encrypted = decoder.decodeBuffer(data);
AsymmetricBlockCipher eng = new RSAEngine();
eng = new PKCS1Encoding(eng);
RSAKeyParameters privateKey = new RSAKeyParameters(true, rsaPriv.getModulus(), rsaPriv.getPrivateExponent());
eng.init(false, privateKey);

byte[] decrypted = eng.processBlock(encrypted, 0, encrypted.length);
return new String(decrypted);
}
catch(Exception err){
return "";
}
}
}

关于java - Bouncy CaSTLe J2ME 加载现有私钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14303333/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com