蚂蚁金服电话面试时,问到了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. CodeForces 617C Watering Flowers

    无脑暴力题,算出所有点到圆心p1的距离的平方,从小到大排序. 然后暴力枚举p1的半径的平方,计算剩余点中到p2的最大距离的平方,枚举过程中记录答案 #include<cstdio> #in ...

  2. GIT使用规范流程

    1:每次开发新功能时,都应该新建立一个独立的分支(branch),整个项目工程有且只有一个主分支(master branch),项目发版时是从主分支上发布. Step01:切换到主分支 $ git c ...

  3. SecureCRT上传bash: rz: command not found

    SecureCRT上传bash: rz: command not found -bash: rz: command not found rz命令没找到? 执行sz,同样也没找到.     安装lrzs ...

  4. Linux Apache2 配置介绍

    转自:http://blog.csdn.net/hursing/article/details/18730813 apache原指http server程序,后来成为了该程序的组织名,所以把原程序名定 ...

  5. (简单) POJ 3414 Pots,BFS+记录路径。

    Description You are given two pots, having the volume of A and B liters respectively. The following ...

  6. 一种比较简单的在USB U盘中访问nandflash的方法

    u8 nandflash_write_buffer[NAND_SERECT_FULL_SIZE]; static int currentBlock = -1; static int currentPa ...

  7. lPC1788驱动SDRAM

    Sdram型号为hy57v256 #ifndef __SRAM_H_ #define __SRAM_H_ #include "common.h" #include "de ...

  8. ios 设置屏幕方向的两种方法

    第一种:通过人为的办法改变view.transform的属性. 具体办法: view.transform一般是View的旋转,拉伸移动等属性,类似view.layer.transform,区别在于Vi ...

  9. shell基本理论知识

    (1)查看系统上安装了哪些shell # cat /etc/shells # /etc/shells: valid login shells /bin/sh /bin/dash /bin/bash / ...

  10. Java 和Oracle的数据类型

    一.BigDecimal BigDecimal 由任意精度的整数非标度值 和 32 位的整数标度 (scale) 组成. 如果为零或正数,则标度是小数点后的位数. 如果为负数,则将该数的非标度值乘以 ...