1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Ruby OpenSSL::PKCS5.pbkdf2_hmac_sha1 をPHPで置き換えたときのメモ

Posted at
def self.encrypt(data, pass, salt)
    cipher = OpenSSL::Cipher::Cipher.new("AES-256-CBC")
    key_iv = OpenSSL::PKCS5.pbkdf2_hmac_sha1(pass, salt, 1000, cipher.key_len+cipher.iv_len)
    key = key_iv[0, cipher.key_len]
    iv  = key_iv[cipher.key_len, cipher.iv_len]
    cipher.encrypt
    cipher.key = key
    cipher.iv = iv
    encryptvalue = cipher.update(data) + cipher.final
    return Base64.b64encode(encryptvalue)
end
  
def self.decrypt(data, pass, salt)
    enctyptvalue = Base64.decode64(data)
    cipher = OpenSSL::Cipher::Cipher.new("AES-256-CBC")
    key_iv = OpenSSL::PKCS5.pbkdf2_hmac_sha1(pass, salt, 1000, cipher.key_len+cipher.iv_len)
    key = key_iv[0, cipher.key_len]
    iv  = key_iv[cipher.key_len, cipher.iv_len]
    cipher.decrypt
    cipher.key = key
    cipher.iv = iv
    cipher.update(enctyptvalue) + cipher.final
end
function encrypt($data, $pass, $salt) {
	$key_iv = openssl_pbkdf2($pass, $salt, 32+16, 1000);
	$key = substr($key_iv, 0, 32);
	$iv  = substr($key_iv, 32, 16);
	$decrypted_text = openssl_encrypt($data, 'AES-256-CBC', $key, 0, $iv);
	return $decrypted_text;
}
function decrypt($data, $pass, $salt) {
	$key_iv = openssl_pbkdf2($pass, $salt, 32+16, 1000);
	$key = substr($key_iv, 0, 32);
	$iv  = substr($key_iv, 32, 16);
	$decrypted_text = openssl_decrypt($data, 'AES-256-CBC', $key, 0, $iv);
	return $decrypted_text;
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?