我正在尝试生成第一个用于 RSA 加密的公钥/私钥对。这是我第一次这样做,但通过查看各种教程和网站,我决定使用以下代码来这样做。虽然我的代码没有给我错误,但它强制关闭。所有内容都已发布,包括我的导入,有人可以帮助我理解为什么我的代码没有生成密钥并给我错误吗?是的,我确实在 AndroidManifest.xml 文件中声明了它
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
public class RSA {
public static void GenerateKeyPair() {
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(4096);
KeyPair kp = kpg.genKeyPair();
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
RSAPrivateKeySpec.class);
saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
saveToFile("private.key", priv.getModulus(),
priv.getPrivateExponent());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void saveToFile(String fileName, BigInteger mod,
BigInteger exp) throws Exception {
ObjectOutputStream oout = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(fileName)));
try {
oout.writeObject(mod);
oout.writeObject(exp);
} catch (Exception e) {
throw new Exception("error", e);
} finally {
oout.close();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.BLAH"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".UUIDActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Installation"
android:label="@string/app_name" >
</activity>
<activity
android:name=".RSA"
android:label="@string/app_name" >
</activity>
</application>
</manifest>
我不知道是什么导致了你的问题(我们必须看看你在哪里使用这个类来调试它),但如果你可以包含第三方库,我确实有一个替代方案。看JSch http://www.jcraft.com/jsch/,它可以生成 RSA 密钥对(例如用于 SSH 公钥身份验证)。文档:http://epaul.github.com/jsch-documentation/simple.javadoc/ http://epaul.github.com/jsch-documentation/simple.javadoc/
您正在寻找的方法是密钥对.genKeyPair http://epaul.github.com/jsch-documentation/javadoc/com/jcraft/jsch/KeyPair.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)