我想在java中使用rsa / ecb / pkcs1填充模式对给定公钥(公钥是字符串)的字符串进行编码。
我还想以UTF-8格式呈现结果 怎么做?
答案 0 :(得分:0)
我已完成此代码:
String pub = "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA4IJZLsjlx+o4RSvafaAcReoNnzrI0UXu7kZyXPe31ql32X9AvhC6QQIUmLkr1Evm0zP/SgVG9YX3DSqBUgPo04iv1I1/wNKwAf1/uH9EiiqdpczefyxxnzJiKUTcx2/4mA4E4QxCIL5JsZb78WoYZrd2kToW/WD01MnSFiCgSyjGdd812GY2EVzfvlv8kYuti3icMUyitEfHhtw8cAWI6/nVrRPNs0e5NsvtZJ0nfrXsfQDR0C7+ivQK+fQabi8oRGsbTZceAvVlqVE669zoIwIFLcB+eYXTxbka4E7veUMpaF9w//HdwVS2y/2jJiI+16qPStQQPIKQ4Cucoif7/UHfIBuVGVJ5MIVyK7NC7TV/lyoXmyo7ZcnVZnI7rZcw5/qZcqaZ0VCrzvHijwTK7100hOOjiarvRa2OJGXHLIeAUlbrHOXEXS6ah2glPhLDEg6Qzp/lKVSISolal7q73qyhF483P9jXn3hefSLA9J1/1LgeajWvuVkxuw+dy2Tlv7oUpNBkX47/TOho5qttr1y9K3hD5Q87RAJPdBtFdDbY8qUPxoiBsTbUWjVoEjJf2YAsLTJIIi2ZISkbD/VdrtZnS73QSJkJReOMNT9XYNGDJvwNIrRcNGFKlJcX6qq+ozGNsDkrt0ObxAD7YCTjAYQVTlbQOaTu5DbGxGDNCoMCAwEAAQ==";
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] keyBytes = Base64.getDecoder().decode(pub.getBytes("UTF-8"));
PKCS1EncodedKeySpec KeySpec = new PKCS1EncodedKeySpec(keyBytes);
RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic((java.security.spec.KeySpec) KeySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(text.getBytes("UTF-8"));
return cipherData;
但它不起作用.. 据说无效的DER:对象不是整数
答案 1 :(得分:-1)
假设您使用的是有效的RSA密钥,则需要:
将公钥从字符串转换为实际的公钥对象
//This code is incorrect. You'll need bouncy castle for PKCS1
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] keyBytes = Base64().getDecoder.decode(publicKey.getBytes()); //assuming base64 encoded key
PKCS1EncodedKeySpec KeySpec = new PKCS1EncodedKeySpec(keyBytes);
RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(KeySpec);
获取纯文本的字节
查看步骤1-3的答案:RSA Encrypt/Decrypt in Java。在您的情况下,请记住使用正确的算法规范PKCS1
您的密文可能不会仅使用UTF-8字符,因此您可能希望使用Base 64编码的文本来显示密文。 Base 64能够将所有那些不稳定的字符显示为ascii值。
只需使用:Base64.getEncoder().encodeToString(cipherTextBytes)