非对称密钥:应用场景

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", "");
}

}

相关推荐
pencek10 小时前
Hack-The-Box-Cap
网络安全
深邃-1 天前
【Web安全】-计算机网络协议(1):IP协议详解,HTTP协议介绍
linux·tcp/ip·计算机网络·安全·web安全·http·网络安全
录大大i1 天前
javaWeb中使用AES256+RSA网络数据加密
java·网络·网络安全
2301_780789661 天前
云服务器数据会泄露吗?怎么保护云服务器的数据
运维·服务器·tcp/ip·网络安全
汽车电子安全技术研究社2 天前
ISO_PAS 8800_2024 技术深度解读:全球首个道路车辆AI安全标准的核心框架与实施路径
网络安全·汽车电子·功能安全·aspice·预期功能安全
Chockmans2 天前
春秋云境CVE-2017-17733
安全·web安全·网络安全·网络攻击模型·安全威胁分析·春秋云境·cve-2017-17733
其实防守也摸鱼2 天前
软件安全与漏洞--软件安全设计
运维·网络·安全·网络安全·密码学·需求分析·软件安全
treesforest2 天前
IP地址段查询完全指南:从单IP查到IPv4段批量归属地查询
网络·数据库·网络协议·tcp/ip·网络安全·运维开发
сокол2 天前
【网安-Web渗透测试-内网渗透】内网横向移动——IPC连接
服务器·windows·网络安全·系统安全
捉鸭子2 天前
QQ音乐sign vmp逆向
爬虫·python·网络安全·网络爬虫