栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java-使用现有的公钥文件加密字符串

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java-使用现有的公钥文件加密字符串

外壳程序中的这些openssl命令创建RSA密钥对,并将公用密钥和专用密钥写入 DER 格式的文件。

在这里,私钥文件没有密码保护(-nocrypt),以使事情变得简单。

$ openssl genrsa -out keypair.pem 2048Generating RSA private key, 2048 bit long modulus............+++................................+++e is 65537 (0x10001)$ openssl rsa -in keypair.pem -outform DER -pubout -out public.derwriting RSA key$ openssl pkcs8 -topk8 -nocrypt -in keypair.pem -outform DER -out private.der

现在有了DER文件,您可以用Java读取它们,并使用 KeySpecKeyFactory 创建 PublicKey
PrivateKey 对象。

public byte[] readFileBytes(String filename) throws IOException{    Path path = Paths.get(filename);    return Files.readAllBytes(path);        }public PublicKey readPublicKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException{    X509EnpredKeySpec publicSpec = new X509EnpredKeySpec(readFileBytes(filename));    KeyFactory keyFactory = KeyFactory.getInstance("RSA");    return keyFactory.generatePublic(publicSpec);       }public PrivateKey readPrivateKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException{    PKCS8EnpredKeySpec keySpec = new PKCS8EnpredKeySpec(readFileBytes(filename));    KeyFactory keyFactory = KeyFactory.getInstance("RSA");    return keyFactory.generatePrivate(keySpec);     }

使用公钥和私钥,可以加密和解密少量数据(适合RSA模数)。我建议使用 OAEP 填充。

public byte[] encrypt(PublicKey key, byte[] plaintext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");       cipher.init(Cipher.ENCRYPT_MODE, key);      return cipher.doFinal(plaintext);}public byte[] decrypt(PrivateKey key, byte[] ciphertext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");       cipher.init(Cipher.DECRYPT_MODE, key);      return cipher.doFinal(ciphertext);}

在这里,它与简单的加密和解密结合在一起:

public void Hello(){    try    {        PublicKey publicKey = readPublicKey("public.der");        PrivateKey privateKey = readPrivateKey("private.der");        byte[] message = "Hello World".getBytes("UTF8");        byte[] secret = encrypt(publicKey, message);        byte[] recovered_message = decrypt(privateKey, secret);        System.out.println(new String(recovered_message, "UTF8"));    }    catch (Exception e)    {        e.printStackTrace();    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/497526.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号