【发布时间】:2012-04-08 14:29:24
【问题描述】:
我正在尝试为 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>
【问题讨论】:
-
@Obliviator 我在您的问题中唯一检查的是,您说“是的,我确实在清单中声明了它”,这意味着您是否在 Manifest 中声明了这个类,它不是作为 Activity 扩展的,它肯定会给你最后发布的错误。所以你能显示你的清单文件代码吗?可能是你的 Activity 类。
标签: java android encryption rsa public-key-encryption