在服务器中生成 RSA Public 密钥,发送到 Android,后者又加密一条消息并将其发送回解密的服务器
Generate RSA Public Key in the server, send to Android, which in turn encrypts a message and sends it back to the server where it is decrypted
以下代码用于生成 2048 位 RSA public/private 密钥。 public密钥发送到androidapp,用于加密服务端要解密的消息。
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] encoded = publicKey.getEncoded();
但是使用私钥,任何解密都会导致错误填充异常。
为了加密,使用了以下代码:
Cipher cipher = Cipher.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pKey = keyFactory.generatePublic(keySpec);
cipher.init(Cipher.ENCRYPT_MODE, pKey);
encoded = cipher.doFinal(clearText.getBytes());
在 android 和服务(使用 Spring 引导作为后端)端进行调试时,我注意到 android 中的提供程序(OpenSSLRSA 的一些实现..)和服务 (SunRSASign) 端不同。
因为我已经在考虑切换到 Bouncy Castle,所以我所要做的就是为这两个平台提及 Bouncy Castle 提供商,并且 encryption/decryption 都成功了。
像这样:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM, "BC");
// OR
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
希望这对某人有所帮助!
以下代码用于生成 2048 位 RSA public/private 密钥。 public密钥发送到androidapp,用于加密服务端要解密的消息。
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] encoded = publicKey.getEncoded();
但是使用私钥,任何解密都会导致错误填充异常。
为了加密,使用了以下代码:
Cipher cipher = Cipher.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pKey = keyFactory.generatePublic(keySpec);
cipher.init(Cipher.ENCRYPT_MODE, pKey);
encoded = cipher.doFinal(clearText.getBytes());
在 android 和服务(使用 Spring 引导作为后端)端进行调试时,我注意到 android 中的提供程序(OpenSSLRSA 的一些实现..)和服务 (SunRSASign) 端不同。
因为我已经在考虑切换到 Bouncy Castle,所以我所要做的就是为这两个平台提及 Bouncy Castle 提供商,并且 encryption/decryption 都成功了。
像这样:
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM, "BC");
// OR
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
希望这对某人有所帮助!