文章目录
非对称加密 1 常见算法 2 生成公钥和私钥 3 私钥加密 4 私钥加密 公钥解密 5 公钥和私钥的保存和读取 5.1 **保存公钥和私钥** 5.2 读取公钥和私钥
非对称加密
非对称加密算法又称现代加密算法。非对称加密是计算机通信安全的基石,保证了加密数据不会被破解。 与对称加密算法不同,非对称加密算法需要两个密钥:公开密钥(publickey) 和私有密(privatekey) 公开密钥和私有密钥是一对。如果用公开密钥对数据进行加密,只有用对应的私有密钥才能解密。如果用私有密钥对数据进行加密,只有用对应的公开密钥才能解密。 因为加密和解密使用的是两个不同的密钥,所以这种算法叫作非对称加密算法。
特点
加密和解密使用不同的密钥 如果使用私钥加密, 只能使用公钥解密 如果使用公钥加密, 只能使用私钥解密 处理数据的速度较慢, 因为安全级别高
示例
首先生成密钥对, 公钥为(5,14), 私钥为(11,14),A希望将原文2发送给B A使用公钥加密数据. 2的5次方mod 14 = 4 , 将密文4发送给B B使用私钥解密数据. 4的11次方mod14 = 2, 得到原文2
1 常见算法
RSA
RSA是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。 RSA公开密钥密码体制是一种使用不同的加密密钥与解密密钥。 RSA能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。只有短的RSA钥匙才可能被强力方式解破。世界上还没有任何可靠的攻击RSA算法的方式。只要其钥匙的长度足够长,用RSA加密的信息实际上是不能被解破的。 RSA算法基于一个十分简单的数论事实:将两个大质数相乘十分容易,但是想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。 RSA在线工具 希望深入学习RSA的小伙伴,请移步公开密钥加密之RSA算法 ECC(Elliptic curve cryptography)
椭圆曲线密码学(ECC),一种建立公开密钥加密的演算法,基于椭圆曲线数学。椭圆曲线在密码学中的使用是在1985年由Neal Koblitz和Victor Miller分别独立提出的。 希望深入学习ECC的小伙伴,请移步ECC椭圆曲线加解密原理详解(配图)
2 生成公钥和私钥
public static void main ( String [ ] args) throws NoSuchAlgorithmException {
String algorithm = "RSA" ;
KeyPairGenerator keyPairGenerator = KeyPairGenerator . getInstance ( algorithm) ;
KeyPair keyPair = keyPairGenerator. generateKeyPair ( ) ;
PrivateKey privateKey = keyPair. getPrivate ( ) ;
PublicKey publicKey = keyPair. getPublic ( ) ;
byte [ ] privateKeyEncoded = privateKey. getEncoded ( ) ;
byte [ ] publicKeyEncoded = publicKey. getEncoded ( ) ;
String privateKeyString = Base64 . encodeBase64String ( privateKeyEncoded) ;
String publicKeyString = Base64 . encodeBase64String ( publicKeyEncoded) ;
System . out. println ( "私钥:" + privateKeyString) ;
System . out. println ( "共钥:" + publicKeyString) ;
}
私钥:MIIG/QIBADANBgkqhkiG9w0BAQEFAASCBucwggbjAgEAAoIBgQC6hpkMQs+D0XefTNESooz3Cauz8Tpl7NaHKm3X8ZrqLO/QfCqW2ZoozlkXFi7nzNwPQ
BfEv1VgXhiT5VOy+r24Lcc3oakNtSWXYuBoXraJXdpE7EqVKdPSZbxzT3OhSQ0QqX3F2Y19euz5RB8jD9GBEJ+VHTnBKIpugX4irCWj1TYKbB8XGbH85wcWG
4uH2kn41DqM8IPw9TTDpMoyW7BEHShulOS+7G1Nd7rrtaf0tCyk9bVdms9Ou+JzKWRfCQFxuEH1sWvijW4R83OQYfpGa2kvJgiUQP0O9TQCmp0+ImWiThWfY
biqrFyJVynIDko8mFXXWolmdfq1myuNg126sUe1wPmZhtIC595hp965K8bwTiSg8weuSXOkAXJ7Cr4OLCOimSrB4qdLueqjAhMcQWuHXbGZCqnrbtOFmzxxR
NH8TWjhyPvtXldf7bK0CQaSuE2kfAi7YKwBwzI8iAbVomYh7EdVvMHq/YlwEPg8DqcuAJODaqcnZsy7omKuZWcCAwEAAQKCAYAIQ96URIGdfbKnRGgfQ0Srz
anmF1JXId9/rcmgP/x1U/hsbJQWix3hoQMhmsIJU3KM2nIzLadC1eiQ5SCIVcQCXUTumiM7kENSKfd3qHq+K4J4e1/y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wjopkqweKnS7nqowITHEFrh12xmQqp627ThZs8cUTR/E1o4
cj77V5XX+2ytAkGkrhNpHwIu2CsAcMyPIgG1aJmIexHVbzB6v2JcBD4PA6nLgCTg2qnJ2bMu6JirmVnAgMBAAE=
3 私钥加密
public static void main( String[ ] args) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
String input = "国泰民安" ;
// 加密算法
String algorithm = "RSA" ;
// 创建密钥对生成器对象
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance( algorithm) ;
// 生成密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair( ) ;
// 生成私钥
PrivateKey privateKey = keyPair.getPrivate( ) ;
// 生成公钥
PublicKey publicKey = keyPair.getPublic( ) ;
// 创建加密对象
// 参数表示加密算法
Cipher cipher = Cipher.getInstance( algorithm) ;
// 初始化加密
// 第一个参数:加密的模式
// 第二个参数:使用私钥进行加密
cipher.init( Cipher.ENCRYPT_MODE,privateKey) ;
// 私钥加密
byte[ ] bytes = cipher.doFinal( input.getBytes( )) ;
System.out.println( Base64.encodeBase64String( bytes)) ;
}
gjfiD1F+DOFk2IHqrTWSKe+8qGLCihNuu+RrZY6CKji0H56RUhSL3P5fW2X3FXpCrY+CMsGg16HfmR3boeX1qY4e0NJU0JtE1Ch4uERigH1eM/MUCUaFaVI4
9roDAcqbz0v+lnsX41mOCQ4YSd742XoIg7cJX1GcsHhkXDF3JCM/fDxdHYR63ApmSpzr+qfoelntnc+Xah90i3UR/PPiEZ6/6JWz7mU5DK/X5IVnqgGObNCl
syH7tWcwl34IcrszFvK4ovtxeYVQken7IHgW8LMCxWGXWyDThC+9A/d9AV9vlLLuzZcYEvRYMS5BzZqr9gzdrgYE1hsRouFQ0yyuOUoVAbaqAjqhPRTTIj0E
QUl2PpB7hi561x/j/58w9dsoI3gKp/G6SBl40yyuxbm5z/RGYxjeZhyIC4Lm/ddpCQpJ5qzZ/WX6N9fSqjwQLaHSQpgmsy5zdZRkZchxknw8LgONSzObwA5/
F561oXgtHWD44+SzZHoOGY3hDSU3oKMT
4 私钥加密 公钥解密
public static void main ( String [ ] args) throws NoSuchAlgorithmException , InvalidKeyException , NoSuchPaddingException , IllegalBlockSizeException , BadPaddingException {
String input = "国泰民安" ;
System . out. println ( input) ;
String algorithm = "RSA" ;
KeyPairGenerator keyPairGenerator = KeyPairGenerator . getInstance ( algorithm) ;
KeyPair keyPair = keyPairGenerator. generateKeyPair ( ) ;
PrivateKey privateKey = keyPair. getPrivate ( ) ;
PublicKey publicKey = keyPair. getPublic ( ) ;
Cipher cipher = Cipher . getInstance ( algorithm) ;
cipher. init ( Cipher . ENCRYPT_MODE, privateKey) ;
byte [ ] bytes = cipher. doFinal ( input. getBytes ( ) ) ;
System . out. println ( Base64 . encodeBase64String ( bytes) ) ;
cipher. init ( Cipher . DECRYPT_MODE, publicKey) ;
byte [ ] bytes1 = cipher. doFinal ( bytes) ;
System . out. println ( new String ( bytes1) ) ;
}
国泰民安
VfUXV9TiXxeRx5/gq13GtsNm76BSw/63e1SaOI1szLnb9DjE4hfCmim0qqqOQYSp5fyE45694Dlj37p7/+eu7gMAuJN5PYZfN7bYQZ+ZIJeXCiEO/IWXFzQW
yIgoyqUjZ1i6ja0yfHhY0FXkBBJCr2SNwBiMW1lEQav0UE/i05Dj3+OOKDTKNbIgMLcsZfM3WPSNJWJq7bthnjO0KTPSdG5Dl+/eJictaSGTk0it5+D1l4G6
N8CfTfshG9c3vWbfmqgmU8GaA5Iqo1eHINPpS9SZOoAAokGEzmDkx2VJQiQO3GELIdcCGvyWvZIm7PlAV8EYzxTQiHRSuwiCJyGGABC+I9iEFwDaZwYCTAh7
roSwtpt1ax/KgQfbhv8vNE+/3ADnnvFgzDX6LfWuSl0vhclh9kl0ECnIICJd6dxKwCAZkctiwdOoPrbGnK4lWXbeTbdkxBpdw9LcnWMkCuCVy53k47OjB3S+
t+Uktr2snJAjJDYG4ZZmrQpEIj17zLKZ
国泰民安
5 公钥和私钥的保存和读取
5.1 保存公钥和私钥
public static void main ( String [ ] args) throws Exception {
String input = "硅谷" ;
String algorithm = "RSA" ;
generateKeyToFile ( algorithm, "a.pub" , "a.pri" ) ;
}
private static void generateKeyToFile ( String algorithm, String pubPath, String priPath) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator . getInstance ( algorithm) ;
KeyPair keyPair = keyPairGenerator. generateKeyPair ( ) ;
PublicKey publicKey = keyPair. getPublic ( ) ;
PrivateKey privateKey = keyPair. getPrivate ( ) ;
byte [ ] publicKeyEncoded = publicKey. getEncoded ( ) ;
byte [ ] privateKeyEncoded = privateKey. getEncoded ( ) ;
String publicKeyString = Base64 . encodeBase64String ( publicKeyEncoded) ;
String privateKeyString = Base64 . encodeBase64String ( privateKeyEncoded) ;
FileUtils . writeStringToFile ( new File ( pubPath) , publicKeyString, Charset . forName ( "UTF-8" ) ) ;
FileUtils . writeStringToFile ( new File ( priPath) , privateKeyString, Charset . forName ( "UTF-8" ) ) ;
}
5.2 读取公钥和私钥
public static void main ( String [ ] args) throws Exception {
String input = "明德新民,止于至善" ;
String algorithm = "RSA" ;
generateKeyToFile ( algorithm, "a.pub" , "a.pri" ) ;
PrivateKey privateKey = getPrivateKey ( "a.pri" , algorithm) ;
PublicKey publicKey = getPublicKey ( "a.pub" , algorithm) ;
String s = encryptRSA ( algorithm, privateKey, input) ;
String res = decryptRSA ( algorithm, publicKey, s) ;
System . out. println ( res) ;
}
public static String decryptRSA ( String algorithm, Key key, String encrypted) throws Exception {
Cipher cipher = Cipher . getInstance ( algorithm) ;
cipher. init ( Cipher . DECRYPT_MODE, key) ;
byte [ ] decode = Base64 . decodeBase64 ( encrypted) ;
byte [ ] bytes1 = cipher. doFinal ( decode) ;
return new String ( bytes1) ;
}
public static String encryptRSA ( String algorithm, Key key, String input) throws Exception {
Cipher cipher = Cipher . getInstance ( algorithm) ;
cipher. init ( Cipher . ENCRYPT_MODE, key) ;
byte [ ] bytes = cipher. doFinal ( input. getBytes ( ) ) ;
return Base64 . encodeBase64String ( bytes) ;
}
public static PublicKey getPublicKey ( String pulickPath, String algorithm) throws Exception {
String publicKeyString = FileUtils . readFileToString ( new File ( pulickPath) , Charset . defaultCharset ( ) ) ;
KeyFactory keyFactory = KeyFactory . getInstance ( algorithm) ;
X509EncodedKeySpec spec = new X509EncodedKeySpec ( Base64 . decodeBase64 ( publicKeyString) ) ;
return keyFactory. generatePublic ( spec) ;
}
private static void generateKeyToFile ( String algorithm, String pubPath, String priPath) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator . getInstance ( algorithm) ;
KeyPair keyPair = keyPairGenerator. generateKeyPair ( ) ;
PublicKey publicKey = keyPair. getPublic ( ) ;
PrivateKey privateKey = keyPair. getPrivate ( ) ;
byte [ ] publicKeyEncoded = publicKey. getEncoded ( ) ;
byte [ ] privateKeyEncoded = privateKey. getEncoded ( ) ;
String publicKeyString = Base64 . encodeBase64String ( publicKeyEncoded) ;
String privateKeyString = Base64 . encodeBase64String ( privateKeyEncoded) ;
FileUtils . writeStringToFile ( new File ( pubPath) , publicKeyString, Charset . forName ( "UTF-8" ) ) ;
FileUtils . writeStringToFile ( new File ( priPath) , privateKeyString, Charset . forName ( "UTF-8" ) ) ;
}
public static PrivateKey getPrivateKey ( String priPath, String algorithm) throws Exception {
String privateKeyString = FileUtils . readFileToString ( new File ( priPath) , Charset . defaultCharset ( ) ) ;
KeyFactory keyFactory = KeyFactory . getInstance ( algorithm) ;
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec ( Base64 . decodeBase64 ( privateKeyString) ) ;
return keyFactory. generatePrivate ( spec) ;
}