如何使用Java中的RSAPrivateKeySpec类从字符串创建RSA PrivateKey?
我有以下信息,希望在RSA(Java)中生成公钥和私钥 以下是主要的加密和解密功能:如何使用Java中的RSAPrivateKeySpec类从字符串创建RSA PrivateKey?,java,rsa,Java,Rsa,我有以下信息,希望在RSA(Java)中生成公钥和私钥 以下是主要的加密和解密功能: static String Decrypt(String encodedString,PrivateKey privKey) { try { Cipher cipher = Cipher.getInstance(cipherInstancename); cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] de
static String Decrypt(String encodedString,PrivateKey privKey) {
try {
Cipher cipher = Cipher.getInstance(cipherInstancename);
cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encodedString));
return new String(decrypted, "UTF-8");
} catch (Exception err) {
return err.fillInStackTrace().toString();
}
}
static String Encrypt(String encodedString,PublicKey pubKey) {
try {
Cipher cipher = Cipher.getInstance(cipherInstancename);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] plainBytes = new String(encodedString).getBytes("UTF-8");
byte[] cipherData = cipher.doFinal(plainBytes);
String encryptedString = Base64.getEncoder().encodeToString(cipherData);
return encryptedString;
} catch (Exception err) {
return err.fillInStackTrace().toString();
}
}
如果我使用以下功能创建PrivateKey和PublicKey,一切都会很好:
static PrivateKey firstPrivateKey(String privateKeyStr) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(privateKeyStr.getBytes(StandardCharsets.UTF_8));
PKCS8EncodedKeySpec specPrivate = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey fileGeneratedPrivateKey = keyFactory.generatePrivate(specPrivate);
RSAPrivateKey rsaPrv = (RSAPrivateKey)(fileGeneratedPrivateKey);
return rsaPrv;
}
static PublicKey firstPublicKey(String publicKeyStr) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] keyBytes = Base64.getDecoder().decode(publicKeyStr.getBytes(StandardCharsets.UTF_8));
X509EncodedKeySpec specPublic = new X509EncodedKeySpec(keyBytes);
PublicKey fileGeneratedPublicKey = keyFactory.generatePublic(specPublic);
RSAPublicKey rsaPub = (RSAPublicKey)(fileGeneratedPublicKey);
return rsaPub;
}
但我想用下面的函数通过这种方式创建它们,但解密不起作用:
static PublicKey secondPublicKey(String publicKString,String publicExponentStr) throws Exception {
byte[] modulusBytes = Base64.getDecoder().decode(publicKString);
byte[] exponentBytes = Base64.getDecoder().decode(publicExponentStr);
BigInteger modulus = new BigInteger(1, modulusBytes);
BigInteger exponent = new BigInteger(1, exponentBytes);
RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(rsaPubKey);
return pubKey;
}
static PrivateKey secondPrivateKey(String privateKString,String privateExponentStr) throws Exception {
byte[] modulusBytes = Base64.getDecoder().decode(privateKString);
byte[] exponentBytes = Base64.getDecoder().decode(privateExponentStr);
BigInteger modulus = new BigInteger(1, modulusBytes);
BigInteger exponent = new BigInteger(1, exponentBytes);
RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modulus,exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privKey = fact.generatePrivate(privSpec);
return privKey;
}
String a = Encrypt("test",secondPublicKey(pubKey,eExponentPublic));
String b = Decrypt(a, secondPrivateKey(privKey,eExponentPrivate));
System.out.println(b);
使用firstPrivateKey和firstPublicKey生成器并正常工作:
String a = Encrypt("test",firstPrivateKey(pubKey));
String b = Decrypt(a, firstPublicKey(privKey));
System.out.println(b);
使用第二个功能但不起作用:
static PublicKey secondPublicKey(String publicKString,String publicExponentStr) throws Exception {
byte[] modulusBytes = Base64.getDecoder().decode(publicKString);
byte[] exponentBytes = Base64.getDecoder().decode(publicExponentStr);
BigInteger modulus = new BigInteger(1, modulusBytes);
BigInteger exponent = new BigInteger(1, exponentBytes);
RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(rsaPubKey);
return pubKey;
}
static PrivateKey secondPrivateKey(String privateKString,String privateExponentStr) throws Exception {
byte[] modulusBytes = Base64.getDecoder().decode(privateKString);
byte[] exponentBytes = Base64.getDecoder().decode(privateExponentStr);
BigInteger modulus = new BigInteger(1, modulusBytes);
BigInteger exponent = new BigInteger(1, exponentBytes);
RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modulus,exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privKey = fact.generatePrivate(privSpec);
return privKey;
}
String a = Encrypt("test",secondPublicKey(pubKey,eExponentPublic));
String b = Decrypt(a, secondPrivateKey(privKey,eExponentPrivate));
System.out.println(b);
secondPublicKey和secondPrivateKey函数有什么问题
更新:
我根据这段代码生成了所有的密钥和模,似乎我的解码不正常:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
// RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
kpg.initialize( 512 );
KeyPair kp = kpg.generateKeyPair();
String publicKeyStr = Base64.getEncoder().encodeToString(kp.getPublic().getEncoded());
String privateKeyStr = Base64.getEncoder().encodeToString(kp.getPrivate().getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] keyBytes = Base64.getDecoder().decode(publicKeyStr.getBytes(StandardCharsets.UTF_8));
X509EncodedKeySpec specPublic = new X509EncodedKeySpec(keyBytes);
PublicKey fileGeneratedPublicKey = keyFactory.generatePublic(specPublic);
RSAPublicKey rsaPub = (RSAPublicKey)(fileGeneratedPublicKey);
keyBytes = Base64.getDecoder().decode(privateKeyStr.getBytes(StandardCharsets.UTF_8));
PKCS8EncodedKeySpec specPrivate = new PKCS8EncodedKeySpec(keyBytes);
PrivateKey fileGeneratedPrivateKey = keyFactory.generatePrivate(specPrivate);
RSAPrivateKey rsaPrv = (RSAPrivateKey)(fileGeneratedPrivateKey);
BigInteger publicKeyModulus = rsaPub.getModulus();
BigInteger publicKeyExponent = rsaPub.getPublicExponent();
BigInteger privateKeyModulus = rsaPrv.getModulus();
BigInteger privateKeyExponent = rsaPrv.getPrivateExponent();
String nModulusPublic=Base64.getUrlEncoder().encodeToString(publicKeyModulus.toByteArray());
String eExponentPublic=Base64.getUrlEncoder().encodeToString(publicKeyExponent.toByteArray());
String nModulusPrivate=Base64.getUrlEncoder().encodeToString(privateKeyModulus.toByteArray());
String eExponentPrivate=Base64.getUrlEncoder().encodeToString(privateKeyExponent.toByteArray());
System.out.println(publicKeyStr);
System.out.println(privateKeyStr);
System.out.println( nModulusPublic);
System.out.println(eExponentPublic);
System.out.println( nModulusPrivate);
System.out.println(eExponentPrivate);
相关的公钥和私钥具有相同的模数。因此,
nModulusPublic
和nModulusPrivate
之间的区别实际上是不必要的(与公共和私人指数不同)
secondPublicKey()
和secondPrivateKey()
期望模数(nModulusPublic
或相同的nModulusPrivate
)作为第一个参数。而是传递整个密钥(publikey
或privKey
),从而导致错误。如果模量被传递,它就会起作用
顺便说一下,模数和指数是Base64url编码的,必须首先转换为标准Base64编码(-
->+
和->/
)。或者,Base64url解码器可以在secondPublicKey()
或secondPrivateKey()
(Base64.getUrlDecoder()
)中使用
由于两个公钥或私钥相同(仅具有不同的格式),因此任何公钥/私钥组合都可以用于加密/解密:
String pubKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJXFRUWMDJZ+moC/VbcAXoY5dDxOruwI2B+B+YZRHSRRTKPyd9v0HTqdLeVgufLu/cSxlZAKtZDp9mfgyNdbY9ECAwEAAQ==";
String privKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAlcVFRYwMln6agL9VtwBehjl0PE6u7AjYH4H5hlEdJFFMo/J32/QdOp0t5WC58u79xLGVkAq1kOn2Z+DI11tj0QIDAQABAkBC1Bp71OkNAgL47edWWADVja9y9X0R70RYkst/hpQlTrjN4QxzN4k4gCqqdFkno2LfacRO7igMQuVEmYujfkbNAiEA/lU1CyW9J65FXSObsBLxqlNpFw79B2EKUkT6o7b2Ez8CIQCWwJlIyDaoXt7CrvTrPDpok7U93ZKmDPiRjjXDPsGU7wIhAJ6pITIXFO2QNg1ojVNGPiR3bHPKEedsjjfMeF9xYAmZAiAQnfpHg4pC1PJJE2/73g+yJ1X7E8ludE+R+9MBSpGcEQIgBWaVSyTx4e+gSulT93vnMpVsYmiwe53e5t4Uxs+cgSE=";
String nModulusPublic = "AJXFRUWMDJZ-moC_VbcAXoY5dDxOruwI2B-B-YZRHSRRTKPyd9v0HTqdLeVgufLu_cSxlZAKtZDp9mfgyNdbY9E=".replace("-", "+").replace("_","/");
String eExponentPublic = "AQAB".replace("-", "+").replace("_","/");
String nModulusPrivate = "AJXFRUWMDJZ-moC_VbcAXoY5dDxOruwI2B-B-YZRHSRRTKPyd9v0HTqdLeVgufLu_cSxlZAKtZDp9mfgyNdbY9E=".replace("-", "+").replace("_","/");
String eExponentPrivate = "QtQae9TpDQIC-O3nVlgA1Y2vcvV9Ee9EWJLLf4aUJU64zeEMczeJOIAqqnRZJ6Ni32nETu4oDELlRJmLo35GzQ==".replace("-", "+").replace("_","/");
String a, b;
// first/first
a = Encrypt("test", firstPublicKey(pubKey));
b = Decrypt(a, firstPrivateKey(privKey));
System.out.println(b);
// second/second
a = Encrypt("test", secondPublicKey(nModulusPublic, eExponentPublic));
b = Decrypt(a, secondPrivateKey(nModulusPrivate, eExponentPrivate));
System.out.println(b);
// first/second
a = Encrypt("test", firstPublicKey(pubKey));
b = Decrypt(a, secondPrivateKey(nModulusPrivate, eExponentPrivate));
System.out.println(b);
// second/first
a = Encrypt("test", secondPublicKey(nModulusPublic, eExponentPublic));
b = Decrypt(a, firstPrivateKey(privKey));
System.out.println(b);
请注意,发布的代码中有一个输入错误:Encrypt
与firstPrivateKey()
结合使用,Decrypt
与firstPublicKey()结合使用
最好生成一个RSAPrivateCrtKey而不是PrivateKey,因为其他参数可能会在私钥中丢失,并且会在将来导致问题。因此,您还需要来自“primeP、primeQ、primeExpP、primeExpQ、crtCoefficient”的数据。请参见此处的示例:。看起来您正在进行一个C#到Java的项目,但是您的私钥中已经有丢失的数据作为C#端的xml字符串:-)模块和指数的编码很奇怪。它不是base64,因为-
和``字符表示正在使用base64urlencoding,但它不应以=
结尾。您可以尝试使用Base64.getUrlDecoder()
而不是Base64.getDecoder()
您的注释已被删除,但与更新部分有关的以下信息仍然存在:您使用了两种不同的编码:Base64(标准),因为Base64.getEncoder()
和Base64url,因为Base64.geturlcoder()
。Base64url使用字符-
和
而不是+
和/
,请参阅。我建议使用相同的编码(除非您有使用不同编码的特殊原因)。