Skip to content

Instantly share code, notes, and snippets.

@userid
Last active December 29, 2017 07:27
Show Gist options
  • Select an option

  • Save userid/0f8dc93f775cb716ab309d02c2b66bd1 to your computer and use it in GitHub Desktop.

Select an option

Save userid/0f8dc93f775cb716ab309d02c2b66bd1 to your computer and use it in GitHub Desktop.
<?php
$pu_key = '
-----BEGIN PUBLIC KEY-----
MHwwDQYJKoZIhvcNAQEBBQADawAwaAJhALbr6abInZtlggBiXmgwl5fEUe3KHY9s
Zj4bomDh+Jn9IC2CXnLaHYxBzmyoakIMWlJn43cP5bSsqZMTKmKDj/WJ125yR068
L7uvm9YSQBi07hxeW+LISB5lpMrNyuZMnwIDAQAB
-----END PUBLIC KEY-----
';
$data = '1234567890!@#$%^&*()abcd';
for($i=0;$i<4; $i++){
$data = $data . $data ;
}
echo "data: $data\n";
$key = openssl_random_pseudo_bytes(16);
$iv = openssl_random_pseudo_bytes(16);
echo "key:" . base64_encode($key) . ' - ' . base64_encode($iv) . "\n";
base64_encode(openssl_public_encrypt ($key.$iv, $encrypted_key,$pu_key));//公钥加密
$encrypted_key= base64_encode($encrypted_key);
$encrypted_text = openssl_encrypt($data, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $iv);
$encrypted_text = base64_encode($encrypted_text);
echo "kk={$encrypted_key}&rr={$encrypted_text}";
<?php
#-- http://www.php.net/manual/en/function.openssl-public-encrypt.php#95307
$pu_key = '
-----BEGIN PUBLIC KEY-----
MHwwDQYJKoZIhvcNAQEBBQADawAwaAJhALbr6abInZtlggBiXmgwl5fEUe3KHY9s
Zj4bomDh+Jn9IC2CXnLaHYxBzmyoakIMWlJn43cP5bSsqZMTKmKDj/WJ125yR068
L7uvm9YSQBi07hxeW+LISB5lpMrNyuZMnwIDAQAB
-----END PUBLIC KEY-----
';
$data = '1234567890!@#$%^&*()abcd';
openssl_public_encrypt($data,$encrypted,$pu_key);//公钥加密
$encrypted = base64_encode($encrypted);
echo $encrypted,"\n";
#echo "private key decrypt:\n";
#openssl_private_decrypt(base64_decode($encrypted),$decrypted,$pi_key);//私钥解密
#echo $decrypted,"\n";
@userid
Copy link
Author

userid commented Dec 29, 2017

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.druid.util.Base64;


public class AesEncodeTest {
	private static final String ALGORITHM_AES = "AES/CBC/PKCS5Padding";
	public static void main(String [] s) throws Exception{
		byte[] encryptKey = "1234567890123456".getBytes();
		byte[] encryptIv = "0000000000000000".getBytes();
		byte[] data = "123456".getBytes();
		IvParameterSpec ivParameterSpec = new IvParameterSpec(encryptIv);
		SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES");
		Cipher cipher = Cipher.getInstance(ALGORITHM_AES);
		cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);	
		byte[] encrypted = cipher.doFinal(data);
		String out = Base64.byteArrayToBase64(encrypted);
		System.out.println(out);
	}
}
// rersult: 5u0pfa4PMX7/uCTaib3slA==

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment