【问题标题】:Uncaught TypeError: Cannot read property 'encrypt' of undefined未捕获的类型错误:无法读取未定义的属性“加密”
【发布时间】:2022-01-31 18:01:56
【问题描述】:

我想在 JavaScript 端使用 RSA_OAEP_SHA256 进行加密。 我正在使用第三方库 asmcrypto.js

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/asmCrypto/0.22.0/asmcrypto.js"></script>
    <script>
        var encrypted = asmCrypto.RSA_OAEP_SHA256.encrypt(stringToBeEncrypted, pubkey, "");
    </script>

出现错误:未捕获的类型错误:无法读取未定义的属性“加密”。

有人知道解决方案或任何有用的例子吗?

【问题讨论】:

  • asmCrypto.RSA_OAEP_SHA256 === undefined
  • 谢谢。那个错误现在消失了!!但现在它在浏览器控制台中打印在错误下方。 rsa.js:41 Uncaught TypeError: 在 RSA_OAEP.reset (pkcs1.js:40) 在 Object.rsa_oaep_sha256_encrypt_bytes [as encrypt ] (exports-oaep-sha256.js:11) at get (MntRole.jsp:229) at :1:1 我是否必须导入错误堆栈中提到的所有 .js 文件?

标签: javascript rsa sha256


【解决方案1】:

所以我终于找到了解决方案,我在这里分享它,以便对某人有所帮助。

  1. 我更改了库并使用了 jsencrypt.min.js JSEncrypt 它是支持 OAEP 填充的更新版本。
  2. JavaScript 代码:

<script type="text/javascript" src="/RSO/includes/jsencrypt.min.js"></script>
function get(tmpSubmit)
{
  <%
  String key = BouncyCastlePemUtils.readPublicKey();
  System.out.println("readPublicKey: " + key);
  %>    

  alert('<%=key %>');
  var publicKey = '<%=key %>';
  var password = "Dhiraj is the author";
  var RSAEncrypt = new JSEncrypt();
  RSAEncrypt.setPublicKey(publicKey);
  var encryptedPass = RSAEncrypt.encrypt(password, true);
  document.write("encryptedPass: "+encryptedPass)

}
  1. 使用 openssl 生成公钥和私钥,请查看以下链接获取命令。

openssl commands

  1. 用于加密和解密数据的 Java 类:

package com.demo.rsa;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.Serializable;
    import java.nio.charset.StandardCharsets;
    import java.security.NoSuchAlgorithmException;
    import java.security.Security;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    
    import javax.crypto.Cipher;
    import javax.xml.bind.DatatypeConverter;
    
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    
    import com.demo.util.CommonProperties;
    
    public class PEMDemo implements Serializable {
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        public String encrypt(String plainText, RSAPublicKey publicKey) throws Exception {
            Cipher cipher = getCipher();
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
            
            return DatatypeConverter.printBase64Binary(encryptedText);
        }
    
        public String decrypt(String cipherText, RSAPrivateKey privateKey) throws Exception {
            byte[] cipherBytes;
            cipherBytes = DatatypeConverter.parseBase64Binary(cipherText);
            Cipher cipher = getCipher();
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[]  decryptedText = cipher.doFinal(cipherBytes);
            
            return new String(decryptedText, StandardCharsets.UTF_8);
        }
    
        private Cipher getCipher() throws Exception {
            Security.addProvider(new BouncyCastleProvider());
            return Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", new BouncyCastleProvider());
        }
    
        public static RSAPublicKey getPublicKey(){
            RSAPublicKey publicKey = null;
            try {
                File publicKeyFile = new File(CommonProperties.propBag.getProperty("RSA_CONFIG_PATH")+"public_key.pem");
                publicKey = BouncyCastlePemUtils.readX509PublicKey(publicKeyFile);
            } catch (InvalidKeySpecException | NoSuchAlgorithmException | IOException e) {
                e.printStackTrace();
            }
            return publicKey;
        }
        
        public static RSAPrivateKey getPrivateKey(){
            RSAPrivateKey privateKey = null;
            try {
                File privateKeyFile = new File(CommonProperties.propBag.getProperty("RSA_CONFIG_PATH")+"private_key.pem");
                privateKey = BouncyCastlePemUtils.readPKCS8PrivateKey(privateKeyFile);
            } catch (InvalidKeySpecException | NoSuchAlgorithmException | IOException e) {
                e.printStackTrace();
            }
            return privateKey;
        }
        
        public static void main(String[] args){
            PEMDemo rsaEncriptDecrypt = new PEMDemo();
            String encrypted;
            try {
                encrypted = rsaEncriptDecrypt.encrypt("This is plain text.", getPublicKey());
                System.out.println("encrypted: " + encrypted);
                
                // JS Encrypted cipher text
                encrypted = "voxgNKCtKy6wGL/g9oi/jUqwm4lnT+Ais4ZaJ5OwJ4gozjTHl3L7yabB04tyV9UmuxfGb6EywZvrpuZRIKtqWPzO+UgW0A+5g9nPjXtDPI0qMzuv7i1E7WVjM4isJBwOC4yPdttXi4h/vbzOaR5J5r8mbyHdnxkqtuDn3o5jXOM=";
                
                String decrypted = rsaEncriptDecrypt.decrypt(encrypted, getPrivateKey());
                System.out.println("decrypted: " + decrypted);
                
                
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            
        }
    }
  1. 从 .PEM 文件中读取公钥和私钥的实用程序类

package com.demo.rsa;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    
    import org.bouncycastle.util.io.pem.PemObject;
    import org.bouncycastle.util.io.pem.PemReader;
    
    import com.demo.util.CommonProperties;
    
    public class BouncyCastlePemUtils {
    
        public static RSAPublicKey readX509PublicKey(File file) throws InvalidKeySpecException, IOException, NoSuchAlgorithmException {
            KeyFactory factory = KeyFactory.getInstance("RSA");
    
            try (FileReader keyReader = new FileReader(file);
                 PemReader pemReader = new PemReader(keyReader)) {
    
                PemObject pemObject = pemReader.readPemObject();
                byte[] content = pemObject.getContent();
                X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
                return (RSAPublicKey) factory.generatePublic(pubKeySpec);
            }
        }
    
        public static RSAPrivateKey readPKCS8PrivateKey(File file) throws InvalidKeySpecException, IOException, NoSuchAlgorithmException {
            KeyFactory factory = KeyFactory.getInstance("RSA");
    
            try (FileReader keyReader = new FileReader(file);
                 PemReader pemReader = new PemReader(keyReader)) {
    
                PemObject pemObject = pemReader.readPemObject();
                byte[] content = pemObject.getContent();
                PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
                return (RSAPrivateKey) factory.generatePrivate(privKeySpec);
            }
        }
        
        public static String readPublicKey() throws IOException {
            File publicKeyFile = new File(CommonProperties.propBag.getProperty("RSA_CONFIG_PATH")+"public_key.pem");
            StringBuilder st = new StringBuilder();
            try (BufferedReader br = new BufferedReader(new FileReader(publicKeyFile))){
                 String s = st.toString();
                  while ((s = br.readLine()) != null)
                      st.append(s);
            }
            return st.toString();
        }
    }
  1. Maven 依赖:

6. Maven Dependancy:
<dependency>
             <groupId>org.bouncycastle</groupId>
             <artifactId>bcpkix-jdk15on</artifactId>
             <version>${bouncycastle.version}</version>
    </dependency>

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2015-01-06
    • 1970-01-01
    • 2017-07-26
    • 2019-02-26
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多