非对称密钥:应用场景

public class EncryptionAndSignatureExample {

复制代码
public static void main(String[] args) throws Exception {
    // 生成公私钥对
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    System.out.println("公钥:" + publicKey);
    System.out.println("私钥:" + privateKey);

    // 私钥加密、公钥验签示例
    String message = "Test message for signature";
    byte[] signature = sign(privateKey, message);
    boolean isVerified = verify(publicKey, message, signature);

    System.out.println("私钥加密、公钥验签结果: " + isVerified);

    // 公钥加密、私钥解密示例
    String encryptedMessage = encrypt(publicKey, "Secret message");
    String decryptedMessage = decrypt(privateKey, encryptedMessage);

    System.out.println("公钥加密、私钥解密后的消息: " + decryptedMessage);
}

public static byte[] sign(PrivateKey privateKey, String message) throws Exception {
    Signature signature = Signature.getInstance("SHA256withRSA");
    signature.initSign(privateKey);
    signature.update(message.getBytes());
    return signature.sign();
}

public static boolean verify(PublicKey publicKey, String message, byte[] signature) throws Exception {
    Signature verification = Signature.getInstance("SHA256withRSA");
    verification.initVerify(publicKey);
    verification.update(message.getBytes());
    return verification.verify(signature);
}

public static String encrypt(PublicKey publicKey, String message) throws Exception {
    // 这里简单模拟加密,实际应用中需使用更完善的加密逻辑
    return message + "_encrypted";
}

public static String decrypt(PrivateKey privateKey, String encryptedMessage) throws Exception {
    // 这里简单模拟解密,实际应用中需使用更完善的解密逻辑
    return encryptedMessage.replace("_encrypted", "");
}

}

相关推荐
见青..1 天前
文件上传漏洞之原理、探测、利用、绕过、防御
web安全·网络安全·漏洞·文件上传
hzhsec1 天前
启明星辰(安全服务实习生)面试题
网络安全·面试
持敬chijing1 天前
Web渗透之前后端漏洞-CORS跨越访问漏洞
安全·web安全·网络安全·网络攻击模型·安全威胁分析
HackTwoHub1 天前
免费FOFA高级会员、DayDaymap、360Quake、Hunter测绘搜索引擎高级会员免费使用最大1W条查询工具
运维·安全·web安全·搜索引擎·网络安全·系统安全·安全架构
学逆向的2 天前
C++纯虚函数
开发语言·c++·网络安全
买大橘子也用券2 天前
玄机-应急响应靶场-第一章wp汇总
网络安全·应急响应
其实防守也摸鱼2 天前
软件安全与漏洞--软件安全编码与防御技术理论题库
开发语言·网络·安全·网络安全·软件安全·软件安全与漏洞
夏天测2 天前
微信小程序自动化漏洞挖掘流水线:从缓存提取到密钥验证全流程实战
python·网络安全·微信小程序·漏洞挖掘
持敬chijing2 天前
Web渗透之前后端漏洞-命令注入
安全·web安全·网络安全·网络攻击模型·安全威胁分析
hhcgchpspk2 天前
xss漏洞学习笔记
笔记·学习·网络安全·xss