蚂蚁金服电话面试时,问到了RAS加密解密,感觉回答的有点模糊,遂写个例子加深一下印象

package cheng.test.cipher;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class RSADemo {
    
     /**
     * 公钥
     */  
    private RSAPublicKey publicKey;  
    /**
     * 私钥
     */  
    private RSAPrivateKey privateKey;  
    /**
     * 密文的长度
     */  
    private int encrytLength = 256;  
    /**
     * 持久化的公钥文件
     */
    private static final String publicKeyFile = "./public.key";
    /**
     * 持久化的私钥文件
     */
    private static final String privateKeyFile = "./private.key";
    /**
     * generate public key and private key
     * @throws NoSuchAlgorithmException
     */
    public void genKey() throws NoSuchAlgorithmException {
        KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");
        kg.initialize(encrytLength * 8);
        KeyPair kp = kg.generateKeyPair();
        
        publicKey = (RSAPublicKey) kp.getPublic();
        privateKey = (RSAPrivateKey) kp.getPrivate();
        //serialize the public key and the private key
        serailizeKey();
    }
    
    private void serailizeKey() {
        ObjectOutputStream pulicKeyOop = null;
        ObjectOutputStream privateKeyOop = null;
        try {
            pulicKeyOop = new ObjectOutputStream(new FileOutputStream(publicKeyFile));
            pulicKeyOop.writeObject(publicKey);
            privateKeyOop = new ObjectOutputStream(new FileOutputStream(privateKeyFile));
            privateKeyOop.writeObject(privateKey);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(null != pulicKeyOop) {
                    pulicKeyOop.close();
                }
                if(null != privateKeyOop) {
                    privateKeyOop.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    private RSAPublicKey getPublicKey() {
        ObjectInputStream ois = null;
        RSAPublicKey key = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(publicKeyFile));
            key = (RSAPublicKey)ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if(null != ois) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return key;
    }

    private RSAPrivateKey getPrivateKey() {
        RSAPrivateKey key = null;
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(privateKeyFile));
            key = (RSAPrivateKey)ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if(null != ois) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return key;
    }

    public byte[] encrypt(byte [] origin) {
        Cipher cipher = null;
        byte[] cn = null;
        try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, getPrivateKey());
            cn = cipher.doFinal(origin);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return cn;
    }
    
    public byte[] decrypt(byte[] enc) {
        Cipher cipher = null;
        byte[] cn = null;
        try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, getPublicKey());
            cn = cipher.doFinal(enc);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return cn;
    }

public static void main(String[] args) {
        RSADemo rs = new RSADemo();
//            rs.genKey();
        String content = "hello world...";
        byte[] encryptedContent = rs.encrypt(content.getBytes());
        System.out.println(new String(encryptedContent));
        byte[] decryptedContent = rs.decrypt(encryptedContent);
        System.out.println("\n" + new String(decryptedContent));
    }
}

RAS 加密 解密的更多相关文章

  1. 在ios开发中有多少常用的加密解密方式(备用)

    最常用的是MD5和base64编码,还有DES 3DES AES加密 ios怎么实现RAS加密解密 最近几天折腾了一下如何在iOS上使用RSA来加密.iOS上并没有直接的RSA加密API.但是iOS提 ...

  2. php rsa加密解密实例

    1.加密解密的第一步是生成公钥.私钥对,私钥加密的内容能通过公钥解密(反过来亦可以) 下载开源RSA密钥生成工具openssl(通常Linux系统都自带该程序),解压缩至独立的文件夹,进入其中的bin ...

  3. Go加密解密之RSA[转]

    安全总是很重要的,各个语言对于通用的加密算法都会有实现.前段时间,用Go实现了RSA和DES的加密解密,在这分享一下.(对于RSA和DES加密算法本身,请查阅相关资料) 在PHP中,很多功能经常是一个 ...

  4. C#中的三种 加密解密

    刚刚学会的C#的加密与解密(三种)MD5加密/RSA加密与解密/DES加密.也是刚刚申请的blog随便发布一下. (一).MD5加密 MD5 md5 = new MD5CryptoServicePro ...

  5. 信息安全-加密:RAS 加密

    ylbtech-信息安全-加密:RAS 加密 1.返回顶部 1. RSA 是不对称的加密(加密密钥和解密密钥不同  其中 一个为公钥,一个为私钥): 公钥和私钥的产生是基于一对很大的素数(十进制来说 ...

  6. C# RSA 无 长度限制 加密解密 示例

    RSA 是一种非对称加密算法.由于算法特性,加密和解密过程用不同密钥,即公钥和私钥,而被广泛应用于数字证书的安全管理. 在具体应用中,公钥用加密而私钥用于解密,或 私钥用于数字签名而公钥用于签名验证. ...

  7. PHP的学习--RSA加密解密

    PHP服务端与客户端交互或者提供开放API时,通常需要对敏感的数据进行加密,这时候rsa非对称加密就能派上用处了. 举个通俗易懂的例子,假设我们再登录一个网站,发送账号和密码,请求被拦截了. 密码没加 ...

  8. 兼容javascript和C#的RSA加密解密算法,对web提交的数据进行加密传输

    Web应用中往往涉及到敏感的数据,由于HTTP协议以明文的形式与服务器进行交互,因此可以通过截获请求的数据包进行分析来盗取有用的信息.虽然https可以对传输的数据进行加密,但是必须要申请证书(一般都 ...

  9. .NET和JAVA中BYTE的区别以及JAVA中“DES/CBC/PKCS5PADDING” 加密解密在.NET中的实现

    场景:java 作为客户端调用已有的一个.net写的server的webservice,输入string,返回字节数组. 问题:返回的值不是自己想要的,跟.net客户端直接调用总是有差距 分析:平台不 ...

随机推荐

  1. 17.4.3 使用MulticastSocket实现多点广播(5)

    该类主要实现底层的网络通信功能,在该类中提供了一个broadCast()方法,该方法使用Multicast Socket将指定字符串广播到所有客户端:还提供了sendSingle()方法,该方法使用D ...

  2. (三)Jquery Mobile按钮详细讲解

    Jquery Mobile按钮详细讲解 一.JM按钮说明 按钮如下图所示           1.HTML5中的button      效果:      2. JM中的普通button        ...

  3. jquery中如何以逗号分割字符串_百度知道

    body{ font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI& ...

  4. PHP学习笔记-1——快捷键

    整行删除 ctrl+E set get 生成 alt+ insert 查找.搜索和替换 Ctrl-F3 搜索位于插入点的词 F3/Shift-F3 在文件中查找下一个/上一个 Ctrl-F/H 在文件 ...

  5. ReactiveNative学习之Diff算法

    React 源码剖析系列 - 不可思议的 react diff深入浅出React(四):虚拟DOM Diff算法解析React diff 算法总结链接引用的文章React出于性能的考虑,为了避免频繁操 ...

  6. CentOS 7 源码编译安装 Mysql 5.7

    1.创建 mysql 用户,用户组,以及相关目录 /usr/sbin/groupadd mysql /usr/sbin/useradd -g mysql mysql mkdir -p /opt/loc ...

  7. iOS开发——应用图标上显示消息数量

    iOS8以前: UIApplication *app = [UIApplication sharedApplication]; app.applicationIconBadgeNumber = num ...

  8. Android 中内容提供者的使用

    在Android中内容提供者主要是用于不同程序之间的数据共享.内容提供器的用法一般有两种,一种是使用现有的内容提供器来读取和操作相应程序的数据,另一种是创建自己的内容提供器,供其他的程序访问. 使用现 ...

  9. MySQL 同步状态

    Exec_Master_Log_Pos: The position of the last event executed by the SQL thread from the master's bin ...

  10. iOS开发——闪光灯

    还是那句很欠揍的话,没啥难度,直接上代码. // //  ViewController.m //  Demo—闪光灯 // //  Created by yyt on 16/4/21. //  Cop ...