不好意思 加密簽名我都要
私鑰加密得到的密文實(shí)際上就是數(shù)字簽名,要驗(yàn)證這個(gè)簽名是否正確,只能用私鑰持有者的公鑰進(jìn)行解密驗(yàn)證。使用數(shù)字簽名的目的是為了確認(rèn)某個(gè)信息確實(shí)是由某個(gè)發(fā)送方發(fā)送的,任何人都不可能偽造消息,并且,發(fā)送方也不能抵賴
防止抵賴
import javax.crypto.Cipher;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.*;
/**
* RSA 公認(rèn)目前最優(yōu)秀的公鑰方案之一
*/
public class RsaEncrypt {
public static void main(String[] args) throws Exception {
// 明文:
byte[] plain = "Hello, encrypt use RSA".getBytes(StandardCharsets.UTF_8);
// 創(chuàng)建公鑰/私鑰對(duì):
Partner alice = new Partner("Alice");
// 用Alice的公鑰加密:
byte[] pk = alice.getPublicKey();
System.out.println(String.format("public key: %x", new BigInteger(1, pk)));
byte[] encrypted = alice.encrypt(plain);
System.out.println(String.format("encrypted: %x", new BigInteger(1, encrypted)));
// 用Alice的私鑰解密:
byte[] sk = alice.getPrivateKey();
System.out.println(String.format("private key: %x", new BigInteger(1, sk)));
byte[] decrypted = alice.decrypt(encrypted);
System.out.println(new String(decrypted, StandardCharsets.UTF_8));
}
public static void sha1withRSA() throws GeneralSecurityException {
// 生成RSA公鑰/私鑰:
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
kpGen.initialize(1024);
KeyPair kp = kpGen.generateKeyPair();
PrivateKey sk = kp.getPrivate();
PublicKey pk = kp.getPublic();
// 待簽名的消息:
byte[] message = "Hello, I am Bob!".getBytes(StandardCharsets.UTF_8);
// 用私鑰簽名:
Signature s = Signature.getInstance("SHA1withRSA");
s.initSign(sk);
s.update(message);
byte[] signed = s.sign();
System.out.println(String.format("signature: %x", new BigInteger(1, signed)));
// 用公鑰驗(yàn)證:
Signature v = Signature.getInstance("SHA1withRSA");
v.initVerify(pk);
v.update(message);
boolean valid = v.verify(signed);
System.out.println("valid? " + valid);
}
}
class Partner {
String name;
// 私鑰:
PrivateKey sk;
// 公鑰:
PublicKey pk;
public Partner(String name) throws GeneralSecurityException {
this.name = name;
// 生成公鑰/私鑰對(duì):
KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");
kpGen.initialize(1024);
KeyPair kp = kpGen.generateKeyPair();
this.sk = kp.getPrivate();
this.pk = kp.getPublic();
}
// 把私鑰導(dǎo)出為字節(jié)
public byte[] getPrivateKey() {
return this.sk.getEncoded();
}
// 把公鑰導(dǎo)出為字節(jié)
public byte[] getPublicKey() {
return this.pk.getEncoded();
}
// 用公鑰加密:
public byte[] encrypt(byte[] message) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, this.pk);
return cipher.doFinal(message);
}
// 用私鑰解密:
public byte[] decrypt(byte[] input) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, this.sk);
return cipher.doFinal(input);
}
}
我方持有私鑰
我認(rèn)為
調(diào)用方調(diào)用之后 我方可用rsa進(jìn)行簽名加密后
返回調(diào)用方 告知調(diào)用方 調(diào)用方可做進(jìn)一步驗(yàn)證