「java中rsa加密」java实现rsa加密

博主:adminadmin 2022-12-02 22:06:06 58

今天给各位分享java中rsa加密的知识,其中也会对java实现rsa加密进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

java中RSA用私钥加密公钥解密问题

公钥和私钥可以互换的用,用公钥加密私钥解密,用私钥加密公钥解密都ok,方法一样

Java中RSA的方式如何实现非对称加密的示例

代码如下,需要依赖一个jar包commons-codec-1.9.jar,用于Base64转换,请自行下载。

import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import java.io.ByteArrayOutputStream;

import java.io.UnsupportedEncodingException;

import java.security.*;

import java.security.interfaces.RSAPrivateKey;

import java.security.interfaces.RSAPublicKey;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

public class RSAUtils {

    // 加密方式

    public static final String ALGORITHM = "RSA";

    // 签名算法

    private static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";

    // 创建密钥对初始长度

    private static final int KEY_SIZE = 512;

    // 字符编码格式

    private static final String CHARSET = "UTF-8";

    // RSA最大加密明文大小

    private static final int MAX_ENCRYPT_BLOCK = 117;

    // RSA最大解密密文大小

    private static final int MAX_DECRYPT_BLOCK = 128;

    private KeyFactory keyFactory;

    public RSAUtils() throws NoSuchAlgorithmException {

        keyFactory = KeyFactory.getInstance(ALGORITHM);

    }

    /**

     * 私钥加密

     *

     * @param content    待加密字符串

     * @param privateKey 私钥

     * @return 加密后字符串(BASE64编码)

     */

    public String encryptByPrivateKey(String content, String privateKey) throws Exception {

        String result;

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {

            byte[] keyBytes = new Base64().decode(privateKey);

            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

            PrivateKey pKey = keyFactory.generatePrivate(pkcs8KeySpec);

            Cipher cipher = Cipher.getInstance(ALGORITHM);

            cipher.init(Cipher.ENCRYPT_MODE, pKey);

            byte[] data = content.getBytes(CHARSET);

            write2Stream(cipher, data, out);

            byte[] resultBytes = out.toByteArray();

            result = Base64.encodeBase64String(resultBytes);

        } catch (Exception e) {

            throw new Exception(e);

        }

        return result;

    }

    /**

     * 公钥解密

     *

     * @param content   已加密字符串(BASE64加密)

     * @param publicKey 公钥

     * @return

     */

    public String decryptByPublicKey(String content, String publicKey) throws Exception {

        String result = "";

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {

            byte[] keyBytes = new Base64().decode(publicKey);

            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);

            PublicKey pKey = keyFactory.generatePublic(x509KeySpec);

            Cipher cipher = Cipher.getInstance(ALGORITHM);

            cipher.init(Cipher.DECRYPT_MODE, pKey);

            byte[] data = Base64.decodeBase64(content);

            write2Stream(cipher, data, out);

            byte[] resultBytes = out.toByteArray();

            result = new String(resultBytes);

        } catch (Exception e) {

            throw new Exception(e);

        }

        return result;

    }

    /**

     * 公钥加密

     *

     * @param content   待加密字符串

     * @param publicKey 公钥

     * @return 加密后字符串(BASE64编码)

     */

    public String encryptByPublicKey(String content, String publicKey) throws Exception {

        String result = "";

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {

            byte[] keyBytes = new Base64().decode(publicKey);

            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);

            PublicKey pKey = keyFactory.generatePublic(x509KeySpec);

            Cipher cipher = Cipher.getInstance(ALGORITHM);

            cipher.init(Cipher.ENCRYPT_MODE, pKey);

            byte[] data = content.getBytes(CHARSET);

            write2Stream(cipher,

                    data, out);

            byte[] resultBytes = out.toByteArray();

            result = Base64.encodeBase64String(resultBytes);

        } catch (Exception e) {

            throw new Exception(e);

        }

        return result;

    }

    /**

     * 私钥解密

     *

     * @param content    已加密字符串

     * @param privateKey 私钥

     * @return 解密后字符串

     */

    public String decryptByPrivateKey(String content, String privateKey) throws Exception {

        String result = "";

        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {

            byte[] keyBytes = new Base64().decode(privateKey);

            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

            PrivateKey pKey = keyFactory.generatePrivate(pkcs8KeySpec);

            Cipher cipher = Cipher.getInstance(ALGORITHM);

            cipher.init(Cipher.DECRYPT_MODE, pKey);

            byte[] data = Base64.decodeBase64(content);

            write2Stream(cipher, data, out);

            byte[] resultBytes = out.toByteArray();

            result = new String(resultBytes);

        } catch (Exception e) {

            throw new Exception(e);

        }

        return result;

    }

    private static void write2Stream(Cipher cipher, byte[] data, ByteArrayOutputStream out) throws

            BadPaddingException, IllegalBlockSizeException {

        int dataLen = data.length;

        int offSet = 0;

        byte[] cache;

        int i = 0;

        // 对数据分段解密

        while (dataLen - offSet  0) {

            if (dataLen - offSet  MAX_DECRYPT_BLOCK) {

                cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);

            } else {

                cache = cipher.doFinal(data, offSet, dataLen - offSet);

            }

            out.write(cache, 0, cache.length);

            i++;

            offSet = i * MAX_DECRYPT_BLOCK;

        }

    }

    /**

     * 用私钥对信息生成数字签名

     *

     * @param data       已加密数据

     * @param privateKey 私钥(BASE64编码)

     * @return sign

     */

    public String sign(String data, String privateKey) throws Exception {

        String result = "";

        try {

            byte[] keyBytes = new Base64().decode(privateKey);

            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);

            PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);

            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

            signature.initSign(privateK);

            signature.update(parse2HexStr(data).getBytes(CHARSET));

            result = new Base64().encodeToString(signature.sign());

        } catch (Exception e) {

            throw new Exception(e);

        }

        return result;

    }

    /**

     * 校验数字签名

     *

     * @param data      已加密数据

     * @param publicKey 公钥(BASE64编码)

     * @param sign      数字签名

     * @return

     * @throws Exception

     */

    public boolean verify(String data, String publicKey, String sign) throws Exception {

        boolean result;

        try {

            byte[] keyBytes = new Base64().decode(publicKey);

            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

            PublicKey publicK = keyFactory.generatePublic(keySpec);

            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

            signature.initVerify(publicK);

            signature.update(parse2HexStr(data).getBytes(CHARSET));

            result = signature.verify(new Base64().decode(sign));

        } catch (Exception e) {

            throw new Exception(e);

        }

        return result;

    }

    /**

     * 将二进制转换成16进制

     *

     * @param data

     * @return

     */

    public static String parse2HexStr(String data) throws Exception {

        String result = "";

        try {

            byte[] buf = data.getBytes(CHARSET);

            StringBuffer sb = new StringBuffer();

            for (int i = 0; i  buf.length; i++) {

                String hex = Integer.toHexString(buf[i]  0xFF);

                if (hex.length() == 1) {

                    hex = '0' + hex;

                }

                sb.append(hex.toUpperCase());

            }

            result = sb.toString();

        } catch (UnsupportedEncodingException e) {

            throw new Exception(e);

        }

        return result;

    }

    /**

     * 生成公钥与私钥

     */

    public static void createKey() throws Exception {

        try {

            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);

            keyPairGenerator.initialize(KEY_SIZE);

            KeyPair keyPair = keyPairGenerator.generateKeyPair();

            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();

            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();

            String publicKey = Base64.encodeBase64String(rsaPublicKey.getEncoded());

            String privateKey = Base64.encodeBase64String(rsaPrivateKey.getEncoded());

            System.out.println("publicKey=" + publicKey + "\nprivateKey=" + privateKey);

        } catch (NoSuchAlgorithmException e) {

            throw new Exception(e);

        }

    }

    public static void main(String[] args) throws Exception {

        String PRIVATE_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKeYGXH6Vz+m+KuL11RDRaNdHB4YQeZgqpJGPRSwBelgvEoHu2/fNs1bmgfJhI8lhr/o/Hy8EFB/I/DDyLcCcU4bCLtxpki8edC+KJR2WvyYfnVmWEe/3q2jSVKRf81868q9Cd3MMfrQPMsY4x0TQ0GtOf/nMSMbAltV2W8J86IfAgMBAAECgYEApYu4lr2SMW3ddJZNvQ42W4g9nfyYG9igpJx8+VJmhIDpfLbmjzsOBwvUupx0NHH9CNQ7k3qxItJzzf+W5C+lesEOAqdO5nahRZsL8BIDoxTEn2j+1GXkzQw3vqPY50xqRnZsoP5TyNNsOM7KYaOoz4VFMdVIFwoT3OKM5z7mxgECQQD51r17WZDSa/kucaH7gCOePxJPS6Ust0eVd5tBOMpFzD/VtziogSIWyhGKkLH0SyTJEe91CCpdpxufLSZgIiN5AkEAq7ojtvU4twak1N1/1qX+t8f5wD8i/8GU702PeCwkGI5ymrARq+W2yCuvU1bouXBhjKHV4KhafKYixdHUMg00VwJAYVUjpLaUESY3gbyLWqvlNHVl8LaLtwwAO17JgXNaei7Ef8JNtHf6i95VTyJn8cCEqEDwhSuVNb8wp6azWKh0IQJBAJHrcT2d0bt0IcvfCynRk0eG3WnGPG8mhu9w8GAk4ecb47YdtmZio5YjyK8AQnCQVdOyEJL9eyY/5XxCeBSvs7ECQQCKQ2f5HLDkkHvc6rlaHCJmqNRCS+CxhoaiaSPYLAac7WXmb614ACLECc86C/nkefTq0SNpUDVbGxVpJi9/FOUf";

        String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnmBlx+lc/pviri9dUQ0WjXRweGEHmYKqSRj0UsAXpYLxKB7tv3zbNW5oHyYSPJYa/6Px8vBBQfyPww8i3AnFOGwi7caZIvHnQviiUdlr8mH51ZlhHv96to0lSkX/NfOvKvQndzDH60DzLGOMdE0NBrTn/5zEjGwJbVdlvCfOiHwIDAQAB";

        RSAUtils rsaUtil = new RSAUtils();

        String encryptByPublicKey = rsaUtil.encryptByPublicKey("你好!", PUBLIC_KEY);

        System.out.println(encryptByPublicKey);

        String decryptByPrivateKey = rsaUtil.decryptByPrivateKey(encryptByPublicKey, PRIVATE_KEY);

        System.out.println(decryptByPrivateKey);

        String encryptByPrivateKey = rsaUtil.encryptByPrivateKey("你好!", PRIVATE_KEY);

        System.out.println(encryptByPrivateKey);

        String decryptByPublicKey = rsaUtil.decryptByPublicKey(encryptByPrivateKey, PUBLIC_KEY);

        System.out.println(decryptByPublicKey);

        String sign = rsaUtil.sign("1234", PRIVATE_KEY);

        System.out.println("sign:" + sign);

        System.out.println(rsaUtil.verify("1234", PUBLIC_KEY, sign));

    }

}

java RSA实现对文件加密解密

这个我不清楚。

对文件加密,我使用的是超级加密3000.

超级加密3000采用国际上成熟的加密算法和安全快速的加密方法,可以有效保障数据安全!

具体操作方法:

1下载安装超级加密3000。

2 然后在需要加密的文件上单击鼠标右键选择加密。

3 在弹出的文件加密窗口中设置文件加密密码就OK了。

超级加密3000的下载地址你可以在百度上搜索超级加密3000,第一个就是。

怎样用Java实现RSA加密

提供加密,解密,生成密钥对等方法。�梢愿�模��遣灰��螅�裨蛐�驶岬� keyPairGen.initialize(KEY_SIZE, new SecureRandom()); KeyPair keyPair = keyPairGen.genKeyPair(); return keyPair; } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * 生成公钥 * @param modulus * @param publicExponent * @return RSAPublicKey * @throws Exception */ public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception { KeyFactory keyFac = null; try { keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); } catch (NoSuchAlgorithmException ex) { throw new Exception(ex.getMessage()); } RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent)); try { return (RSAPublicKey) keyFac.generatePublic(pubKeySpec); } catch (InvalidKeySpecException ex) { throw new Exception(ex.getMessage()); } } /** * 生成私钥 * @param modulus * @param privateExponent * @return RSAPrivateKey * @throws Exception */ public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws Exception { KeyFactory keyFac = null; try { keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); } catch (NoSuchAlgorithmException ex) { throw new Exception(ex.getMessage()); } RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent)); try { return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec); } catch (InvalidKeySpecException ex) { throw new Exception(ex.getMessage()); } } /** * 加密 * @param key 加密的密钥 * @param data 待加密的明文数据 * @return 加密后的数据 * @throws Exception */ public static byte[] encrypt(Key key, byte[] data) throws Exception { try { Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); cipher.init(Cipher.ENCRYPT_MODE, key); int blockSize = cipher.getBlockSize();//获得加密块大小� i++; } return raw; } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * 解密 * @param key 解密的密钥 * @param raw 已经加密的数据 * @return 解密后的明文 * @throws Exception */ public static byte[] decrypt(Key key, byte[] raw) throws Exception { try { Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider()); cipher.init(cipher.DECRYPT_MODE, key); int blockSize = cipher.getBlockSize(); ByteArrayOutputStream bout = new ByteArrayOutputStream(64); int j = 0; while (raw.length - j * blockSize 0) { bout.write(cipher.doFinal(raw, j * blockSize, blockSize)); j++; } return bout.toByteArray(); } catch (Exception e) { throw new Exception(e.getMessage()); } } /** * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { File file = new File("c:/test.html"); FileInputStream in = new FileInputStream(file); ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] tmpbuf = new byte[1024]; int count = 0; while ((count = in.read(tmpbuf)) != -1) { bout.write(tmpbuf, 0, count); tmpbuf = new byte[1024]; } in.close(); byte[] orgData = bout.toByteArray(); KeyPair keyPair = RSA.generateKeyPair(); RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey priKey = (RSAPrivateKey) keyPair.getPrivate(); byte[] pubModBytes = pubKey.getModulus().toByteArray(); byte[] pubPubExpBytes = pubKey.getPublicExponent().toByteArray(); byte[] priModBytes = priKey.getModulus().toByteArray(); byte[] priPriExpBytes = priKey.getPrivateExponent().toByteArray(); RSAPublicKey recoveryPubKey = RSA.generateRSAPublicKey(pubModBytes,pubPubExpBytes); RSAPrivateKey recoveryPriKey = RSA.generateRSAPrivateKey(priModBytes,priPriExpBytes); byte[] raw = RSA.encrypt(priKey, orgData); file = new File("c:/encrypt_result.dat"); OutputStream out = new FileOutputStream(file); out.write(raw); out.close(); byte[] data = RSA.decrypt(recoveryPubKey, raw); file = new File("c:/decrypt_result.html"); out = new FileOutputStream(file); out.write(data); out.flush(); out.close(); } } (责任编辑:云子)

java ibm jdk rsa 怎么 加密

android和java webservice RSA处理的不同

1.andorid机器上生成的(密钥对由服务器在windows xp下生成并将公钥发给客户端保存)密码无法在服务器通过私钥解密。

2.为了测试,在服务器本地加解密正常,另外,在android上加解密也正常,但是在服务器中加密(使用相同公钥)后的密码同样无法在android系统解密(使用相同私钥)。

3.由于对RSA加密算法不了解,而且对Java RSA的加密过程也不清楚、谷歌一番,才了解到可能是加密过程中的填充字符长度不同,这跟加解密时指定的RSA算法有关系。

4. 比如,在A机中使用标准RSA通过公钥加密,然后在B系统中使用“RSA/ECB/NoPadding”使用私钥解密,结果可以解密,但是会发现解密后的原文前面带有很多特殊字符,这就是在加密前填充的空字符;如果在B系统中仍然使用标准的RSA算法解密,这在相同类型的JDK虚拟机环境下当然是完全一样的,关键是android系统使用的虚拟机(dalvik)跟SUN标准JDK是有所区别的,其中他们默认的RSA实现就不同。

5.更形象一点,在加密的时候加密的原文“abc”,直接使用“abc”.getBytes()方法获得的bytes长度可能只有3,但是系统却先把它放到一个512位的byte数组里,new byte[512],再进行加密。但是解密的时候使用的是“加密后的密码”.getBytes()来解密,解密后的原文自然就是512长度的数据,即是在“abc”之外另外填充了500多字节的其他空字符。

java中rsa加密的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java实现rsa加密、java中rsa加密的信息别忘了在本站进行查找喔。

The End

发布于:2022-12-02,除非注明,否则均为首码项目网原创文章,转载请注明出处。