無線通訊易遭竊聽,且裝置算力有限,傳統 TLS/SSL 完整實作過於沉重。Bouncy Castle 提供輕量級、開源、支援 MIDP 的完整密碼學套件,涵蓋對稱加密、非對稱加密、雜湊、數位簽章、憑證解析等,是 J2ME 安全開發的首選。
NoClassDefFoundError: java.math.BigInteger。推薦 ProGuard、RetroGuard(開源)或 DashO(商業)。public void generateRSAKeyPair() throws Exception {
SecureRandom sr = new SecureRandom();
BigInteger pubExp = new BigInteger("10001", 16); // 65537
RSAKeyGenerationParameters param = new RSAKeyGenerationParameters(pubExp, sr, 1024, 80);
RSAKeyPairGenerator gen = new RSAKeyPairGenerator();
gen.init(param);
AsymmetricCipherKeyPair pair = gen.generateKeyPair();
RSAPrivateCrtKeyParameters priv = (RSAPrivateCrtKeyParameters) pair.getPrivate();
RSAKeyParameters pub = (RSAKeyParameters) pair.getPublic();
// 儲存 priv/pub 供後續使用
}
public byte[] sign(byte[] data, RSAPrivateCrtKeyParameters priv) throws Exception {
SHA1Digest digest = new SHA1Digest();
RSAEngine engine = new RSAEngine();
PSSSigner signer = new PSSSigner(engine, digest, 64); // salt=64 bytes
signer.init(true, priv);
signer.update(data, 0, data.length);
return signer.generateSignature();
}
public boolean verify(byte[] data, byte[] sig, RSAKeyParameters pub) throws Exception {
SHA1Digest digest = new SHA1Digest();
RSAEngine engine = new RSAEngine();
PSSSigner signer = new PSSSigner(engine, digest, 64);
signer.init(false, pub);
signer.update(data, 0, data.length);
return signer.verifySignature(sig);
}
public byte[] encrypt(String plain, RSAKeyParameters pub) throws Exception {
AsymmetricBlockCipher cipher = new RSAEngine();
cipher.init(true, pub);
return cipher.processBlock(plain.getBytes(), 0, plain.getBytes().length);
}
public String decrypt(byte[] cipherText, RSAPrivateCrtKeyParameters priv) throws Exception {
AsymmetricBlockCipher cipher = new RSAEngine();
cipher.init(false, priv);
byte[] plain = cipher.processBlock(cipherText, 0, cipherText.length);
return new String(plain).trim();
}
public void parseCert(byte[] der) throws Exception {
ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(der));
ASN1Sequence seq = (ASN1Sequence) in.readObject();
X509CertificateStructure cert = new X509CertificateStructure(seq);
TBSCertificateStructure tbs = cert.getTBSCertificate();
System.out.println("Subject: " + tbs.getSubject());
System.out.println("Issuer: " + tbs.getIssuer());
System.out.println("Serial: " + tbs.getSerialNumber().getValue());
// Extensions 遍歷...
}
NoClassDefFoundError,確認所有相依類別皆已打包。Bouncy Castle 讓 J2ME 擁有桌面級密碼學能力,配合妥善的金鑰管理與混淆部署,能構建符合商業安全需求的行動應用。