2
1

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.

ApexでBlobからStringに変換しようとした時に起こったバグとその対処

Last updated at Posted at 2020-03-24

概要

ある文字列を暗号化してURLにパラメーターとして付与し、別ページでURLのパラメーターを受け取り復号化したいという状況

この際に、BLOb(Binary Large Object)からStringに変換する際、エンコード方式に制限があるようで、
「BLOB is not a valid UTF-8 string」
というエラーが出た。
その時の対処について記載する。

エラーの発生したソースコード

    Blob key=Crypto.generateAesKey(128);
    String encodedKey=key.toString();
    system.debug(encodedKey);
    Blob data=Blob.valueOf('00000');
    Blob encryptedData=Crypto.encryptWithManagedIV('AES128', key, data);
    String encodedEncryptedData=EncodingUtil.base64Encode(encryptedData);
    system.debug(encodedEncryptedData);
    Blob decodedEncryptedData=EncodingUtil.base64Decode(encodedEncryptedData);
    Blob decrypted=Crypto.decryptWithManagedIV('AES128', key, decodedEncryptedData);
    String toStringData=decrypted.toString();
    system.debug(toStringData);

原因部分

    String encodedKey=key.toString();

対処したソースコード

    Blob key=Crypto.generateAesKey(128);
    String encodedKey=EncodingUtil.base64Encode(key);
    system.debug(encodedKey);
    Blob data=Blob.valueOf('00000');
    Blob encryptedData=Crypto.encryptWithManagedIV('AES128', key, data);
    String encodedEncryptedData=EncodingUtil.base64Encode(encryptedData);
    system.debug(encodedEncryptedData);
    Blob decodedEncryptedData=EncodingUtil.base64Decode(encodedEncryptedData);
    Blob decrypted=Crypto.decryptWithManagedIV('AES128', key, decodedEncryptedData);
    String toStringData=decrypted.toString();
    system.debug(toStringData);

原因の推測

個人的には、generateAesKeyで生成されるBlob内にtoStringで変換するutf-8の形式に対応していない文字列が含まれているから変換できないのかな?と考えております。
Crypto.decryptWithManagedIVでdecryptoしたBlobをStringに変換することはできているので、generateAesKeyで生成されたBlobがutf-8で対応できない文字列を含んでいるのでできていないと考えました。
このエラーの原因がわかる方、推測できる方いらっしゃいましたらコメントなどで教えていただけると嬉しいです。

参考文献

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?