📄 e205. signing a java object.txt
字号:
A signed object makes a copy of a serializable object and signs it with a private key. Since the signed object makes a copy of the original object, any further modifications to the original object do not affect the signed object.
// Create a public and private key
PublicKey publicKey = null;
PrivateKey privateKey = null;
try {
// Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
keyGen.initialize(1024);
KeyPair keypair = keyGen.genKeyPair();
privateKey = keypair.getPrivate();
publicKey = keypair.getPublic();
} catch (NoSuchAlgorithmException e) {
}
// Create the signed object
SignedObject so = null;
try {
Serializable o = new MyClass();
Signature sig = Signature.getInstance(privateKey.getAlgorithm());
so = new SignedObject(o, privateKey, sig);
} catch (NoSuchAlgorithmException e) {
} catch (SignatureException e) {
} catch (InvalidKeyException e) {
} catch (IOException e) {
}
// Verify the signed object
try {
Signature sig = Signature.getInstance(publicKey.getAlgorithm());
// Verify the signed object
boolean b = so.verify(publicKey, sig);
// Retrieve the object
MyClass o = (MyClass)so.getObject();
} catch (SignatureException e) {
} catch (InvalidKeyException e) {
} catch (NoSuchAlgorithmException e) {
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}
public class MyClass implements Serializable {
String s = "my string";
int i = 123;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -