Java非对称加密算法RSA

主方法类:

import javafx.scene.effect.DisplacementMap;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cuboo on 2016/10/14.
 */
public class Main {
    public static void main(String agrs[]) throws Exception {
        Map<String,Object> map;
        map = RSAcode.GenerateKeyPair("RSA",1024);
        RSAPublicKey publicKey = RSAcode.GetPublicKey(map);
        RSAPrivateKey privateKey = RSAcode.GetPrivateKey(map);
        byte[] encryptdata = RSAcode.encrypt(publicKey,"RSA","hello abc".getBytes());
        byte[] decryptdata = RSAcode.decrypt(privateKey,"RSA",encryptdata);
        System.out.println("公钥:"+publicKey);
        System.out.println("私钥:"+privateKey);
        System.out.println("加密:"+fromBytesToHexString(encryptdata));
        System.out.println("解密:"+new String(decryptdata));
    }

    public static String fromBytesToHexString(byte[] data){
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
             String s = Integer.toHexString(0xFF & data[i]);
            if (s.length() == 1){
                str.append(0).append(s);
            }else {
                str.append(s);
            }
        }
        return str.toString();
    }

    //十六进制字符串转字节数组
    public static byte[] fromHexStringToBytes(String hexString) {

        if ((hexString == null) || (hexString.equals("")) || hexString.length()%2 != 0){
            return null;
        }else{
            hexString = hexString.toUpperCase();
            int length = hexString.length()/2;
            char[] bytec = hexString.toCharArray();
            byte[] bit = new byte[length];
            for (int i = 0; i < length; i++){
                int p = 2 * i;
                //两个十六进制字符转换成1个字节,第1个字符转换成byte后左移4位,然后和第2个字符的byte做或运算
                bit[i] = (byte) (fromCharToByte(bytec[p]) << 4 | fromCharToByte(bytec[p + 1]));
            }
            return bit;
        }
    }

    //字符转换为字节
    private static byte fromCharToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

}


方法类:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cuboo on 2016/10/15.
 */
public class RSAcode {
    private static final String PUBLIC_KEY = "publickey";
    private static final String PRIVATE_KEY = "privatekey";

    /*
        *步骤1生成公钥和私钥 keyType = "RSA" keySize = 1024 512 - 65536(64的整数倍)
        */
    public static Map<String,Object> GenerateKeyPair(String keyType, int keySize) throws Exception {
        KeyPairGenerator pairGenerator = KeyPairGenerator.getInstance(keyType);
        pairGenerator.initialize(keySize);
        //生成秘钥对
        KeyPair keyPair = pairGenerator.generateKeyPair();
        //获得公钥和私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put(PUBLIC_KEY,publicKey);
        map.put(PRIVATE_KEY,privateKey);
        return  map;
    }
    /*
        *加密
        */
    public static byte[] encrypt(RSAPublicKey publickey,String keyType,byte[] data)
            throws Exception {
        Cipher cipher = Cipher.getInstance(keyType);
        cipher.init(Cipher.ENCRYPT_MODE,publickey);
        return cipher.doFinal(data);
    }

    /*
    *解密
    */
    public static byte[] decrypt(RSAPrivateKey privateKey,String keyType,byte[] data)
            throws Exception {
        Cipher cipher = Cipher.getInstance(keyType);
        cipher.init(Cipher.DECRYPT_MODE,privateKey);
        return cipher.doFinal(data);
    }
    /*
    *从Map中获得密钥对
    */
    public static RSAPublicKey GetPublicKey(Map<String,Object> map){
        RSAPublicKey publicKey = (RSAPublicKey) map.get(PUBLIC_KEY);
        return publicKey;
    }
    public static RSAPrivateKey GetPrivateKey(Map<String,Object> map){
        RSAPrivateKey privateKey = (RSAPrivateKey) map.get(PRIVATE_KEY);
        return privateKey;
    }
    
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非对称加密算法Java中有多种实现,其中最常用的是RSA算法。Java提供了内置的RSA算法库,可以方便地使用公钥加密和私钥解密,或者使用私钥签名和公钥验证签名。 要在Java中使用RSA算法进行非对称加密,可以按照以下步骤进行: 1. 生成RSA密钥对:使用`KeyPairGenerator`类生成一个RSA密钥对,其中包含公钥和私钥。 2. 获取公钥和私钥:从生成的密钥对中获取公钥和私钥,分别用于加密和解密。 3. 使用公钥加密:使用公钥对要加密的数据进行加密,可以使用`Cipher`类来进行加密操作。 4. 使用私钥解密:使用私钥对加密后的数据进行解密,同样可以使用`Cipher`类来进行解密操作。 以下是一个简单的示例代码,演示了如何在Java中使用RSA算法进行非对称加密: ```java import java.security.*; import javax.crypto.Cipher; public class RSAEncryptionExample { public static void main(String[] args) throws Exception { // 1. 生成RSA密钥对 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 2. 获取公钥和私钥 PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // 3. 使用公钥加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedData = cipher.doFinal("Hello, World!".getBytes()); // 4. 使用私钥解密 cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedData = cipher.doFinal(encryptedData); // 打印加密后和解密后的数据 System.out.println("加密后的数据:" + new String(encryptedData)); System.out.println("解密后的数据:" + new String(decryptedData)); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值