26
29

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 5 years have passed since last update.

AESでテキストを暗号化する(javascript)

Posted at

暗号化方式

AES、TKIP、WEPなど色々なアルゴリズムがありますが、今回はAESで暗号化します。モードはCBC。

キーのみで暗号/複号

var CryptoJS = require('crypto-js');

var pwd = "password";

function Encrypt(word) {
    return CryptoJS.AES.encrypt(word, pwd).toString();
}

function Decrypt(word) {
    return CryptoJS.AES.decrypt(word, pwd).toString(CryptoJS.enc.Utf8);
}

var origin = 'test';
console.log(origin);
var mm = Encrypt(origin);
console.log(mm);

var jm = Decrypt(mm);
console.log(jm);

キーとIVで暗号/複号

var CryptoJS = require('crypto-js');

var key = CryptoJS.enc.Utf8.parse('0123456789abcede');
var iv = CryptoJS.enc.Utf8.parse('1234567812345678');

function Encrypt(word) {
    srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
    return encrypted.ciphertext.toString().toUpperCase();
}

function Decrypt(word) {
    var encryptedHexStr = CryptoJS.enc.Hex.parse(word);
    var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    var decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
    var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}

var origin = 'test';
console.log(origin);
var mm = Encrypt(origin);
console.log(mm);

var jm = Decrypt(mm);
console.log(jm)

その他

「javascript側で暗号化→同じjavascript側で復号」ケースだけではなく、
「javascript/python/java側で暗号化->javascript/python/java側で復号」ケースにも活用できます。

26
29
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
26
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?