我正在尝试将我的RSA密钥对大小从1024升级到2048.我将在此处提供示例代码。
对于1024: 我的代码的第一步是使用Java代码构建签名
try {
// Generate Public & Private Keys
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair keyPair = kpg.genKeyPair();
RSAPublicKey key = (RSAPublicKey) keyPair.getPublic();
System.out.println("Modulus");
System.out.println(key.getModulus());
String publicKey = encode(key.getModulus().toByteArray()) + encode(key.getPublicExponent().toByteArray());
// Build the Signature
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(keyPair.getPrivate());
seedData = seedData + "ABC";
sig.update(seedData.getBytes("UTF-8"));
String signature = encode(sig.sign());
signatureString.append(signature);
// Embed the public key in the signature
int publicKeyLocation = signatureString.charAt(signatureString.length() - 2) % 40;
// Add some random bytes at the end
int randomBytesToAdd = signatureString.charAt(signatureString.length() - 10) % 9;
System.out.println("Random bytes to add");
System.out.println(randomBytesToAdd);
System.out.println("Adding Random bytes that are:");
String s = randomString(randomBytesToAdd);
signatureString.insert(publicKeyLocation, s);
} catch (Exception e) {
}
return signatureString.toString();
}
现在这个编码的字符串传递给.NET应用程序 我曾经在.NET应用程序中获取公钥和签名
protected RSAParameters GetPublicKey(string encodedString)
{
int bytesToSkip = encodedString.Substring((encodedString.Length - 10), 1).ToCharArray()[0] % 9;
int publicKeyStarts = bytesToSkip + encodedString.Substring((encodedString.Length - 2), 1).ToCharArray()[0] % 40;
string keyString = encodedString.Substring(publicKeyStarts, 176);
string modulusString = keyString.Substring(0, 172);
string exponentString = keyString.Substring(172);
RSAParameters publicKey = new RSAParameters();
publicKey.Modulus = new byte[128];
Array.Copy(System.Convert.FromBase64String(modulusString), 1, publicKey.Modulus, 0, 128);
publicKey.Exponent = System.Convert.FromBase64String(exponentString);
return publicKey;
}
protected byte[] GetSignature(string encodedString)
{
int bytesToSkip = encodedString.Substring((encodedString.Length - 10), 1).ToCharArray()[0] % 9;
int publicKeyStarts = bytesToSkip + encodedString.Substring((encodedString.Length - 2), 1).ToCharArray()[0] % 40;
String digSig = encodedString.Substring(0, publicKeyStarts - bytesToSkip) + encodedString.Substring(publicKeyStarts + 176);
return System.Convert.FromBase64String(digSig);
}
如果我将密钥对大小从1024更改为2048,那么我需要在.NET代码中进行哪些更改
我正在寻找的答案是:从生成的RSA公钥中我如何获得模数和指数的长度
答案 0 :(得分:0)
我找到了从RSA公钥中获取模数和指数的大小或长度的答案
生成公钥的代码
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.genKeyPair();
RSAPublicKey key = (RSAPublicKey) keyPair.getPublic();
String publicKey = encode(key.getModulus().toByteArray()) + encode(key.getPublicExponent().toByteArray());
int modLength = key.getModulus().toByteArray().length;
int exponentLength = key.getPublicExponent().toByteArray().length;