Uncaught TypeError: Cannot read property 'encrypt' of undefined

Uncaught TypeError: Cannot read property 'encrypt' of undefined

我想在 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>

出现错误:未捕获类型错误:无法读取未定义的 属性 'encrypt'。

是否有人知道解决方案或有帮助的示例?

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

  1. 我换了库,用了jsencrypt.min.jsJSEncrypt 更新后支持OAEP padding
  2. Java脚本代码:

<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生成Public和私钥,请查看下面的link命令。

openssl commands

  1. JavaClass加密解密数据:

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. 实用程序 class 从 .PEM 文件中读取 Public 和私钥

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>