String content = ""; for(int i=1;i<100;i++)content += i + ") Easy to say, hard to do./n"; /*1、利用公钥加密至文件*/ { /*1)根据公钥反向构造PublickKey对象,调用cipher的init方法时使用*/ String KEY_PUBLIC = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIv38xXk06As11OCWq0IPQoQAmz20ZiE8T5KeaMTUbhzUkGNTAQygApua71R/INeEDNsyyQS4PT6EaWTjJop2rcCAwEAAQ=="; X509EncodedKeySpec keySpec = new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(KEY_PUBLIC)); PublicKey key = KeyFactory.getInstance("RSA").generatePublic(keySpec); Cipher cipher = Cipher.getInstance("RSA");//RSA/ECB/PKCS1PADDING cipher.init(Cipher.ENCRYPT_MODE, key); /* * 直接加密,因为内容太长将有异常,需要分块加密 * javax.crypto.IllegalBlockSizeException: Data must not be longer than 53 bytes * cipher.doFinal(content.getBytes()); */ /*2)分块加密,与KeyPairGenerator.initialize(int keysize)有关,本例使用的keysize为512*/ int blockSize = 53;//cipher.getBlockSize()为0?根据异常提示设的53 byte[] encryptByte = content.getBytes(); //根据块大小分块,不足一块的部分为一块 int blocksNum = (int)Math.ceil((1.0*encryptByte.length)/blockSize); FileOutputStream out = new FileOutputStream("license.lic"); for (int i = 0; i < blocksNum; i++) { if (i < blocksNum - 1) { out.write(cipher.doFinal(encryptByte, i * blockSize, blockSize)); } else { out.write(cipher.doFinal(encryptByte, i * blockSize, encryptByte.length - i * blockSize)); } } out.close(); } /*2、利用私钥从文件解密*/ { /*1)根据私钥反向构造PrivateKey对象*/ String KEY_PRIVATE = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAi/fzFeTToCzXU4JarQg9ChACbPbRmITxPkp5oxNRuHNSQY1MBDKACm5rvVH8g14QM2zLJBLg9PoRpZOMminatwIDAQABAkBqDAR7FBJbC15hgSQecV194D9WO3L18dOt9FNQgPSroGVYIvIizp1/wIHpMTN6uHwSoaZQcOqV33gxLF6fKbwxAiEAv390Q3X2cBjeScxhNbqPiOspE9rYD3eWSajN6Q7ud7UCIQC7HTUZelHMCpv4xPzg6e1QZkWhBfuqkhg9aOeAnIW0OwIgLW5Tat3FhXqg4ek29sQ34UfJCwjUUXcRlJATqcL9GDECIQChqe+JzrxDbVsrCY9vB83JLEO2hwPUcJtO24dBAHsopwIgEV547YcgZ+pyI1dnQhiLJiiFif+h1aBzaIH5mrkshtw="; PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(KEY_PRIVATE)); PrivateKey key = KeyFactory.getInstance("RSA").generatePrivate(keySpec); Cipher cipher = Cipher.getInstance("RSA");//RSA/ECB/PKCS1PADDING cipher.init(Cipher.DECRYPT_MODE, key); /*2)分块解密,根据每块加密输出大小确定*/ FileInputStream cis = new FileInputStream("license.lic"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); /*加密时分块加密,加密输出结果大小固定*/ byte[] data = new byte[cipher.getOutputSize(cis.available())]; int len = 0; while((len = cis.read(data)) > 0){ bos.write(cipher.doFinal(data, 0, len)); } cis.close(); System.out.print(new String(bos.toByteArray())); }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10934.html