0
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?

【Node.js】crypto.createCipherの廃止エラーを解決!安全な暗号化実装への移行方法

Posted at
Node.js暗号化APIの非推奨メソッド廃止による実装更新とセキュリティ向上を学んだ

📝 状況説明

[何を作っていた]:
StravaAPI接続と接続解除機能

[何が起きた]:
接続完了もUIが切り替わらない
コンソールログでエラーメッセージ
Strava callback error: TypeError: crypto.createCipher is not a function
    at StravaService.encryptToken (/path/to/project/backend/services/stravaService.js)

[どう解決した]:
crypto.createCipherとcrypto.createDecipherを現代的なcrypto.createCipherivとcrypto.createDecipherivに更新
適切なキー導出(SHA-256)と初期化ベクター(IV)生成を実装
暗号化データとIVを結合した安全なデータ形式を採用

💻 コード

Before(問題のコード)

  // トークン暗号化
  encryptToken(token) {
    if (!token) return null;
    const cipher = crypto.createCipher('aes-256-cbc', process.env.ENCRYPTION_KEY);
    let encrypted = cipher.update(token, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return encrypted;
  }

After(解決策)

  // トークン暗号化
  encryptToken(token) {
    if (!token) return null;
    const key = crypto.createHash('sha256').update(process.env.ENCRYPTION_KEY).digest();
    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    let encrypted = cipher.update(token, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return iv.toString('hex') + ':' + encrypted;
  }

  // トークン復号化
  decryptToken(encryptedToken) {
    if (!encryptedToken) return null;
    const key = crypto.createHash('sha256').update(process.env.ENCRYPTION_KEY).digest();
    const parts = encryptedToken.split(':');
    if (parts.length !== 2) {
      throw new Error('Invalid encrypted token format');
    }
    const iv = Buffer.from(parts[0], 'hex');
    const encryptedData = parts[1];
    const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
  }

💡 学んだこと

  • セキュリティ向上: crypto.createCipherは弱いキー導出を使用していたが、SHA-256による明示的キー導出とランダムIVでセキュリティが大幅向上
  • データ形式設計: IV:暗号化データの形式により、セキュアかつ実用的なトークン保存が可能。毎回異なる暗号化結果を実現
  • 現代暗号実装: createCipherivとcreateDecipherivを使用することで、暗号学の原理(キー導出、IV生成、データ形式)を正しく理解して実装

🔗 参考リンク

🏷️ タグ

#Node.js #Crypto #非推奨API #セキュリティ向上 #AES-256-CBC #暗号化 #StravaAPI

0
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
0
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?