Bouncy Castle J2ME 加载现有私钥
Posted
技术标签:
【中文标题】Bouncy Castle J2ME 加载现有私钥【英文标题】:Bouncy Castle J2ME load existing private key 【发布时间】:2013-01-13 12:15:40 【问题描述】:我有一个 PEM 或 DER 私钥,一个现有的密钥。如何加载此密钥
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();
接下来我可以尝试什么?
【问题讨论】:
【参考方案1】:我在 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 "";
【讨论】:
以上是关于Bouncy Castle J2ME 加载现有私钥的主要内容,如果未能解决你的问题,请参考以下文章
仅使用 Bouncy Castle 读取 PEM RSA 公钥
如何使用 Bouncy Castle 创建与 OpenSSH 兼容的 ED25519 密钥?
在没有 Bouncy Castle 的情况下,如何在 java 中从私有(ecdsa)生成公钥?